babylon.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /**
  1460. * Constant used to convert a value to gamma space
  1461. * @ignorenaming
  1462. */
  1463. BABYLON.ToGammaSpace = 1 / 2.2;
  1464. /**
  1465. * Constant used to convert a value to linear space
  1466. * @ignorenaming
  1467. */
  1468. BABYLON.ToLinearSpace = 2.2;
  1469. /**
  1470. * Constant used to define the minimal number value in Babylon.js
  1471. * @ignorenaming
  1472. */
  1473. BABYLON.Epsilon = 0.001;
  1474. /**
  1475. * Class used to hold a RBG color
  1476. */
  1477. var Color3 = /** @class */ (function () {
  1478. /**
  1479. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1480. * @param r defines the red component (between 0 and 1, default is 0)
  1481. * @param g defines the green component (between 0 and 1, default is 0)
  1482. * @param b defines the blue component (between 0 and 1, default is 0)
  1483. */
  1484. function Color3(
  1485. /**
  1486. * Defines the red component (between 0 and 1, default is 0)
  1487. */
  1488. r,
  1489. /**
  1490. * Defines the green component (between 0 and 1, default is 0)
  1491. */
  1492. g,
  1493. /**
  1494. * Defines the blue component (between 0 and 1, default is 0)
  1495. */
  1496. b) {
  1497. if (r === void 0) { r = 0; }
  1498. if (g === void 0) { g = 0; }
  1499. if (b === void 0) { b = 0; }
  1500. this.r = r;
  1501. this.g = g;
  1502. this.b = b;
  1503. }
  1504. /**
  1505. * Creates a string with the Color3 current values
  1506. * @returns the string representation of the Color3 object
  1507. */
  1508. Color3.prototype.toString = function () {
  1509. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1510. };
  1511. /**
  1512. * Returns the string "Color3"
  1513. * @returns "Color3"
  1514. */
  1515. Color3.prototype.getClassName = function () {
  1516. return "Color3";
  1517. };
  1518. /**
  1519. * Compute the Color3 hash code
  1520. * @returns an unique number that can be used to hash Color3 objects
  1521. */
  1522. Color3.prototype.getHashCode = function () {
  1523. var hash = this.r || 0;
  1524. hash = (hash * 397) ^ (this.g || 0);
  1525. hash = (hash * 397) ^ (this.b || 0);
  1526. return hash;
  1527. };
  1528. // Operators
  1529. /**
  1530. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1531. * @param array defines the array where to store the r,g,b components
  1532. * @param index defines an optional index in the target array to define where to start storing values
  1533. * @returns the current Color3 object
  1534. */
  1535. Color3.prototype.toArray = function (array, index) {
  1536. if (index === undefined) {
  1537. index = 0;
  1538. }
  1539. array[index] = this.r;
  1540. array[index + 1] = this.g;
  1541. array[index + 2] = this.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1546. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1547. * @returns a new {BABYLON.Color4} object
  1548. */
  1549. Color3.prototype.toColor4 = function (alpha) {
  1550. if (alpha === void 0) { alpha = 1; }
  1551. return new Color4(this.r, this.g, this.b, alpha);
  1552. };
  1553. /**
  1554. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1555. * @returns the new array
  1556. */
  1557. Color3.prototype.asArray = function () {
  1558. var result = new Array();
  1559. this.toArray(result, 0);
  1560. return result;
  1561. };
  1562. /**
  1563. * Returns the luminance value
  1564. * @returns a float value
  1565. */
  1566. Color3.prototype.toLuminance = function () {
  1567. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1568. };
  1569. /**
  1570. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3 object
  1573. */
  1574. Color3.prototype.multiply = function (otherColor) {
  1575. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1576. };
  1577. /**
  1578. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the current Color3
  1582. */
  1583. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1584. result.r = this.r * otherColor.r;
  1585. result.g = this.g * otherColor.g;
  1586. result.b = this.b * otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Determines equality between Color3 objects
  1591. * @param otherColor defines the second operand
  1592. * @returns true if the rgb values are equal to the given ones
  1593. */
  1594. Color3.prototype.equals = function (otherColor) {
  1595. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1596. };
  1597. /**
  1598. * Determines equality between the current Color3 object and a set of r,b,g values
  1599. * @param r defines the red component to check
  1600. * @param g defines the green component to check
  1601. * @param b defines the blue component to check
  1602. * @returns true if the rgb values are equal to the given ones
  1603. */
  1604. Color3.prototype.equalsFloats = function (r, g, b) {
  1605. return this.r === r && this.g === g && this.b === b;
  1606. };
  1607. /**
  1608. * Multiplies in place each rgb value by scale
  1609. * @param scale defines the scaling factor
  1610. * @returns the updated Color3
  1611. */
  1612. Color3.prototype.scale = function (scale) {
  1613. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1614. };
  1615. /**
  1616. * Multiplies the rgb values by scale and stores the result into "result"
  1617. * @param scale defines the scaling factor
  1618. * @param result defines the Color3 object where to store the result
  1619. * @returns the unmodified current Color3
  1620. */
  1621. Color3.prototype.scaleToRef = function (scale, result) {
  1622. result.r = this.r * scale;
  1623. result.g = this.g * scale;
  1624. result.b = this.b * scale;
  1625. return this;
  1626. };
  1627. /**
  1628. * Scale the current Color3 values by a factor and add the result to a given Color3
  1629. * @param scale defines the scale factor
  1630. * @param result defines color to store the result into
  1631. * @returns the unmodified current Color3
  1632. */
  1633. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1634. result.r += this.r * scale;
  1635. result.g += this.g * scale;
  1636. result.b += this.b * scale;
  1637. return this;
  1638. };
  1639. /**
  1640. * Clamps the rgb values by the min and max values and stores the result into "result"
  1641. * @param min defines minimum clamping value (default is 0)
  1642. * @param max defines maximum clamping value (default is 1)
  1643. * @param result defines color to store the result into
  1644. * @returns the original Color3
  1645. */
  1646. Color3.prototype.clampToRef = function (min, max, result) {
  1647. if (min === void 0) { min = 0; }
  1648. if (max === void 0) { max = 1; }
  1649. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1650. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1651. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1652. return this;
  1653. };
  1654. /**
  1655. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1656. * @param otherColor defines the second operand
  1657. * @returns the new Color3
  1658. */
  1659. Color3.prototype.add = function (otherColor) {
  1660. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1661. };
  1662. /**
  1663. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1664. * @param otherColor defines the second operand
  1665. * @param result defines Color3 object to store the result into
  1666. * @returns the unmodified current Color3
  1667. */
  1668. Color3.prototype.addToRef = function (otherColor, result) {
  1669. result.r = this.r + otherColor.r;
  1670. result.g = this.g + otherColor.g;
  1671. result.b = this.b + otherColor.b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.subtract = function (otherColor) {
  1680. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.subtractToRef = function (otherColor, result) {
  1689. result.r = this.r - otherColor.r;
  1690. result.g = this.g - otherColor.g;
  1691. result.b = this.b - otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Copy the current object
  1696. * @returns a new Color3 copied the current one
  1697. */
  1698. Color3.prototype.clone = function () {
  1699. return new Color3(this.r, this.g, this.b);
  1700. };
  1701. /**
  1702. * Copies the rgb values from the source in the current Color3
  1703. * @param source defines the source Color3 object
  1704. * @returns the updated Color3 object
  1705. */
  1706. Color3.prototype.copyFrom = function (source) {
  1707. this.r = source.r;
  1708. this.g = source.g;
  1709. this.b = source.b;
  1710. return this;
  1711. };
  1712. /**
  1713. * Updates the Color3 rgb values from the given floats
  1714. * @param r defines the red component to read from
  1715. * @param g defines the green component to read from
  1716. * @param b defines the blue component to read from
  1717. * @returns the current Color3 object
  1718. */
  1719. Color3.prototype.copyFromFloats = function (r, g, b) {
  1720. this.r = r;
  1721. this.g = g;
  1722. this.b = b;
  1723. return this;
  1724. };
  1725. /**
  1726. * Updates the Color3 rgb values from the given floats
  1727. * @param r defines the red component to read from
  1728. * @param g defines the green component to read from
  1729. * @param b defines the blue component to read from
  1730. * @returns the current Color3 object
  1731. */
  1732. Color3.prototype.set = function (r, g, b) {
  1733. return this.copyFromFloats(r, g, b);
  1734. };
  1735. /**
  1736. * Compute the Color3 hexadecimal code as a string
  1737. * @returns a string containing the hexadecimal representation of the Color3 object
  1738. */
  1739. Color3.prototype.toHexString = function () {
  1740. var intR = (this.r * 255) | 0;
  1741. var intG = (this.g * 255) | 0;
  1742. var intB = (this.b * 255) | 0;
  1743. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1744. };
  1745. /**
  1746. * Computes a new Color3 converted from the current one to linear space
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.prototype.toLinearSpace = function () {
  1750. var convertedColor = new Color3();
  1751. this.toLinearSpaceToRef(convertedColor);
  1752. return convertedColor;
  1753. };
  1754. /**
  1755. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1756. * @param convertedColor defines the Color3 object where to store the linear space version
  1757. * @returns the unmodified Color3
  1758. */
  1759. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1760. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1761. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1762. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1763. return this;
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to gamma space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toGammaSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toGammaSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the gamma space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1783. return this;
  1784. };
  1785. // Statics
  1786. /**
  1787. * Creates a new Color3 from the string containing valid hexadecimal values
  1788. * @param hex defines a string containing valid hexadecimal values
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.FromHexString = function (hex) {
  1792. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1793. return new Color3(0, 0, 0);
  1794. }
  1795. var r = parseInt(hex.substring(1, 3), 16);
  1796. var g = parseInt(hex.substring(3, 5), 16);
  1797. var b = parseInt(hex.substring(5, 7), 16);
  1798. return Color3.FromInts(r, g, b);
  1799. };
  1800. /**
  1801. * Creates a new Vector3 from the starting index of the given array
  1802. * @param array defines the source array
  1803. * @param offset defines an offset in the source array
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1809. };
  1810. /**
  1811. * Creates a new Color3 from integer values (< 256)
  1812. * @param r defines the red component to read from (value between 0 and 255)
  1813. * @param g defines the green component to read from (value between 0 and 255)
  1814. * @param b defines the blue component to read from (value between 0 and 255)
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.FromInts = function (r, g, b) {
  1818. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1819. };
  1820. /**
  1821. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1822. * @param start defines the start Color3 value
  1823. * @param end defines the end Color3 value
  1824. * @param amount defines the gradient value between start and end
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Lerp = function (start, end, amount) {
  1828. var result = new Color3(0.0, 0.0, 0.0);
  1829. Color3.LerpToRef(start, end, amount, result);
  1830. return result;
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param left defines the start value
  1835. * @param right defines the end value
  1836. * @param amount defines the gradient factor
  1837. * @param result defines the Color3 object where to store the result
  1838. */
  1839. Color3.LerpToRef = function (left, right, amount, result) {
  1840. result.r = left.r + ((right.r - left.r) * amount);
  1841. result.g = left.g + ((right.g - left.g) * amount);
  1842. result.b = left.b + ((right.b - left.b) * amount);
  1843. };
  1844. /**
  1845. * Returns a Color3 value containing a red color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Red = function () { return new Color3(1, 0, 0); };
  1849. /**
  1850. * Returns a Color3 value containing a green color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Green = function () { return new Color3(0, 1, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a blue color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a black color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Black = function () { return new Color3(0, 0, 0); };
  1864. /**
  1865. * Returns a Color3 value containing a white color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.White = function () { return new Color3(1, 1, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a purple color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1874. /**
  1875. * Returns a Color3 value containing a magenta color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1879. /**
  1880. * Returns a Color3 value containing a yellow color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a gray color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1889. /**
  1890. * Returns a Color3 value containing a teal color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1894. /**
  1895. * Returns a Color3 value containing a random color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1899. return Color3;
  1900. }());
  1901. BABYLON.Color3 = Color3;
  1902. /**
  1903. * Class used to hold a RBGA color
  1904. */
  1905. var Color4 = /** @class */ (function () {
  1906. /**
  1907. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1908. * @param r defines the red component (between 0 and 1, default is 0)
  1909. * @param g defines the green component (between 0 and 1, default is 0)
  1910. * @param b defines the blue component (between 0 and 1, default is 0)
  1911. * @param a defines the alpha component (between 0 and 1, default is 1)
  1912. */
  1913. function Color4(
  1914. /**
  1915. * Defines the red component (between 0 and 1, default is 0)
  1916. */
  1917. r,
  1918. /**
  1919. * Defines the green component (between 0 and 1, default is 0)
  1920. */
  1921. g,
  1922. /**
  1923. * Defines the blue component (between 0 and 1, default is 0)
  1924. */
  1925. b,
  1926. /**
  1927. * Defines the alpha component (between 0 and 1, default is 1)
  1928. */
  1929. a) {
  1930. if (r === void 0) { r = 0; }
  1931. if (g === void 0) { g = 0; }
  1932. if (b === void 0) { b = 0; }
  1933. if (a === void 0) { a = 1; }
  1934. this.r = r;
  1935. this.g = g;
  1936. this.b = b;
  1937. this.a = a;
  1938. }
  1939. // Operators
  1940. /**
  1941. * Adds in place the given Color4 values to the current Color4 object
  1942. * @param right defines the second operand
  1943. * @returns the current updated Color4 object
  1944. */
  1945. Color4.prototype.addInPlace = function (right) {
  1946. this.r += right.r;
  1947. this.g += right.g;
  1948. this.b += right.b;
  1949. this.a += right.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1954. * @returns the new array
  1955. */
  1956. Color4.prototype.asArray = function () {
  1957. var result = new Array();
  1958. this.toArray(result, 0);
  1959. return result;
  1960. };
  1961. /**
  1962. * Stores from the starting index in the given array the Color4 successive values
  1963. * @param array defines the array where to store the r,g,b components
  1964. * @param index defines an optional index in the target array to define where to start storing values
  1965. * @returns the current Color4 object
  1966. */
  1967. Color4.prototype.toArray = function (array, index) {
  1968. if (index === undefined) {
  1969. index = 0;
  1970. }
  1971. array[index] = this.r;
  1972. array[index + 1] = this.g;
  1973. array[index + 2] = this.b;
  1974. array[index + 3] = this.a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1979. * @param right defines the second operand
  1980. * @returns a new Color4 object
  1981. */
  1982. Color4.prototype.add = function (right) {
  1983. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1984. };
  1985. /**
  1986. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1987. * @param right defines the second operand
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.subtract = function (right) {
  1991. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1992. };
  1993. /**
  1994. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1995. * @param right defines the second operand
  1996. * @param result defines the Color4 object where to store the result
  1997. * @returns the current Color4 object
  1998. */
  1999. Color4.prototype.subtractToRef = function (right, result) {
  2000. result.r = this.r - right.r;
  2001. result.g = this.g - right.g;
  2002. result.b = this.b - right.b;
  2003. result.a = this.a - right.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Creates a new Color4 with the current Color4 values multiplied by scale
  2008. * @param scale defines the scaling factor to apply
  2009. * @returns a new Color4 object
  2010. */
  2011. Color4.prototype.scale = function (scale) {
  2012. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2013. };
  2014. /**
  2015. * Multiplies the current Color4 values by scale and stores the result in "result"
  2016. * @param scale defines the scaling factor to apply
  2017. * @param result defines the Color4 object where to store the result
  2018. * @returns the current unmodified Color4
  2019. */
  2020. Color4.prototype.scaleToRef = function (scale, result) {
  2021. result.r = this.r * scale;
  2022. result.g = this.g * scale;
  2023. result.b = this.b * scale;
  2024. result.a = this.a * scale;
  2025. return this;
  2026. };
  2027. /**
  2028. * Scale the current Color4 values by a factor and add the result to a given Color4
  2029. * @param scale defines the scale factor
  2030. * @param result defines the Color4 object where to store the result
  2031. * @returns the unmodified current Color4
  2032. */
  2033. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2034. result.r += this.r * scale;
  2035. result.g += this.g * scale;
  2036. result.b += this.b * scale;
  2037. result.a += this.a * scale;
  2038. return this;
  2039. };
  2040. /**
  2041. * Clamps the rgb values by the min and max values and stores the result into "result"
  2042. * @param min defines minimum clamping value (default is 0)
  2043. * @param max defines maximum clamping value (default is 1)
  2044. * @param result defines color to store the result into.
  2045. * @returns the cuurent Color4
  2046. */
  2047. Color4.prototype.clampToRef = function (min, max, result) {
  2048. if (min === void 0) { min = 0; }
  2049. if (max === void 0) { max = 1; }
  2050. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2051. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2052. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2053. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2054. return this;
  2055. };
  2056. /**
  2057. * Multipy an Color4 value by another and return a new Color4 object
  2058. * @param color defines the Color4 value to multiply by
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.multiply = function (color) {
  2062. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2063. };
  2064. /**
  2065. * Multipy a Color4 value by another and push the result in a reference value
  2066. * @param color defines the Color4 value to multiply by
  2067. * @param result defines the Color4 to fill the result in
  2068. * @returns the result Color4
  2069. */
  2070. Color4.prototype.multiplyToRef = function (color, result) {
  2071. result.r = this.r * color.r;
  2072. result.g = this.g * color.g;
  2073. result.b = this.b * color.b;
  2074. result.a = this.a * color.a;
  2075. return result;
  2076. };
  2077. /**
  2078. * Creates a string with the Color4 current values
  2079. * @returns the string representation of the Color4 object
  2080. */
  2081. Color4.prototype.toString = function () {
  2082. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2083. };
  2084. /**
  2085. * Returns the string "Color4"
  2086. * @returns "Color4"
  2087. */
  2088. Color4.prototype.getClassName = function () {
  2089. return "Color4";
  2090. };
  2091. /**
  2092. * Compute the Color4 hash code
  2093. * @returns an unique number that can be used to hash Color4 objects
  2094. */
  2095. Color4.prototype.getHashCode = function () {
  2096. var hash = this.r || 0;
  2097. hash = (hash * 397) ^ (this.g || 0);
  2098. hash = (hash * 397) ^ (this.b || 0);
  2099. hash = (hash * 397) ^ (this.a || 0);
  2100. return hash;
  2101. };
  2102. /**
  2103. * Creates a new Color4 copied from the current one
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.prototype.clone = function () {
  2107. return new Color4(this.r, this.g, this.b, this.a);
  2108. };
  2109. /**
  2110. * Copies the given Color4 values into the current one
  2111. * @param source defines the source Color4 object
  2112. * @returns the current updated Color4 object
  2113. */
  2114. Color4.prototype.copyFrom = function (source) {
  2115. this.r = source.r;
  2116. this.g = source.g;
  2117. this.b = source.b;
  2118. this.a = source.a;
  2119. return this;
  2120. };
  2121. /**
  2122. * Copies the given float values into the current one
  2123. * @param r defines the red component to read from
  2124. * @param g defines the green component to read from
  2125. * @param b defines the blue component to read from
  2126. * @param a defines the alpha component to read from
  2127. * @returns the current updated Color4 object
  2128. */
  2129. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2130. this.r = r;
  2131. this.g = g;
  2132. this.b = b;
  2133. this.a = a;
  2134. return this;
  2135. };
  2136. /**
  2137. * Copies the given float values into the current one
  2138. * @param r defines the red component to read from
  2139. * @param g defines the green component to read from
  2140. * @param b defines the blue component to read from
  2141. * @param a defines the alpha component to read from
  2142. * @returns the current updated Color4 object
  2143. */
  2144. Color4.prototype.set = function (r, g, b, a) {
  2145. return this.copyFromFloats(r, g, b, a);
  2146. };
  2147. /**
  2148. * Compute the Color4 hexadecimal code as a string
  2149. * @returns a string containing the hexadecimal representation of the Color4 object
  2150. */
  2151. Color4.prototype.toHexString = function () {
  2152. var intR = (this.r * 255) | 0;
  2153. var intG = (this.g * 255) | 0;
  2154. var intB = (this.b * 255) | 0;
  2155. var intA = (this.a * 255) | 0;
  2156. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2157. };
  2158. /**
  2159. * Computes a new Color4 converted from the current one to linear space
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.prototype.toLinearSpace = function () {
  2163. var convertedColor = new Color4();
  2164. this.toLinearSpaceToRef(convertedColor);
  2165. return convertedColor;
  2166. };
  2167. /**
  2168. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2169. * @param convertedColor defines the Color4 object where to store the linear space version
  2170. * @returns the unmodified Color4
  2171. */
  2172. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2173. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2174. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2175. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2176. convertedColor.a = this.a;
  2177. return this;
  2178. };
  2179. /**
  2180. * Computes a new Color4 converted from the current one to gamma space
  2181. * @returns a new Color4 object
  2182. */
  2183. Color4.prototype.toGammaSpace = function () {
  2184. var convertedColor = new Color4();
  2185. this.toGammaSpaceToRef(convertedColor);
  2186. return convertedColor;
  2187. };
  2188. /**
  2189. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2190. * @param convertedColor defines the Color4 object where to store the gamma space version
  2191. * @returns the unmodified Color4
  2192. */
  2193. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2194. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2195. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2196. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2197. convertedColor.a = this.a;
  2198. return this;
  2199. };
  2200. // Statics
  2201. /**
  2202. * Creates a new Color4 from the string containing valid hexadecimal values
  2203. * @param hex defines a string containing valid hexadecimal values
  2204. * @returns a new Color4 object
  2205. */
  2206. Color4.FromHexString = function (hex) {
  2207. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2208. return new Color4(0.0, 0.0, 0.0, 0.0);
  2209. }
  2210. var r = parseInt(hex.substring(1, 3), 16);
  2211. var g = parseInt(hex.substring(3, 5), 16);
  2212. var b = parseInt(hex.substring(5, 7), 16);
  2213. var a = parseInt(hex.substring(7, 9), 16);
  2214. return Color4.FromInts(r, g, b, a);
  2215. };
  2216. /**
  2217. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @returns a new Color4 object
  2222. */
  2223. Color4.Lerp = function (left, right, amount) {
  2224. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2225. Color4.LerpToRef(left, right, amount, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2230. * @param left defines the start value
  2231. * @param right defines the end value
  2232. * @param amount defines the gradient factor
  2233. * @param result defines the Color4 object where to store data
  2234. */
  2235. Color4.LerpToRef = function (left, right, amount, result) {
  2236. result.r = left.r + (right.r - left.r) * amount;
  2237. result.g = left.g + (right.g - left.g) * amount;
  2238. result.b = left.b + (right.b - left.b) * amount;
  2239. result.a = left.a + (right.a - left.a) * amount;
  2240. };
  2241. /**
  2242. * Creates a new Color4 from a Color3 and an alpha value
  2243. * @param color3 defines the source Color3 to read from
  2244. * @param alpha defines the alpha component (1.0 by default)
  2245. * @returns a new Color4 object
  2246. */
  2247. Color4.FromColor3 = function (color3, alpha) {
  2248. if (alpha === void 0) { alpha = 1.0; }
  2249. return new Color4(color3.r, color3.g, color3.b, alpha);
  2250. };
  2251. /**
  2252. * Creates a new Color4 from the starting index element of the given array
  2253. * @param array defines the source array to read from
  2254. * @param offset defines the offset in the source array
  2255. * @returns a new Color4 object
  2256. */
  2257. Color4.FromArray = function (array, offset) {
  2258. if (offset === void 0) { offset = 0; }
  2259. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2260. };
  2261. /**
  2262. * Creates a new Color3 from integer values (< 256)
  2263. * @param r defines the red component to read from (value between 0 and 255)
  2264. * @param g defines the green component to read from (value between 0 and 255)
  2265. * @param b defines the blue component to read from (value between 0 and 255)
  2266. * @param a defines the alpha component to read from (value between 0 and 255)
  2267. * @returns a new Color3 object
  2268. */
  2269. Color4.FromInts = function (r, g, b, a) {
  2270. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2271. };
  2272. /**
  2273. * Check the content of a given array and convert it to an array containing RGBA data
  2274. * If the original array was already containing count * 4 values then it is returned directly
  2275. * @param colors defines the array to check
  2276. * @param count defines the number of RGBA data to expect
  2277. * @returns an array containing count * 4 values (RGBA)
  2278. */
  2279. Color4.CheckColors4 = function (colors, count) {
  2280. // Check if color3 was used
  2281. if (colors.length === count * 3) {
  2282. var colors4 = [];
  2283. for (var index = 0; index < colors.length; index += 3) {
  2284. var newIndex = (index / 3) * 4;
  2285. colors4[newIndex] = colors[index];
  2286. colors4[newIndex + 1] = colors[index + 1];
  2287. colors4[newIndex + 2] = colors[index + 2];
  2288. colors4[newIndex + 3] = 1.0;
  2289. }
  2290. return colors4;
  2291. }
  2292. return colors;
  2293. };
  2294. return Color4;
  2295. }());
  2296. BABYLON.Color4 = Color4;
  2297. /**
  2298. * Class representing a vector containing 2 coordinates
  2299. */
  2300. var Vector2 = /** @class */ (function () {
  2301. /**
  2302. * Creates a new Vector2 from the given x and y coordinates
  2303. * @param x defines the first coordinate
  2304. * @param y defines the second coordinate
  2305. */
  2306. function Vector2(
  2307. /** defines the first coordinate */
  2308. x,
  2309. /** defines the second coordinate */
  2310. y) {
  2311. if (x === void 0) { x = 0; }
  2312. if (y === void 0) { y = 0; }
  2313. this.x = x;
  2314. this.y = y;
  2315. }
  2316. /**
  2317. * Gets a string with the Vector2 coordinates
  2318. * @returns a string with the Vector2 coordinates
  2319. */
  2320. Vector2.prototype.toString = function () {
  2321. return "{X: " + this.x + " Y:" + this.y + "}";
  2322. };
  2323. /**
  2324. * Gets class name
  2325. * @returns the string "Vector2"
  2326. */
  2327. Vector2.prototype.getClassName = function () {
  2328. return "Vector2";
  2329. };
  2330. /**
  2331. * Gets current vector hash code
  2332. * @returns the Vector2 hash code as a number
  2333. */
  2334. Vector2.prototype.getHashCode = function () {
  2335. var hash = this.x || 0;
  2336. hash = (hash * 397) ^ (this.y || 0);
  2337. return hash;
  2338. };
  2339. // Operators
  2340. /**
  2341. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2342. * @param array defines the source array
  2343. * @param index defines the offset in source array
  2344. * @returns the current Vector2
  2345. */
  2346. Vector2.prototype.toArray = function (array, index) {
  2347. if (index === void 0) { index = 0; }
  2348. array[index] = this.x;
  2349. array[index + 1] = this.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Copy the current vector to an array
  2354. * @returns a new array with 2 elements: the Vector2 coordinates.
  2355. */
  2356. Vector2.prototype.asArray = function () {
  2357. var result = new Array();
  2358. this.toArray(result, 0);
  2359. return result;
  2360. };
  2361. /**
  2362. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2363. * @param source defines the source Vector2
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.copyFrom = function (source) {
  2367. this.x = source.x;
  2368. this.y = source.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Sets the Vector2 coordinates with the given floats
  2373. * @param x defines the first coordinate
  2374. * @param y defines the second coordinate
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.copyFromFloats = function (x, y) {
  2378. this.x = x;
  2379. this.y = y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Sets the Vector2 coordinates with the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.set = function (x, y) {
  2389. return this.copyFromFloats(x, y);
  2390. };
  2391. /**
  2392. * Add another vector with the current one
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2395. */
  2396. Vector2.prototype.add = function (otherVector) {
  2397. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.addToRef = function (otherVector, result) {
  2406. result.x = this.x + otherVector.x;
  2407. result.y = this.y + otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.addInPlace = function (otherVector) {
  2416. this.x += otherVector.x;
  2417. this.y += otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.addVector3 = function (otherVector) {
  2426. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2427. };
  2428. /**
  2429. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2430. * @param otherVector defines the other vector
  2431. * @returns a new Vector2
  2432. */
  2433. Vector2.prototype.subtract = function (otherVector) {
  2434. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2435. };
  2436. /**
  2437. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2438. * @param otherVector defines the other vector
  2439. * @param result defines the target vector
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2443. result.x = this.x - otherVector.x;
  2444. result.y = this.y - otherVector.y;
  2445. return this;
  2446. };
  2447. /**
  2448. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns the current updated Vector2
  2451. */
  2452. Vector2.prototype.subtractInPlace = function (otherVector) {
  2453. this.x -= otherVector.x;
  2454. this.y -= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Multiplies in place the current Vector2 coordinates by the given ones
  2459. * @param otherVector defines the other vector
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2463. this.x *= otherVector.x;
  2464. this.y *= otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2469. * @param otherVector defines the other vector
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.multiply = function (otherVector) {
  2473. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2474. };
  2475. /**
  2476. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2477. * @param otherVector defines the other vector
  2478. * @param result defines the target vector
  2479. * @returns the unmodified current Vector2
  2480. */
  2481. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2482. result.x = this.x * otherVector.x;
  2483. result.y = this.y * otherVector.y;
  2484. return this;
  2485. };
  2486. /**
  2487. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2488. * @param x defines the first coordinate
  2489. * @param y defines the second coordinate
  2490. * @returns a new Vector2
  2491. */
  2492. Vector2.prototype.multiplyByFloats = function (x, y) {
  2493. return new Vector2(this.x * x, this.y * y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2497. * @param otherVector defines the other vector
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.divide = function (otherVector) {
  2501. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2502. };
  2503. /**
  2504. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2505. * @param otherVector defines the other vector
  2506. * @param result defines the target vector
  2507. * @returns the unmodified current Vector2
  2508. */
  2509. Vector2.prototype.divideToRef = function (otherVector, result) {
  2510. result.x = this.x / otherVector.x;
  2511. result.y = this.y / otherVector.y;
  2512. return this;
  2513. };
  2514. /**
  2515. * Divides the current Vector2 coordinates by the given ones
  2516. * @param otherVector defines the other vector
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.divideInPlace = function (otherVector) {
  2520. return this.divideToRef(otherVector, this);
  2521. };
  2522. /**
  2523. * Gets a new Vector2 with current Vector2 negated coordinates
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.prototype.negate = function () {
  2527. return new Vector2(-this.x, -this.y);
  2528. };
  2529. /**
  2530. * Multiply the Vector2 coordinates by scale
  2531. * @param scale defines the scaling factor
  2532. * @returns the current updated Vector2
  2533. */
  2534. Vector2.prototype.scaleInPlace = function (scale) {
  2535. this.x *= scale;
  2536. this.y *= scale;
  2537. return this;
  2538. };
  2539. /**
  2540. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2541. * @param scale defines the scaling factor
  2542. * @returns a new Vector2
  2543. */
  2544. Vector2.prototype.scale = function (scale) {
  2545. var result = new Vector2(0, 0);
  2546. this.scaleToRef(scale, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Scale the current Vector2 values by a factor to a given Vector2
  2551. * @param scale defines the scale factor
  2552. * @param result defines the Vector2 object where to store the result
  2553. * @returns the unmodified current Vector2
  2554. */
  2555. Vector2.prototype.scaleToRef = function (scale, result) {
  2556. result.x = this.x * scale;
  2557. result.y = this.y * scale;
  2558. return this;
  2559. };
  2560. /**
  2561. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2562. * @param scale defines the scale factor
  2563. * @param result defines the Vector2 object where to store the result
  2564. * @returns the unmodified current Vector2
  2565. */
  2566. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2567. result.x += this.x * scale;
  2568. result.y += this.y * scale;
  2569. return this;
  2570. };
  2571. /**
  2572. * Gets a boolean if two vectors are equals
  2573. * @param otherVector defines the other vector
  2574. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2575. */
  2576. Vector2.prototype.equals = function (otherVector) {
  2577. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2578. };
  2579. /**
  2580. * Gets a boolean if two vectors are equals (using an epsilon value)
  2581. * @param otherVector defines the other vector
  2582. * @param epsilon defines the minimal distance to consider equality
  2583. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2584. */
  2585. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2586. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2587. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2588. };
  2589. /**
  2590. * Gets a new Vector2 from current Vector2 floored values
  2591. * @returns a new Vector2
  2592. */
  2593. Vector2.prototype.floor = function () {
  2594. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2595. };
  2596. /**
  2597. * Gets a new Vector2 from current Vector2 floored values
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.fract = function () {
  2601. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2602. };
  2603. // Properties
  2604. /**
  2605. * Gets the length of the vector
  2606. * @returns the vector length (float)
  2607. */
  2608. Vector2.prototype.length = function () {
  2609. return Math.sqrt(this.x * this.x + this.y * this.y);
  2610. };
  2611. /**
  2612. * Gets the vector squared length
  2613. * @returns the vector squared length (float)
  2614. */
  2615. Vector2.prototype.lengthSquared = function () {
  2616. return (this.x * this.x + this.y * this.y);
  2617. };
  2618. // Methods
  2619. /**
  2620. * Normalize the vector
  2621. * @returns the current updated Vector2
  2622. */
  2623. Vector2.prototype.normalize = function () {
  2624. var len = this.length();
  2625. if (len === 0)
  2626. return this;
  2627. var num = 1.0 / len;
  2628. this.x *= num;
  2629. this.y *= num;
  2630. return this;
  2631. };
  2632. /**
  2633. * Gets a new Vector2 copied from the Vector2
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.prototype.clone = function () {
  2637. return new Vector2(this.x, this.y);
  2638. };
  2639. // Statics
  2640. /**
  2641. * Gets a new Vector2(0, 0)
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Zero = function () {
  2645. return new Vector2(0, 0);
  2646. };
  2647. /**
  2648. * Gets a new Vector2(1, 1)
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.One = function () {
  2652. return new Vector2(1, 1);
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set from the given index element of the given array
  2656. * @param array defines the data source
  2657. * @param offset defines the offset in the data source
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.FromArray = function (array, offset) {
  2661. if (offset === void 0) { offset = 0; }
  2662. return new Vector2(array[offset], array[offset + 1]);
  2663. };
  2664. /**
  2665. * Sets "result" from the given index element of the given array
  2666. * @param array defines the data source
  2667. * @param offset defines the offset in the data source
  2668. * @param result defines the target vector
  2669. */
  2670. Vector2.FromArrayToRef = function (array, offset, result) {
  2671. result.x = array[offset];
  2672. result.y = array[offset + 1];
  2673. };
  2674. /**
  2675. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2676. * @param value1 defines 1st point of control
  2677. * @param value2 defines 2nd point of control
  2678. * @param value3 defines 3rd point of control
  2679. * @param value4 defines 4th point of control
  2680. * @param amount defines the interpolation factor
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2684. var squared = amount * amount;
  2685. var cubed = amount * squared;
  2686. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2687. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2688. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2689. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2690. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2691. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2692. return new Vector2(x, y);
  2693. };
  2694. /**
  2695. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2696. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2697. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2698. * @param value defines the value to clamp
  2699. * @param min defines the lower limit
  2700. * @param max defines the upper limit
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Clamp = function (value, min, max) {
  2704. var x = value.x;
  2705. x = (x > max.x) ? max.x : x;
  2706. x = (x < min.x) ? min.x : x;
  2707. var y = value.y;
  2708. y = (y > max.y) ? max.y : y;
  2709. y = (y < min.y) ? min.y : y;
  2710. return new Vector2(x, y);
  2711. };
  2712. /**
  2713. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2714. * @param value1 defines the 1st control point
  2715. * @param tangent1 defines the outgoing tangent
  2716. * @param value2 defines the 2nd control point
  2717. * @param tangent2 defines the incoming tangent
  2718. * @param amount defines the interpolation factor
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2722. var squared = amount * amount;
  2723. var cubed = amount * squared;
  2724. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2725. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2726. var part3 = (cubed - (2.0 * squared)) + amount;
  2727. var part4 = cubed - squared;
  2728. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2729. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2730. return new Vector2(x, y);
  2731. };
  2732. /**
  2733. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2734. * @param start defines the start vector
  2735. * @param end defines the end vector
  2736. * @param amount defines the interpolation factor
  2737. * @returns a new Vector2
  2738. */
  2739. Vector2.Lerp = function (start, end, amount) {
  2740. var x = start.x + ((end.x - start.x) * amount);
  2741. var y = start.y + ((end.y - start.y) * amount);
  2742. return new Vector2(x, y);
  2743. };
  2744. /**
  2745. * Gets the dot product of the vector "left" and the vector "right"
  2746. * @param left defines first vector
  2747. * @param right defines second vector
  2748. * @returns the dot product (float)
  2749. */
  2750. Vector2.Dot = function (left, right) {
  2751. return left.x * right.x + left.y * right.y;
  2752. };
  2753. /**
  2754. * Returns a new Vector2 equal to the normalized given vector
  2755. * @param vector defines the vector to normalize
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Normalize = function (vector) {
  2759. var newVector = vector.clone();
  2760. newVector.normalize();
  2761. return newVector;
  2762. };
  2763. /**
  2764. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2765. * @param left defines 1st vector
  2766. * @param right defines 2nd vector
  2767. * @returns a new Vector2
  2768. */
  2769. Vector2.Minimize = function (left, right) {
  2770. var x = (left.x < right.x) ? left.x : right.x;
  2771. var y = (left.y < right.y) ? left.y : right.y;
  2772. return new Vector2(x, y);
  2773. };
  2774. /**
  2775. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2776. * @param left defines 1st vector
  2777. * @param right defines 2nd vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Maximize = function (left, right) {
  2781. var x = (left.x > right.x) ? left.x : right.x;
  2782. var y = (left.y > right.y) ? left.y : right.y;
  2783. return new Vector2(x, y);
  2784. };
  2785. /**
  2786. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2787. * @param vector defines the vector to transform
  2788. * @param transformation defines the matrix to apply
  2789. * @returns a new Vector2
  2790. */
  2791. Vector2.Transform = function (vector, transformation) {
  2792. var r = Vector2.Zero();
  2793. Vector2.TransformToRef(vector, transformation, r);
  2794. return r;
  2795. };
  2796. /**
  2797. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2798. * @param vector defines the vector to transform
  2799. * @param transformation defines the matrix to apply
  2800. * @param result defines the target vector
  2801. */
  2802. Vector2.TransformToRef = function (vector, transformation, result) {
  2803. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2804. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2805. result.x = x;
  2806. result.y = y;
  2807. };
  2808. /**
  2809. * Determines if a given vector is included in a triangle
  2810. * @param p defines the vector to test
  2811. * @param p0 defines 1st triangle point
  2812. * @param p1 defines 2nd triangle point
  2813. * @param p2 defines 3rd triangle point
  2814. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2815. */
  2816. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2817. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2818. var sign = a < 0 ? -1 : 1;
  2819. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2820. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2821. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2822. };
  2823. /**
  2824. * Gets the distance between the vectors "value1" and "value2"
  2825. * @param value1 defines first vector
  2826. * @param value2 defines second vector
  2827. * @returns the distance between vectors
  2828. */
  2829. Vector2.Distance = function (value1, value2) {
  2830. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2831. };
  2832. /**
  2833. * Returns the squared distance between the vectors "value1" and "value2"
  2834. * @param value1 defines first vector
  2835. * @param value2 defines second vector
  2836. * @returns the squared distance between vectors
  2837. */
  2838. Vector2.DistanceSquared = function (value1, value2) {
  2839. var x = value1.x - value2.x;
  2840. var y = value1.y - value2.y;
  2841. return (x * x) + (y * y);
  2842. };
  2843. /**
  2844. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2845. * @param value1 defines first vector
  2846. * @param value2 defines second vector
  2847. * @returns a new Vector2
  2848. */
  2849. Vector2.Center = function (value1, value2) {
  2850. var center = value1.add(value2);
  2851. center.scaleInPlace(0.5);
  2852. return center;
  2853. };
  2854. /**
  2855. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2856. * @param p defines the middle point
  2857. * @param segA defines one point of the segment
  2858. * @param segB defines the other point of the segment
  2859. * @returns the shortest distance
  2860. */
  2861. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2862. var l2 = Vector2.DistanceSquared(segA, segB);
  2863. if (l2 === 0.0) {
  2864. return Vector2.Distance(p, segA);
  2865. }
  2866. var v = segB.subtract(segA);
  2867. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2868. var proj = segA.add(v.multiplyByFloats(t, t));
  2869. return Vector2.Distance(p, proj);
  2870. };
  2871. return Vector2;
  2872. }());
  2873. BABYLON.Vector2 = Vector2;
  2874. /**
  2875. * Classed used to store (x,y,z) vector representation
  2876. * A Vector3 is the main object used in 3D geometry
  2877. * It can represent etiher the coordinates of a point the space, either a direction
  2878. * Reminder: Babylon.js uses a left handed forward facing system
  2879. */
  2880. var Vector3 = /** @class */ (function () {
  2881. /**
  2882. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2883. * @param x defines the first coordinates (on X axis)
  2884. * @param y defines the second coordinates (on Y axis)
  2885. * @param z defines the third coordinates (on Z axis)
  2886. */
  2887. function Vector3(
  2888. /**
  2889. * Defines the first coordinates (on X axis)
  2890. */
  2891. x,
  2892. /**
  2893. * Defines the second coordinates (on Y axis)
  2894. */
  2895. y,
  2896. /**
  2897. * Defines the third coordinates (on Z axis)
  2898. */
  2899. z) {
  2900. if (x === void 0) { x = 0; }
  2901. if (y === void 0) { y = 0; }
  2902. if (z === void 0) { z = 0; }
  2903. this.x = x;
  2904. this.y = y;
  2905. this.z = z;
  2906. }
  2907. /**
  2908. * Creates a string representation of the Vector3
  2909. * @returns a string with the Vector3 coordinates.
  2910. */
  2911. Vector3.prototype.toString = function () {
  2912. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2913. };
  2914. /**
  2915. * Gets the class name
  2916. * @returns the string "Vector3"
  2917. */
  2918. Vector3.prototype.getClassName = function () {
  2919. return "Vector3";
  2920. };
  2921. /**
  2922. * Creates the Vector3 hash code
  2923. * @returns a number which tends to be unique between Vector3 instances
  2924. */
  2925. Vector3.prototype.getHashCode = function () {
  2926. var hash = this.x || 0;
  2927. hash = (hash * 397) ^ (this.y || 0);
  2928. hash = (hash * 397) ^ (this.z || 0);
  2929. return hash;
  2930. };
  2931. // Operators
  2932. /**
  2933. * Creates an array containing three elements : the coordinates of the Vector3
  2934. * @returns a new array of numbers
  2935. */
  2936. Vector3.prototype.asArray = function () {
  2937. var result = [];
  2938. this.toArray(result, 0);
  2939. return result;
  2940. };
  2941. /**
  2942. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2943. * @param array defines the destination array
  2944. * @param index defines the offset in the destination array
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.toArray = function (array, index) {
  2948. if (index === void 0) { index = 0; }
  2949. array[index] = this.x;
  2950. array[index + 1] = this.y;
  2951. array[index + 2] = this.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2956. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2957. */
  2958. Vector3.prototype.toQuaternion = function () {
  2959. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2960. };
  2961. /**
  2962. * Adds the given vector to the current Vector3
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.addInPlace = function (otherVector) {
  2967. this.x += otherVector.x;
  2968. this.y += otherVector.y;
  2969. this.z += otherVector.z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2974. * @param otherVector defines the second operand
  2975. * @returns the resulting Vector3
  2976. */
  2977. Vector3.prototype.add = function (otherVector) {
  2978. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2979. };
  2980. /**
  2981. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2982. * @param otherVector defines the second operand
  2983. * @param result defines the Vector3 object where to store the result
  2984. * @returns the current Vector3
  2985. */
  2986. Vector3.prototype.addToRef = function (otherVector, result) {
  2987. result.x = this.x + otherVector.x;
  2988. result.y = this.y + otherVector.y;
  2989. result.z = this.z + otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Subtract the given vector from the current Vector3
  2994. * @param otherVector defines the second operand
  2995. * @returns the current updated Vector3
  2996. */
  2997. Vector3.prototype.subtractInPlace = function (otherVector) {
  2998. this.x -= otherVector.x;
  2999. this.y -= otherVector.y;
  3000. this.z -= otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3005. * @param otherVector defines the second operand
  3006. * @returns the resulting Vector3
  3007. */
  3008. Vector3.prototype.subtract = function (otherVector) {
  3009. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3010. };
  3011. /**
  3012. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3013. * @param otherVector defines the second operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3018. result.x = this.x - otherVector.x;
  3019. result.y = this.y - otherVector.y;
  3020. result.z = this.z - otherVector.z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3025. * @param x defines the x coordinate of the operand
  3026. * @param y defines the y coordinate of the operand
  3027. * @param z defines the z coordinate of the operand
  3028. * @returns the resulting Vector3
  3029. */
  3030. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3031. return new Vector3(this.x - x, this.y - y, this.z - z);
  3032. };
  3033. /**
  3034. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3035. * @param x defines the x coordinate of the operand
  3036. * @param y defines the y coordinate of the operand
  3037. * @param z defines the z coordinate of the operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3042. result.x = this.x - x;
  3043. result.y = this.y - y;
  3044. result.z = this.z - z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3049. * @returns a new Vector3
  3050. */
  3051. Vector3.prototype.negate = function () {
  3052. return new Vector3(-this.x, -this.y, -this.z);
  3053. };
  3054. /**
  3055. * Multiplies the Vector3 coordinates by the float "scale"
  3056. * @param scale defines the multiplier factor
  3057. * @returns the current updated Vector3
  3058. */
  3059. Vector3.prototype.scaleInPlace = function (scale) {
  3060. this.x *= scale;
  3061. this.y *= scale;
  3062. this.z *= scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3067. * @param scale defines the multiplier factor
  3068. * @returns a new Vector3
  3069. */
  3070. Vector3.prototype.scale = function (scale) {
  3071. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3072. };
  3073. /**
  3074. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3075. * @param scale defines the multiplier factor
  3076. * @param result defines the Vector3 object where to store the result
  3077. * @returns the current Vector3
  3078. */
  3079. Vector3.prototype.scaleToRef = function (scale, result) {
  3080. result.x = this.x * scale;
  3081. result.y = this.y * scale;
  3082. result.z = this.z * scale;
  3083. return this;
  3084. };
  3085. /**
  3086. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3087. * @param scale defines the scale factor
  3088. * @param result defines the Vector3 object where to store the result
  3089. * @returns the unmodified current Vector3
  3090. */
  3091. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3092. result.x += this.x * scale;
  3093. result.y += this.y * scale;
  3094. result.z += this.z * scale;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3099. * @param otherVector defines the second operand
  3100. * @returns true if both vectors are equals
  3101. */
  3102. Vector3.prototype.equals = function (otherVector) {
  3103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3104. };
  3105. /**
  3106. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3107. * @param otherVector defines the second operand
  3108. * @param epsilon defines the minimal distance to define values as equals
  3109. * @returns true if both vectors are distant less than epsilon
  3110. */
  3111. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3112. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3113. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3114. };
  3115. /**
  3116. * Returns true if the current Vector3 coordinates equals the given floats
  3117. * @param x defines the x coordinate of the operand
  3118. * @param y defines the y coordinate of the operand
  3119. * @param z defines the z coordinate of the operand
  3120. * @returns true if both vectors are equals
  3121. */
  3122. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3123. return this.x === x && this.y === y && this.z === z;
  3124. };
  3125. /**
  3126. * Multiplies the current Vector3 coordinates by the given ones
  3127. * @param otherVector defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3131. this.x *= otherVector.x;
  3132. this.y *= otherVector.y;
  3133. this.z *= otherVector.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3138. * @param otherVector defines the second operand
  3139. * @returns the new Vector3
  3140. */
  3141. Vector3.prototype.multiply = function (otherVector) {
  3142. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3143. };
  3144. /**
  3145. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3146. * @param otherVector defines the second operand
  3147. * @param result defines the Vector3 object where to store the result
  3148. * @returns the current Vector3
  3149. */
  3150. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3151. result.x = this.x * otherVector.x;
  3152. result.y = this.y * otherVector.y;
  3153. result.z = this.z * otherVector.z;
  3154. return this;
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3158. * @param x defines the x coordinate of the operand
  3159. * @param y defines the y coordinate of the operand
  3160. * @param z defines the z coordinate of the operand
  3161. * @returns the new Vector3
  3162. */
  3163. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3164. return new Vector3(this.x * x, this.y * y, this.z * z);
  3165. };
  3166. /**
  3167. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3168. * @param otherVector defines the second operand
  3169. * @returns the new Vector3
  3170. */
  3171. Vector3.prototype.divide = function (otherVector) {
  3172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3173. };
  3174. /**
  3175. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3176. * @param otherVector defines the second operand
  3177. * @param result defines the Vector3 object where to store the result
  3178. * @returns the current Vector3
  3179. */
  3180. Vector3.prototype.divideToRef = function (otherVector, result) {
  3181. result.x = this.x / otherVector.x;
  3182. result.y = this.y / otherVector.y;
  3183. result.z = this.z / otherVector.z;
  3184. return this;
  3185. };
  3186. /**
  3187. * Divides the current Vector3 coordinates by the given ones.
  3188. * @param otherVector defines the second operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.divideInPlace = function (otherVector) {
  3192. return this.divideToRef(otherVector, this);
  3193. };
  3194. /**
  3195. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3196. * @param other defines the second operand
  3197. * @returns the current updated Vector3
  3198. */
  3199. Vector3.prototype.minimizeInPlace = function (other) {
  3200. if (other.x < this.x)
  3201. this.x = other.x;
  3202. if (other.y < this.y)
  3203. this.y = other.y;
  3204. if (other.z < this.z)
  3205. this.z = other.z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3210. * @param other defines the second operand
  3211. * @returns the current updated Vector3
  3212. */
  3213. Vector3.prototype.maximizeInPlace = function (other) {
  3214. if (other.x > this.x)
  3215. this.x = other.x;
  3216. if (other.y > this.y)
  3217. this.y = other.y;
  3218. if (other.z > this.z)
  3219. this.z = other.z;
  3220. return this;
  3221. };
  3222. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3223. /**
  3224. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3225. */
  3226. get: function () {
  3227. var absX = Math.abs(this.x);
  3228. var absY = Math.abs(this.y);
  3229. if (absX !== absY) {
  3230. return true;
  3231. }
  3232. var absZ = Math.abs(this.z);
  3233. if (absX !== absZ) {
  3234. return true;
  3235. }
  3236. if (absY !== absZ) {
  3237. return true;
  3238. }
  3239. return false;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. /**
  3245. * Gets a new Vector3 from current Vector3 floored values
  3246. * @returns a new Vector3
  3247. */
  3248. Vector3.prototype.floor = function () {
  3249. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3250. };
  3251. /**
  3252. * Gets a new Vector3 from current Vector3 floored values
  3253. * @returns a new Vector3
  3254. */
  3255. Vector3.prototype.fract = function () {
  3256. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3257. };
  3258. // Properties
  3259. /**
  3260. * Gets the length of the Vector3
  3261. * @returns the length of the Vecto3
  3262. */
  3263. Vector3.prototype.length = function () {
  3264. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3265. };
  3266. /**
  3267. * Gets the squared length of the Vector3
  3268. * @returns squared length of the Vector3
  3269. */
  3270. Vector3.prototype.lengthSquared = function () {
  3271. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3272. };
  3273. /**
  3274. * Normalize the current Vector3.
  3275. * Please note that this is an in place operation.
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.normalize = function () {
  3279. var len = this.length();
  3280. if (len === 0 || len === 1.0)
  3281. return this;
  3282. var num = 1.0 / len;
  3283. this.x *= num;
  3284. this.y *= num;
  3285. this.z *= num;
  3286. return this;
  3287. };
  3288. /**
  3289. * Normalize the current Vector3 to a new vector
  3290. * @returns the new Vector3
  3291. */
  3292. Vector3.prototype.normalizeToNew = function () {
  3293. var normalized = new Vector3(0, 0, 0);
  3294. this.normalizeToRef(normalized);
  3295. return normalized;
  3296. };
  3297. /**
  3298. * Normalize the current Vector3 to the reference
  3299. * @param reference define the Vector3 to update
  3300. * @returns the updated Vector3
  3301. */
  3302. Vector3.prototype.normalizeToRef = function (reference) {
  3303. var len = this.length();
  3304. if (len === 0 || len === 1.0) {
  3305. reference.set(this.x, this.y, this.z);
  3306. return reference;
  3307. }
  3308. var scale = 1.0 / len;
  3309. this.scaleToRef(scale, reference);
  3310. return reference;
  3311. };
  3312. /**
  3313. * Creates a new Vector3 copied from the current Vector3
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.prototype.clone = function () {
  3317. return new Vector3(this.x, this.y, this.z);
  3318. };
  3319. /**
  3320. * Copies the given vector coordinates to the current Vector3 ones
  3321. * @param source defines the source Vector3
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFrom = function (source) {
  3325. this.x = source.x;
  3326. this.y = source.y;
  3327. this.z = source.z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3338. this.x = x;
  3339. this.y = y;
  3340. this.z = z;
  3341. return this;
  3342. };
  3343. /**
  3344. * Copies the given floats to the current Vector3 coordinates
  3345. * @param x defines the x coordinate of the operand
  3346. * @param y defines the y coordinate of the operand
  3347. * @param z defines the z coordinate of the operand
  3348. * @returns the current updated Vector3
  3349. */
  3350. Vector3.prototype.set = function (x, y, z) {
  3351. return this.copyFromFloats(x, y, z);
  3352. };
  3353. // Statics
  3354. /**
  3355. * Get the clip factor between two vectors
  3356. * @param vector0 defines the first operand
  3357. * @param vector1 defines the second operand
  3358. * @param axis defines the axis to use
  3359. * @param size defines the size along the axis
  3360. * @returns the clip factor
  3361. */
  3362. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3363. var d0 = Vector3.Dot(vector0, axis) - size;
  3364. var d1 = Vector3.Dot(vector1, axis) - size;
  3365. var s = d0 / (d0 - d1);
  3366. return s;
  3367. };
  3368. /**
  3369. * Get angle between two vectors
  3370. * @param vector0 angle between vector0 and vector1
  3371. * @param vector1 angle between vector0 and vector1
  3372. * @param normal direction of the normal
  3373. * @return the angle between vector0 and vector1
  3374. */
  3375. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3376. var v0 = vector0.clone().normalize();
  3377. var v1 = vector1.clone().normalize();
  3378. var dot = Vector3.Dot(v0, v1);
  3379. var n = Vector3.Cross(v0, v1);
  3380. if (Vector3.Dot(n, normal) > 0) {
  3381. return Math.acos(dot);
  3382. }
  3383. return -Math.acos(dot);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set from the index "offset" of the given array
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromArray = function (array, offset) {
  3392. if (!offset) {
  3393. offset = 0;
  3394. }
  3395. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3399. * This function is deprecated. Use FromArray instead
  3400. * @param array defines the source array
  3401. * @param offset defines the offset in the source array
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.FromFloatArray = function (array, offset) {
  3405. return Vector3.FromArray(array, offset);
  3406. };
  3407. /**
  3408. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3409. * @param array defines the source array
  3410. * @param offset defines the offset in the source array
  3411. * @param result defines the Vector3 where to store the result
  3412. */
  3413. Vector3.FromArrayToRef = function (array, offset, result) {
  3414. result.x = array[offset];
  3415. result.y = array[offset + 1];
  3416. result.z = array[offset + 2];
  3417. };
  3418. /**
  3419. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3420. * This function is deprecated. Use FromArrayToRef instead.
  3421. * @param array defines the source array
  3422. * @param offset defines the offset in the source array
  3423. * @param result defines the Vector3 where to store the result
  3424. */
  3425. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3426. return Vector3.FromArrayToRef(array, offset, result);
  3427. };
  3428. /**
  3429. * Sets the given vector "result" with the given floats.
  3430. * @param x defines the x coordinate of the source
  3431. * @param y defines the y coordinate of the source
  3432. * @param z defines the z coordinate of the source
  3433. * @param result defines the Vector3 where to store the result
  3434. */
  3435. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3436. result.x = x;
  3437. result.y = y;
  3438. result.z = z;
  3439. };
  3440. /**
  3441. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3442. * @returns a new empty Vector3
  3443. */
  3444. Vector3.Zero = function () {
  3445. return new Vector3(0.0, 0.0, 0.0);
  3446. };
  3447. /**
  3448. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3449. * @returns a new unit Vector3
  3450. */
  3451. Vector3.One = function () {
  3452. return new Vector3(1.0, 1.0, 1.0);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3456. * @returns a new up Vector3
  3457. */
  3458. Vector3.Up = function () {
  3459. return new Vector3(0.0, 1.0, 0.0);
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3463. * @returns a new down Vector3
  3464. */
  3465. Vector3.Down = function () {
  3466. return new Vector3(0.0, -1.0, 0.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3470. * @returns a new forward Vector3
  3471. */
  3472. Vector3.Forward = function () {
  3473. return new Vector3(0.0, 0.0, 1.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3477. * @returns a new forward Vector3
  3478. */
  3479. Vector3.Backward = function () {
  3480. return new Vector3(0.0, 0.0, -1.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3484. * @returns a new right Vector3
  3485. */
  3486. Vector3.Right = function () {
  3487. return new Vector3(1.0, 0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3491. * @returns a new left Vector3
  3492. */
  3493. Vector3.Left = function () {
  3494. return new Vector3(-1.0, 0.0, 0.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3498. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3499. * @param vector defines the Vector3 to transform
  3500. * @param transformation defines the transformation matrix
  3501. * @returns the transformed Vector3
  3502. */
  3503. Vector3.TransformCoordinates = function (vector, transformation) {
  3504. var result = Vector3.Zero();
  3505. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3510. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3511. * @param vector defines the Vector3 to transform
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3518. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3519. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3520. result.x = x / w;
  3521. result.y = y / w;
  3522. result.z = z / w;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3526. * This method computes tranformed coordinates only, not transformed direction vectors
  3527. * @param x define the x coordinate of the source vector
  3528. * @param y define the y coordinate of the source vector
  3529. * @param z define the z coordinate of the source vector
  3530. * @param transformation defines the transformation matrix
  3531. * @param result defines the Vector3 where to store the result
  3532. */
  3533. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3534. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3535. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3536. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3537. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3538. result.x = rx / rw;
  3539. result.y = ry / rw;
  3540. result.z = rz / rw;
  3541. };
  3542. /**
  3543. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param vector defines the Vector3 to transform
  3546. * @param transformation defines the transformation matrix
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.TransformNormal = function (vector, transformation) {
  3550. var result = Vector3.Zero();
  3551. Vector3.TransformNormalToRef(vector, transformation, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3556. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3557. * @param vector defines the Vector3 to transform
  3558. * @param transformation defines the transformation matrix
  3559. * @param result defines the Vector3 where to store the result
  3560. */
  3561. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3562. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3563. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3564. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3565. result.x = x;
  3566. result.y = y;
  3567. result.z = z;
  3568. };
  3569. /**
  3570. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3571. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3572. * @param x define the x coordinate of the source vector
  3573. * @param y define the y coordinate of the source vector
  3574. * @param z define the z coordinate of the source vector
  3575. * @param transformation defines the transformation matrix
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3579. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3580. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3581. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3582. };
  3583. /**
  3584. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3585. * @param value1 defines the first control point
  3586. * @param value2 defines the second control point
  3587. * @param value3 defines the third control point
  3588. * @param value4 defines the fourth control point
  3589. * @param amount defines the amount on the spline to use
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3593. var squared = amount * amount;
  3594. var cubed = amount * squared;
  3595. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3596. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3597. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3598. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3599. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3600. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3601. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3602. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3603. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3604. return new Vector3(x, y, z);
  3605. };
  3606. /**
  3607. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3608. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3609. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3610. * @param value defines the current value
  3611. * @param min defines the lower range value
  3612. * @param max defines the upper range value
  3613. * @returns the new Vector3
  3614. */
  3615. Vector3.Clamp = function (value, min, max) {
  3616. var x = value.x;
  3617. x = (x > max.x) ? max.x : x;
  3618. x = (x < min.x) ? min.x : x;
  3619. var y = value.y;
  3620. y = (y > max.y) ? max.y : y;
  3621. y = (y < min.y) ? min.y : y;
  3622. var z = value.z;
  3623. z = (z > max.z) ? max.z : z;
  3624. z = (z < min.z) ? min.z : z;
  3625. return new Vector3(x, y, z);
  3626. };
  3627. /**
  3628. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3629. * @param value1 defines the first control point
  3630. * @param tangent1 defines the first tangent vector
  3631. * @param value2 defines the second control point
  3632. * @param tangent2 defines the second tangent vector
  3633. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3634. * @returns the new Vector3
  3635. */
  3636. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3637. var squared = amount * amount;
  3638. var cubed = amount * squared;
  3639. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3640. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3641. var part3 = (cubed - (2.0 * squared)) + amount;
  3642. var part4 = cubed - squared;
  3643. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3644. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3645. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3646. return new Vector3(x, y, z);
  3647. };
  3648. /**
  3649. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3650. * @param start defines the start value
  3651. * @param end defines the end value
  3652. * @param amount max defines amount between both (between 0 and 1)
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Lerp = function (start, end, amount) {
  3656. var result = new Vector3(0, 0, 0);
  3657. Vector3.LerpToRef(start, end, amount, result);
  3658. return result;
  3659. };
  3660. /**
  3661. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3662. * @param start defines the start value
  3663. * @param end defines the end value
  3664. * @param amount max defines amount between both (between 0 and 1)
  3665. * @param result defines the Vector3 where to store the result
  3666. */
  3667. Vector3.LerpToRef = function (start, end, amount, result) {
  3668. result.x = start.x + ((end.x - start.x) * amount);
  3669. result.y = start.y + ((end.y - start.y) * amount);
  3670. result.z = start.z + ((end.z - start.z) * amount);
  3671. };
  3672. /**
  3673. * Returns the dot product (float) between the vectors "left" and "right"
  3674. * @param left defines the left operand
  3675. * @param right defines the right operand
  3676. * @returns the dot product
  3677. */
  3678. Vector3.Dot = function (left, right) {
  3679. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3680. };
  3681. /**
  3682. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3683. * The cross product is then orthogonal to both "left" and "right"
  3684. * @param left defines the left operand
  3685. * @param right defines the right operand
  3686. * @returns the cross product
  3687. */
  3688. Vector3.Cross = function (left, right) {
  3689. var result = Vector3.Zero();
  3690. Vector3.CrossToRef(left, right, result);
  3691. return result;
  3692. };
  3693. /**
  3694. * Sets the given vector "result" with the cross product of "left" and "right"
  3695. * The cross product is then orthogonal to both "left" and "right"
  3696. * @param left defines the left operand
  3697. * @param right defines the right operand
  3698. * @param result defines the Vector3 where to store the result
  3699. */
  3700. Vector3.CrossToRef = function (left, right, result) {
  3701. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3702. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3703. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3704. result.copyFrom(MathTmp.Vector3[0]);
  3705. };
  3706. /**
  3707. * Returns a new Vector3 as the normalization of the given vector
  3708. * @param vector defines the Vector3 to normalize
  3709. * @returns the new Vector3
  3710. */
  3711. Vector3.Normalize = function (vector) {
  3712. var result = Vector3.Zero();
  3713. Vector3.NormalizeToRef(vector, result);
  3714. return result;
  3715. };
  3716. /**
  3717. * Sets the given vector "result" with the normalization of the given first vector
  3718. * @param vector defines the Vector3 to normalize
  3719. * @param result defines the Vector3 where to store the result
  3720. */
  3721. Vector3.NormalizeToRef = function (vector, result) {
  3722. result.copyFrom(vector);
  3723. result.normalize();
  3724. };
  3725. /**
  3726. * Project a Vector3 onto screen space
  3727. * @param vector defines the Vector3 to project
  3728. * @param world defines the world matrix to use
  3729. * @param transform defines the transform (view x projection) matrix to use
  3730. * @param viewport defines the screen viewport to use
  3731. * @returns the new Vector3
  3732. */
  3733. Vector3.Project = function (vector, world, transform, viewport) {
  3734. var cw = viewport.width;
  3735. var ch = viewport.height;
  3736. var cx = viewport.x;
  3737. var cy = viewport.y;
  3738. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3739. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3740. var matrix = MathTmp.Matrix[0];
  3741. world.multiplyToRef(transform, matrix);
  3742. matrix.multiplyToRef(viewportMatrix, matrix);
  3743. return Vector3.TransformCoordinates(vector, matrix);
  3744. };
  3745. /**
  3746. * Unproject from screen space to object space
  3747. * @param source defines the screen space Vector3 to use
  3748. * @param viewportWidth defines the current width of the viewport
  3749. * @param viewportHeight defines the current height of the viewport
  3750. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3751. * @param transform defines the transform (view x projection) matrix to use
  3752. * @returns the new Vector3
  3753. */
  3754. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3755. var matrix = MathTmp.Matrix[0];
  3756. world.multiplyToRef(transform, matrix);
  3757. matrix.invert();
  3758. source.x = source.x / viewportWidth * 2 - 1;
  3759. source.y = -(source.y / viewportHeight * 2 - 1);
  3760. var vector = Vector3.TransformCoordinates(source, matrix);
  3761. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3762. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3763. vector = vector.scale(1.0 / num);
  3764. }
  3765. return vector;
  3766. };
  3767. /**
  3768. * Unproject from screen space to object space
  3769. * @param source defines the screen space Vector3 to use
  3770. * @param viewportWidth defines the current width of the viewport
  3771. * @param viewportHeight defines the current height of the viewport
  3772. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3773. * @param view defines the view matrix to use
  3774. * @param projection defines the projection matrix to use
  3775. * @returns the new Vector3
  3776. */
  3777. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3778. var result = Vector3.Zero();
  3779. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3780. return result;
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param source defines the screen space Vector3 to use
  3785. * @param viewportWidth defines the current width of the viewport
  3786. * @param viewportHeight defines the current height of the viewport
  3787. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3788. * @param view defines the view matrix to use
  3789. * @param projection defines the projection matrix to use
  3790. * @param result defines the Vector3 where to store the result
  3791. */
  3792. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3793. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3794. };
  3795. /**
  3796. * Unproject from screen space to object space
  3797. * @param sourceX defines the screen space x coordinate to use
  3798. * @param sourceY defines the screen space y coordinate to use
  3799. * @param sourceZ defines the screen space z coordinate to use
  3800. * @param viewportWidth defines the current width of the viewport
  3801. * @param viewportHeight defines the current height of the viewport
  3802. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3803. * @param view defines the view matrix to use
  3804. * @param projection defines the projection matrix to use
  3805. * @param result defines the Vector3 where to store the result
  3806. */
  3807. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3808. var matrix = MathTmp.Matrix[0];
  3809. world.multiplyToRef(view, matrix);
  3810. matrix.multiplyToRef(projection, matrix);
  3811. matrix.invert();
  3812. var screenSource = MathTmp.Vector3[0];
  3813. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3814. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3815. screenSource.z = 2 * sourceZ - 1.0;
  3816. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3817. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3818. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3819. result.scaleInPlace(1.0 / num);
  3820. }
  3821. };
  3822. /**
  3823. * Gets the minimal coordinate values between two Vector3
  3824. * @param left defines the first operand
  3825. * @param right defines the second operand
  3826. * @returns the new Vector3
  3827. */
  3828. Vector3.Minimize = function (left, right) {
  3829. var min = left.clone();
  3830. min.minimizeInPlace(right);
  3831. return min;
  3832. };
  3833. /**
  3834. * Gets the maximal coordinate values between two Vector3
  3835. * @param left defines the first operand
  3836. * @param right defines the second operand
  3837. * @returns the new Vector3
  3838. */
  3839. Vector3.Maximize = function (left, right) {
  3840. var max = left.clone();
  3841. max.maximizeInPlace(right);
  3842. return max;
  3843. };
  3844. /**
  3845. * Returns the distance between the vectors "value1" and "value2"
  3846. * @param value1 defines the first operand
  3847. * @param value2 defines the second operand
  3848. * @returns the distance
  3849. */
  3850. Vector3.Distance = function (value1, value2) {
  3851. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3852. };
  3853. /**
  3854. * Returns the squared distance between the vectors "value1" and "value2"
  3855. * @param value1 defines the first operand
  3856. * @param value2 defines the second operand
  3857. * @returns the squared distance
  3858. */
  3859. Vector3.DistanceSquared = function (value1, value2) {
  3860. var x = value1.x - value2.x;
  3861. var y = value1.y - value2.y;
  3862. var z = value1.z - value2.z;
  3863. return (x * x) + (y * y) + (z * z);
  3864. };
  3865. /**
  3866. * Returns a new Vector3 located at the center between "value1" and "value2"
  3867. * @param value1 defines the first operand
  3868. * @param value2 defines the second operand
  3869. * @returns the new Vector3
  3870. */
  3871. Vector3.Center = function (value1, value2) {
  3872. var center = value1.add(value2);
  3873. center.scaleInPlace(0.5);
  3874. return center;
  3875. };
  3876. /**
  3877. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3878. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3879. * to something in order to rotate it from its local system to the given target system
  3880. * Note: axis1, axis2 and axis3 are normalized during this operation
  3881. * @param axis1 defines the first axis
  3882. * @param axis2 defines the second axis
  3883. * @param axis3 defines the third axis
  3884. * @returns a new Vector3
  3885. */
  3886. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3887. var rotation = Vector3.Zero();
  3888. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3889. return rotation;
  3890. };
  3891. /**
  3892. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3893. * @param axis1 defines the first axis
  3894. * @param axis2 defines the second axis
  3895. * @param axis3 defines the third axis
  3896. * @param ref defines the Vector3 where to store the result
  3897. */
  3898. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3899. var quat = MathTmp.Quaternion[0];
  3900. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3901. quat.toEulerAnglesToRef(ref);
  3902. };
  3903. return Vector3;
  3904. }());
  3905. BABYLON.Vector3 = Vector3;
  3906. /**
  3907. * Vector4 class created for EulerAngle class conversion to Quaternion
  3908. */
  3909. var Vector4 = /** @class */ (function () {
  3910. /**
  3911. * Creates a Vector4 object from the given floats.
  3912. * @param x x value of the vector
  3913. * @param y y value of the vector
  3914. * @param z z value of the vector
  3915. * @param w w value of the vector
  3916. */
  3917. function Vector4(
  3918. /** x value of the vector */
  3919. x,
  3920. /** y value of the vector */
  3921. y,
  3922. /** z value of the vector */
  3923. z,
  3924. /** w value of the vector */
  3925. w) {
  3926. this.x = x;
  3927. this.y = y;
  3928. this.z = z;
  3929. this.w = w;
  3930. }
  3931. /**
  3932. * Returns the string with the Vector4 coordinates.
  3933. * @returns a string containing all the vector values
  3934. */
  3935. Vector4.prototype.toString = function () {
  3936. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3937. };
  3938. /**
  3939. * Returns the string "Vector4".
  3940. * @returns "Vector4"
  3941. */
  3942. Vector4.prototype.getClassName = function () {
  3943. return "Vector4";
  3944. };
  3945. /**
  3946. * Returns the Vector4 hash code.
  3947. * @returns a unique hash code
  3948. */
  3949. Vector4.prototype.getHashCode = function () {
  3950. var hash = this.x || 0;
  3951. hash = (hash * 397) ^ (this.y || 0);
  3952. hash = (hash * 397) ^ (this.z || 0);
  3953. hash = (hash * 397) ^ (this.w || 0);
  3954. return hash;
  3955. };
  3956. // Operators
  3957. /**
  3958. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3959. * @returns the resulting array
  3960. */
  3961. Vector4.prototype.asArray = function () {
  3962. var result = new Array();
  3963. this.toArray(result, 0);
  3964. return result;
  3965. };
  3966. /**
  3967. * Populates the given array from the given index with the Vector4 coordinates.
  3968. * @param array array to populate
  3969. * @param index index of the array to start at (default: 0)
  3970. * @returns the Vector4.
  3971. */
  3972. Vector4.prototype.toArray = function (array, index) {
  3973. if (index === undefined) {
  3974. index = 0;
  3975. }
  3976. array[index] = this.x;
  3977. array[index + 1] = this.y;
  3978. array[index + 2] = this.z;
  3979. array[index + 3] = this.w;
  3980. return this;
  3981. };
  3982. /**
  3983. * Adds the given vector to the current Vector4.
  3984. * @param otherVector the vector to add
  3985. * @returns the updated Vector4.
  3986. */
  3987. Vector4.prototype.addInPlace = function (otherVector) {
  3988. this.x += otherVector.x;
  3989. this.y += otherVector.y;
  3990. this.z += otherVector.z;
  3991. this.w += otherVector.w;
  3992. return this;
  3993. };
  3994. /**
  3995. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3996. * @param otherVector the vector to add
  3997. * @returns the resulting vector
  3998. */
  3999. Vector4.prototype.add = function (otherVector) {
  4000. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4001. };
  4002. /**
  4003. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4004. * @param otherVector the vector to add
  4005. * @param result the vector to store the result
  4006. * @returns the current Vector4.
  4007. */
  4008. Vector4.prototype.addToRef = function (otherVector, result) {
  4009. result.x = this.x + otherVector.x;
  4010. result.y = this.y + otherVector.y;
  4011. result.z = this.z + otherVector.z;
  4012. result.w = this.w + otherVector.w;
  4013. return this;
  4014. };
  4015. /**
  4016. * Subtract in place the given vector from the current Vector4.
  4017. * @param otherVector the vector to subtract
  4018. * @returns the updated Vector4.
  4019. */
  4020. Vector4.prototype.subtractInPlace = function (otherVector) {
  4021. this.x -= otherVector.x;
  4022. this.y -= otherVector.y;
  4023. this.z -= otherVector.z;
  4024. this.w -= otherVector.w;
  4025. return this;
  4026. };
  4027. /**
  4028. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4029. * @param otherVector the vector to add
  4030. * @returns the new vector with the result
  4031. */
  4032. Vector4.prototype.subtract = function (otherVector) {
  4033. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4034. };
  4035. /**
  4036. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4037. * @param otherVector the vector to subtract
  4038. * @param result the vector to store the result
  4039. * @returns the current Vector4.
  4040. */
  4041. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4042. result.x = this.x - otherVector.x;
  4043. result.y = this.y - otherVector.y;
  4044. result.z = this.z - otherVector.z;
  4045. result.w = this.w - otherVector.w;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4050. */
  4051. /**
  4052. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4053. * @param x value to subtract
  4054. * @param y value to subtract
  4055. * @param z value to subtract
  4056. * @param w value to subtract
  4057. * @returns new vector containing the result
  4058. */
  4059. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4060. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4061. };
  4062. /**
  4063. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4064. * @param x value to subtract
  4065. * @param y value to subtract
  4066. * @param z value to subtract
  4067. * @param w value to subtract
  4068. * @param result the vector to store the result in
  4069. * @returns the current Vector4.
  4070. */
  4071. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4072. result.x = this.x - x;
  4073. result.y = this.y - y;
  4074. result.z = this.z - z;
  4075. result.w = this.w - w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4080. * @returns a new vector with the negated values
  4081. */
  4082. Vector4.prototype.negate = function () {
  4083. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4084. };
  4085. /**
  4086. * Multiplies the current Vector4 coordinates by scale (float).
  4087. * @param scale the number to scale with
  4088. * @returns the updated Vector4.
  4089. */
  4090. Vector4.prototype.scaleInPlace = function (scale) {
  4091. this.x *= scale;
  4092. this.y *= scale;
  4093. this.z *= scale;
  4094. this.w *= scale;
  4095. return this;
  4096. };
  4097. /**
  4098. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4099. * @param scale the number to scale with
  4100. * @returns a new vector with the result
  4101. */
  4102. Vector4.prototype.scale = function (scale) {
  4103. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4104. };
  4105. /**
  4106. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4107. * @param scale the number to scale with
  4108. * @param result a vector to store the result in
  4109. * @returns the current Vector4.
  4110. */
  4111. Vector4.prototype.scaleToRef = function (scale, result) {
  4112. result.x = this.x * scale;
  4113. result.y = this.y * scale;
  4114. result.z = this.z * scale;
  4115. result.w = this.w * scale;
  4116. return this;
  4117. };
  4118. /**
  4119. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4120. * @param scale defines the scale factor
  4121. * @param result defines the Vector4 object where to store the result
  4122. * @returns the unmodified current Vector4
  4123. */
  4124. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4125. result.x += this.x * scale;
  4126. result.y += this.y * scale;
  4127. result.z += this.z * scale;
  4128. result.w += this.w * scale;
  4129. return this;
  4130. };
  4131. /**
  4132. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4133. * @param otherVector the vector to compare against
  4134. * @returns true if they are equal
  4135. */
  4136. Vector4.prototype.equals = function (otherVector) {
  4137. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4138. };
  4139. /**
  4140. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4141. * @param otherVector vector to compare against
  4142. * @param epsilon (Default: very small number)
  4143. * @returns true if they are equal
  4144. */
  4145. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4146. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4147. return otherVector
  4148. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4149. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4150. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4151. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4152. };
  4153. /**
  4154. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4155. * @param x x value to compare against
  4156. * @param y y value to compare against
  4157. * @param z z value to compare against
  4158. * @param w w value to compare against
  4159. * @returns true if equal
  4160. */
  4161. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4162. return this.x === x && this.y === y && this.z === z && this.w === w;
  4163. };
  4164. /**
  4165. * Multiplies in place the current Vector4 by the given one.
  4166. * @param otherVector vector to multiple with
  4167. * @returns the updated Vector4.
  4168. */
  4169. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4170. this.x *= otherVector.x;
  4171. this.y *= otherVector.y;
  4172. this.z *= otherVector.z;
  4173. this.w *= otherVector.w;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4178. * @param otherVector vector to multiple with
  4179. * @returns resulting new vector
  4180. */
  4181. Vector4.prototype.multiply = function (otherVector) {
  4182. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4183. };
  4184. /**
  4185. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4186. * @param otherVector vector to multiple with
  4187. * @param result vector to store the result
  4188. * @returns the current Vector4.
  4189. */
  4190. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4191. result.x = this.x * otherVector.x;
  4192. result.y = this.y * otherVector.y;
  4193. result.z = this.z * otherVector.z;
  4194. result.w = this.w * otherVector.w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4199. * @param x x value multiply with
  4200. * @param y y value multiply with
  4201. * @param z z value multiply with
  4202. * @param w w value multiply with
  4203. * @returns resulting new vector
  4204. */
  4205. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4206. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4207. };
  4208. /**
  4209. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4210. * @param otherVector vector to devide with
  4211. * @returns resulting new vector
  4212. */
  4213. Vector4.prototype.divide = function (otherVector) {
  4214. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4215. };
  4216. /**
  4217. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4218. * @param otherVector vector to devide with
  4219. * @param result vector to store the result
  4220. * @returns the current Vector4.
  4221. */
  4222. Vector4.prototype.divideToRef = function (otherVector, result) {
  4223. result.x = this.x / otherVector.x;
  4224. result.y = this.y / otherVector.y;
  4225. result.z = this.z / otherVector.z;
  4226. result.w = this.w / otherVector.w;
  4227. return this;
  4228. };
  4229. /**
  4230. * Divides the current Vector3 coordinates by the given ones.
  4231. * @param otherVector vector to devide with
  4232. * @returns the updated Vector3.
  4233. */
  4234. Vector4.prototype.divideInPlace = function (otherVector) {
  4235. return this.divideToRef(otherVector, this);
  4236. };
  4237. /**
  4238. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4239. * @param other defines the second operand
  4240. * @returns the current updated Vector4
  4241. */
  4242. Vector4.prototype.minimizeInPlace = function (other) {
  4243. if (other.x < this.x)
  4244. this.x = other.x;
  4245. if (other.y < this.y)
  4246. this.y = other.y;
  4247. if (other.z < this.z)
  4248. this.z = other.z;
  4249. if (other.w < this.w)
  4250. this.w = other.w;
  4251. return this;
  4252. };
  4253. /**
  4254. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4255. * @param other defines the second operand
  4256. * @returns the current updated Vector4
  4257. */
  4258. Vector4.prototype.maximizeInPlace = function (other) {
  4259. if (other.x > this.x)
  4260. this.x = other.x;
  4261. if (other.y > this.y)
  4262. this.y = other.y;
  4263. if (other.z > this.z)
  4264. this.z = other.z;
  4265. if (other.w > this.w)
  4266. this.w = other.w;
  4267. return this;
  4268. };
  4269. /**
  4270. * Gets a new Vector4 from current Vector4 floored values
  4271. * @returns a new Vector4
  4272. */
  4273. Vector4.prototype.floor = function () {
  4274. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4275. };
  4276. /**
  4277. * Gets a new Vector4 from current Vector3 floored values
  4278. * @returns a new Vector4
  4279. */
  4280. Vector4.prototype.fract = function () {
  4281. 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));
  4282. };
  4283. // Properties
  4284. /**
  4285. * Returns the Vector4 length (float).
  4286. * @returns the length
  4287. */
  4288. Vector4.prototype.length = function () {
  4289. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4290. };
  4291. /**
  4292. * Returns the Vector4 squared length (float).
  4293. * @returns the length squared
  4294. */
  4295. Vector4.prototype.lengthSquared = function () {
  4296. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4297. };
  4298. // Methods
  4299. /**
  4300. * Normalizes in place the Vector4.
  4301. * @returns the updated Vector4.
  4302. */
  4303. Vector4.prototype.normalize = function () {
  4304. var len = this.length();
  4305. if (len === 0)
  4306. return this;
  4307. var num = 1.0 / len;
  4308. this.x *= num;
  4309. this.y *= num;
  4310. this.z *= num;
  4311. this.w *= num;
  4312. return this;
  4313. };
  4314. /**
  4315. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4316. * @returns this converted to a new vector3
  4317. */
  4318. Vector4.prototype.toVector3 = function () {
  4319. return new Vector3(this.x, this.y, this.z);
  4320. };
  4321. /**
  4322. * Returns a new Vector4 copied from the current one.
  4323. * @returns the new cloned vector
  4324. */
  4325. Vector4.prototype.clone = function () {
  4326. return new Vector4(this.x, this.y, this.z, this.w);
  4327. };
  4328. /**
  4329. * Updates the current Vector4 with the given one coordinates.
  4330. * @param source the source vector to copy from
  4331. * @returns the updated Vector4.
  4332. */
  4333. Vector4.prototype.copyFrom = function (source) {
  4334. this.x = source.x;
  4335. this.y = source.y;
  4336. this.z = source.z;
  4337. this.w = source.w;
  4338. return this;
  4339. };
  4340. /**
  4341. * Updates the current Vector4 coordinates with the given floats.
  4342. * @param x float to copy from
  4343. * @param y float to copy from
  4344. * @param z float to copy from
  4345. * @param w float to copy from
  4346. * @returns the updated Vector4.
  4347. */
  4348. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4349. this.x = x;
  4350. this.y = y;
  4351. this.z = z;
  4352. this.w = w;
  4353. return this;
  4354. };
  4355. /**
  4356. * Updates the current Vector4 coordinates with the given floats.
  4357. * @param x float to set from
  4358. * @param y float to set from
  4359. * @param z float to set from
  4360. * @param w float to set from
  4361. * @returns the updated Vector4.
  4362. */
  4363. Vector4.prototype.set = function (x, y, z, w) {
  4364. return this.copyFromFloats(x, y, z, w);
  4365. };
  4366. // Statics
  4367. /**
  4368. * Returns a new Vector4 set from the starting index of the given array.
  4369. * @param array the array to pull values from
  4370. * @param offset the offset into the array to start at
  4371. * @returns the new vector
  4372. */
  4373. Vector4.FromArray = function (array, offset) {
  4374. if (!offset) {
  4375. offset = 0;
  4376. }
  4377. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4378. };
  4379. /**
  4380. * Updates the given vector "result" from the starting index of the given array.
  4381. * @param array the array to pull values from
  4382. * @param offset the offset into the array to start at
  4383. * @param result the vector to store the result in
  4384. */
  4385. Vector4.FromArrayToRef = function (array, offset, result) {
  4386. result.x = array[offset];
  4387. result.y = array[offset + 1];
  4388. result.z = array[offset + 2];
  4389. result.w = array[offset + 3];
  4390. };
  4391. /**
  4392. * Updates the given vector "result" from the starting index of the given Float32Array.
  4393. * @param array the array to pull values from
  4394. * @param offset the offset into the array to start at
  4395. * @param result the vector to store the result in
  4396. */
  4397. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4398. Vector4.FromArrayToRef(array, offset, result);
  4399. };
  4400. /**
  4401. * Updates the given vector "result" coordinates from the given floats.
  4402. * @param x float to set from
  4403. * @param y float to set from
  4404. * @param z float to set from
  4405. * @param w float to set from
  4406. * @param result the vector to the floats in
  4407. */
  4408. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4409. result.x = x;
  4410. result.y = y;
  4411. result.z = z;
  4412. result.w = w;
  4413. };
  4414. /**
  4415. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4416. * @returns the new vector
  4417. */
  4418. Vector4.Zero = function () {
  4419. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4420. };
  4421. /**
  4422. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4423. * @returns the new vector
  4424. */
  4425. Vector4.One = function () {
  4426. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4427. };
  4428. /**
  4429. * Returns a new normalized Vector4 from the given one.
  4430. * @param vector the vector to normalize
  4431. * @returns the vector
  4432. */
  4433. Vector4.Normalize = function (vector) {
  4434. var result = Vector4.Zero();
  4435. Vector4.NormalizeToRef(vector, result);
  4436. return result;
  4437. };
  4438. /**
  4439. * Updates the given vector "result" from the normalization of the given one.
  4440. * @param vector the vector to normalize
  4441. * @param result the vector to store the result in
  4442. */
  4443. Vector4.NormalizeToRef = function (vector, result) {
  4444. result.copyFrom(vector);
  4445. result.normalize();
  4446. };
  4447. /**
  4448. * Returns a vector with the minimum values from the left and right vectors
  4449. * @param left left vector to minimize
  4450. * @param right right vector to minimize
  4451. * @returns a new vector with the minimum of the left and right vector values
  4452. */
  4453. Vector4.Minimize = function (left, right) {
  4454. var min = left.clone();
  4455. min.minimizeInPlace(right);
  4456. return min;
  4457. };
  4458. /**
  4459. * Returns a vector with the maximum values from the left and right vectors
  4460. * @param left left vector to maximize
  4461. * @param right right vector to maximize
  4462. * @returns a new vector with the maximum of the left and right vector values
  4463. */
  4464. Vector4.Maximize = function (left, right) {
  4465. var max = left.clone();
  4466. max.maximizeInPlace(right);
  4467. return max;
  4468. };
  4469. /**
  4470. * Returns the distance (float) between the vectors "value1" and "value2".
  4471. * @param value1 value to calulate the distance between
  4472. * @param value2 value to calulate the distance between
  4473. * @return the distance between the two vectors
  4474. */
  4475. Vector4.Distance = function (value1, value2) {
  4476. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4477. };
  4478. /**
  4479. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4480. * @param value1 value to calulate the distance between
  4481. * @param value2 value to calulate the distance between
  4482. * @return the distance between the two vectors squared
  4483. */
  4484. Vector4.DistanceSquared = function (value1, value2) {
  4485. var x = value1.x - value2.x;
  4486. var y = value1.y - value2.y;
  4487. var z = value1.z - value2.z;
  4488. var w = value1.w - value2.w;
  4489. return (x * x) + (y * y) + (z * z) + (w * w);
  4490. };
  4491. /**
  4492. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4493. * @param value1 value to calulate the center between
  4494. * @param value2 value to calulate the center between
  4495. * @return the center between the two vectors
  4496. */
  4497. Vector4.Center = function (value1, value2) {
  4498. var center = value1.add(value2);
  4499. center.scaleInPlace(0.5);
  4500. return center;
  4501. };
  4502. /**
  4503. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4504. * This methods computes transformed normalized direction vectors only.
  4505. * @param vector the vector to transform
  4506. * @param transformation the transformation matrix to apply
  4507. * @returns the new vector
  4508. */
  4509. Vector4.TransformNormal = function (vector, transformation) {
  4510. var result = Vector4.Zero();
  4511. Vector4.TransformNormalToRef(vector, transformation, result);
  4512. return result;
  4513. };
  4514. /**
  4515. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4516. * This methods computes transformed normalized direction vectors only.
  4517. * @param vector the vector to transform
  4518. * @param transformation the transformation matrix to apply
  4519. * @param result the vector to store the result in
  4520. */
  4521. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4522. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4523. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4524. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4525. result.x = x;
  4526. result.y = y;
  4527. result.z = z;
  4528. result.w = vector.w;
  4529. };
  4530. /**
  4531. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4532. * This methods computes transformed normalized direction vectors only.
  4533. * @param x value to transform
  4534. * @param y value to transform
  4535. * @param z value to transform
  4536. * @param w value to transform
  4537. * @param transformation the transformation matrix to apply
  4538. * @param result the vector to store the results in
  4539. */
  4540. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4541. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4542. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4543. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4544. result.w = w;
  4545. };
  4546. return Vector4;
  4547. }());
  4548. BABYLON.Vector4 = Vector4;
  4549. /**
  4550. * Size containing widht and height
  4551. */
  4552. var Size = /** @class */ (function () {
  4553. /**
  4554. * Creates a Size object from the given width and height (floats).
  4555. * @param width width of the new size
  4556. * @param height height of the new size
  4557. */
  4558. function Size(width, height) {
  4559. this.width = width;
  4560. this.height = height;
  4561. }
  4562. /**
  4563. * Returns a string with the Size width and height
  4564. * @returns a string with the Size width and height
  4565. */
  4566. Size.prototype.toString = function () {
  4567. return "{W: " + this.width + ", H: " + this.height + "}";
  4568. };
  4569. /**
  4570. * "Size"
  4571. * @returns the string "Size"
  4572. */
  4573. Size.prototype.getClassName = function () {
  4574. return "Size";
  4575. };
  4576. /**
  4577. * Returns the Size hash code.
  4578. * @returns a hash code for a unique width and height
  4579. */
  4580. Size.prototype.getHashCode = function () {
  4581. var hash = this.width || 0;
  4582. hash = (hash * 397) ^ (this.height || 0);
  4583. return hash;
  4584. };
  4585. /**
  4586. * Updates the current size from the given one.
  4587. * @param src the given size
  4588. */
  4589. Size.prototype.copyFrom = function (src) {
  4590. this.width = src.width;
  4591. this.height = src.height;
  4592. };
  4593. /**
  4594. * Updates in place the current Size from the given floats.
  4595. * @param width width of the new size
  4596. * @param height height of the new size
  4597. * @returns the updated Size.
  4598. */
  4599. Size.prototype.copyFromFloats = function (width, height) {
  4600. this.width = width;
  4601. this.height = height;
  4602. return this;
  4603. };
  4604. /**
  4605. * Updates in place the current Size from the given floats.
  4606. * @param width width to set
  4607. * @param height height to set
  4608. * @returns the updated Size.
  4609. */
  4610. Size.prototype.set = function (width, height) {
  4611. return this.copyFromFloats(width, height);
  4612. };
  4613. /**
  4614. * Multiplies the width and height by numbers
  4615. * @param w factor to multiple the width by
  4616. * @param h factor to multiple the height by
  4617. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4618. */
  4619. Size.prototype.multiplyByFloats = function (w, h) {
  4620. return new Size(this.width * w, this.height * h);
  4621. };
  4622. /**
  4623. * Clones the size
  4624. * @returns a new Size copied from the given one.
  4625. */
  4626. Size.prototype.clone = function () {
  4627. return new Size(this.width, this.height);
  4628. };
  4629. /**
  4630. * True if the current Size and the given one width and height are strictly equal.
  4631. * @param other the other size to compare against
  4632. * @returns True if the current Size and the given one width and height are strictly equal.
  4633. */
  4634. Size.prototype.equals = function (other) {
  4635. if (!other) {
  4636. return false;
  4637. }
  4638. return (this.width === other.width) && (this.height === other.height);
  4639. };
  4640. Object.defineProperty(Size.prototype, "surface", {
  4641. /**
  4642. * The surface of the Size : width * height (float).
  4643. */
  4644. get: function () {
  4645. return this.width * this.height;
  4646. },
  4647. enumerable: true,
  4648. configurable: true
  4649. });
  4650. /**
  4651. * Create a new size of zero
  4652. * @returns a new Size set to (0.0, 0.0)
  4653. */
  4654. Size.Zero = function () {
  4655. return new Size(0.0, 0.0);
  4656. };
  4657. /**
  4658. * Sums the width and height of two sizes
  4659. * @param otherSize size to add to this size
  4660. * @returns a new Size set as the addition result of the current Size and the given one.
  4661. */
  4662. Size.prototype.add = function (otherSize) {
  4663. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4664. return r;
  4665. };
  4666. /**
  4667. * Subtracts the width and height of two
  4668. * @param otherSize size to subtract to this size
  4669. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4670. */
  4671. Size.prototype.subtract = function (otherSize) {
  4672. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4673. return r;
  4674. };
  4675. /**
  4676. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4677. * @param start starting size to lerp between
  4678. * @param end end size to lerp between
  4679. * @param amount amount to lerp between the start and end values
  4680. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4681. */
  4682. Size.Lerp = function (start, end, amount) {
  4683. var w = start.width + ((end.width - start.width) * amount);
  4684. var h = start.height + ((end.height - start.height) * amount);
  4685. return new Size(w, h);
  4686. };
  4687. return Size;
  4688. }());
  4689. BABYLON.Size = Size;
  4690. /**
  4691. * Class used to store quaternion data
  4692. * @see https://en.wikipedia.org/wiki/Quaternion
  4693. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4694. */
  4695. var Quaternion = /** @class */ (function () {
  4696. /**
  4697. * Creates a new Quaternion from the given floats
  4698. * @param x defines the first component (0 by default)
  4699. * @param y defines the second component (0 by default)
  4700. * @param z defines the third component (0 by default)
  4701. * @param w defines the fourth component (1.0 by default)
  4702. */
  4703. function Quaternion(
  4704. /** defines the first component (0 by default) */
  4705. x,
  4706. /** defines the second component (0 by default) */
  4707. y,
  4708. /** defines the third component (0 by default) */
  4709. z,
  4710. /** defines the fourth component (1.0 by default) */
  4711. w) {
  4712. if (x === void 0) { x = 0.0; }
  4713. if (y === void 0) { y = 0.0; }
  4714. if (z === void 0) { z = 0.0; }
  4715. if (w === void 0) { w = 1.0; }
  4716. this.x = x;
  4717. this.y = y;
  4718. this.z = z;
  4719. this.w = w;
  4720. }
  4721. /**
  4722. * Gets a string representation for the current quaternion
  4723. * @returns a string with the Quaternion coordinates
  4724. */
  4725. Quaternion.prototype.toString = function () {
  4726. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4727. };
  4728. /**
  4729. * Gets the class name of the quaternion
  4730. * @returns the string "Quaternion"
  4731. */
  4732. Quaternion.prototype.getClassName = function () {
  4733. return "Quaternion";
  4734. };
  4735. /**
  4736. * Gets a hash code for this quaternion
  4737. * @returns the quaternion hash code
  4738. */
  4739. Quaternion.prototype.getHashCode = function () {
  4740. var hash = this.x || 0;
  4741. hash = (hash * 397) ^ (this.y || 0);
  4742. hash = (hash * 397) ^ (this.z || 0);
  4743. hash = (hash * 397) ^ (this.w || 0);
  4744. return hash;
  4745. };
  4746. /**
  4747. * Copy the quaternion to an array
  4748. * @returns a new array populated with 4 elements from the quaternion coordinates
  4749. */
  4750. Quaternion.prototype.asArray = function () {
  4751. return [this.x, this.y, this.z, this.w];
  4752. };
  4753. /**
  4754. * Check if two quaternions are equals
  4755. * @param otherQuaternion defines the second operand
  4756. * @return true if the current quaternion and the given one coordinates are strictly equals
  4757. */
  4758. Quaternion.prototype.equals = function (otherQuaternion) {
  4759. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4760. };
  4761. /**
  4762. * Clone the current quaternion
  4763. * @returns a new quaternion copied from the current one
  4764. */
  4765. Quaternion.prototype.clone = function () {
  4766. return new Quaternion(this.x, this.y, this.z, this.w);
  4767. };
  4768. /**
  4769. * Copy a quaternion to the current one
  4770. * @param other defines the other quaternion
  4771. * @returns the updated current quaternion
  4772. */
  4773. Quaternion.prototype.copyFrom = function (other) {
  4774. this.x = other.x;
  4775. this.y = other.y;
  4776. this.z = other.z;
  4777. this.w = other.w;
  4778. return this;
  4779. };
  4780. /**
  4781. * Updates the current quaternion with the given float coordinates
  4782. * @param x defines the x coordinate
  4783. * @param y defines the y coordinate
  4784. * @param z defines the z coordinate
  4785. * @param w defines the w coordinate
  4786. * @returns the updated current quaternion
  4787. */
  4788. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4789. this.x = x;
  4790. this.y = y;
  4791. this.z = z;
  4792. this.w = w;
  4793. return this;
  4794. };
  4795. /**
  4796. * Updates the current quaternion from the given float coordinates
  4797. * @param x defines the x coordinate
  4798. * @param y defines the y coordinate
  4799. * @param z defines the z coordinate
  4800. * @param w defines the w coordinate
  4801. * @returns the updated current quaternion
  4802. */
  4803. Quaternion.prototype.set = function (x, y, z, w) {
  4804. return this.copyFromFloats(x, y, z, w);
  4805. };
  4806. /**
  4807. * Adds two quaternions
  4808. * @param other defines the second operand
  4809. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4810. */
  4811. Quaternion.prototype.add = function (other) {
  4812. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4813. };
  4814. /**
  4815. * Add a quaternion to the current one
  4816. * @param other defines the quaternion to add
  4817. * @returns the current quaternion
  4818. */
  4819. Quaternion.prototype.addInPlace = function (other) {
  4820. this.x += other.x;
  4821. this.y += other.y;
  4822. this.z += other.z;
  4823. this.w += other.w;
  4824. return this;
  4825. };
  4826. /**
  4827. * Subtract two quaternions
  4828. * @param other defines the second operand
  4829. * @returns a new quaternion as the subtraction result of the given one from the current one
  4830. */
  4831. Quaternion.prototype.subtract = function (other) {
  4832. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4833. };
  4834. /**
  4835. * Multiplies the current quaternion by a scale factor
  4836. * @param value defines the scale factor
  4837. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4838. */
  4839. Quaternion.prototype.scale = function (value) {
  4840. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4841. };
  4842. /**
  4843. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4844. * @param scale defines the scale factor
  4845. * @param result defines the Quaternion object where to store the result
  4846. * @returns the unmodified current quaternion
  4847. */
  4848. Quaternion.prototype.scaleToRef = function (scale, result) {
  4849. result.x = this.x * scale;
  4850. result.y = this.y * scale;
  4851. result.z = this.z * scale;
  4852. result.w = this.w * scale;
  4853. return this;
  4854. };
  4855. /**
  4856. * Multiplies in place the current quaternion by a scale factor
  4857. * @param value defines the scale factor
  4858. * @returns the current modified quaternion
  4859. */
  4860. Quaternion.prototype.scaleInPlace = function (value) {
  4861. this.x *= value;
  4862. this.y *= value;
  4863. this.z *= value;
  4864. this.w *= value;
  4865. return this;
  4866. };
  4867. /**
  4868. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4869. * @param scale defines the scale factor
  4870. * @param result defines the Quaternion object where to store the result
  4871. * @returns the unmodified current quaternion
  4872. */
  4873. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4874. result.x += this.x * scale;
  4875. result.y += this.y * scale;
  4876. result.z += this.z * scale;
  4877. result.w += this.w * scale;
  4878. return this;
  4879. };
  4880. /**
  4881. * Multiplies two quaternions
  4882. * @param q1 defines the second operand
  4883. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4884. */
  4885. Quaternion.prototype.multiply = function (q1) {
  4886. var result = new Quaternion(0, 0, 0, 1.0);
  4887. this.multiplyToRef(q1, result);
  4888. return result;
  4889. };
  4890. /**
  4891. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4892. * @param q1 defines the second operand
  4893. * @param result defines the target quaternion
  4894. * @returns the current quaternion
  4895. */
  4896. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4897. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4898. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4899. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4900. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4901. result.copyFromFloats(x, y, z, w);
  4902. return this;
  4903. };
  4904. /**
  4905. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4906. * @param q1 defines the second operand
  4907. * @returns the currentupdated quaternion
  4908. */
  4909. Quaternion.prototype.multiplyInPlace = function (q1) {
  4910. this.multiplyToRef(q1, this);
  4911. return this;
  4912. };
  4913. /**
  4914. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4915. * @param ref defines the target quaternion
  4916. * @returns the current quaternion
  4917. */
  4918. Quaternion.prototype.conjugateToRef = function (ref) {
  4919. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4920. return this;
  4921. };
  4922. /**
  4923. * Conjugates in place (1-q) the current quaternion
  4924. * @returns the current updated quaternion
  4925. */
  4926. Quaternion.prototype.conjugateInPlace = function () {
  4927. this.x *= -1;
  4928. this.y *= -1;
  4929. this.z *= -1;
  4930. return this;
  4931. };
  4932. /**
  4933. * Conjugates in place (1-q) the current quaternion
  4934. * @returns a new quaternion
  4935. */
  4936. Quaternion.prototype.conjugate = function () {
  4937. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4938. return result;
  4939. };
  4940. /**
  4941. * Gets length of current quaternion
  4942. * @returns the quaternion length (float)
  4943. */
  4944. Quaternion.prototype.length = function () {
  4945. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4946. };
  4947. /**
  4948. * Normalize in place the current quaternion
  4949. * @returns the current updated quaternion
  4950. */
  4951. Quaternion.prototype.normalize = function () {
  4952. var length = 1.0 / this.length();
  4953. this.x *= length;
  4954. this.y *= length;
  4955. this.z *= length;
  4956. this.w *= length;
  4957. return this;
  4958. };
  4959. /**
  4960. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4961. * @param order is a reserved parameter and is ignore for now
  4962. * @returns a new Vector3 containing the Euler angles
  4963. */
  4964. Quaternion.prototype.toEulerAngles = function (order) {
  4965. if (order === void 0) { order = "YZX"; }
  4966. var result = Vector3.Zero();
  4967. this.toEulerAnglesToRef(result, order);
  4968. return result;
  4969. };
  4970. /**
  4971. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4972. * @param result defines the vector which will be filled with the Euler angles
  4973. * @param order is a reserved parameter and is ignore for now
  4974. * @returns the current unchanged quaternion
  4975. */
  4976. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4977. if (order === void 0) { order = "YZX"; }
  4978. var qz = this.z;
  4979. var qx = this.x;
  4980. var qy = this.y;
  4981. var qw = this.w;
  4982. var sqw = qw * qw;
  4983. var sqz = qz * qz;
  4984. var sqx = qx * qx;
  4985. var sqy = qy * qy;
  4986. var zAxisY = qy * qz - qx * qw;
  4987. var limit = .4999999;
  4988. if (zAxisY < -limit) {
  4989. result.y = 2 * Math.atan2(qy, qw);
  4990. result.x = Math.PI / 2;
  4991. result.z = 0;
  4992. }
  4993. else if (zAxisY > limit) {
  4994. result.y = 2 * Math.atan2(qy, qw);
  4995. result.x = -Math.PI / 2;
  4996. result.z = 0;
  4997. }
  4998. else {
  4999. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5000. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5001. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5002. }
  5003. return this;
  5004. };
  5005. /**
  5006. * Updates the given rotation matrix with the current quaternion values
  5007. * @param result defines the target matrix
  5008. * @returns the current unchanged quaternion
  5009. */
  5010. Quaternion.prototype.toRotationMatrix = function (result) {
  5011. var xx = this.x * this.x;
  5012. var yy = this.y * this.y;
  5013. var zz = this.z * this.z;
  5014. var xy = this.x * this.y;
  5015. var zw = this.z * this.w;
  5016. var zx = this.z * this.x;
  5017. var yw = this.y * this.w;
  5018. var yz = this.y * this.z;
  5019. var xw = this.x * this.w;
  5020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5021. result.m[1] = 2.0 * (xy + zw);
  5022. result.m[2] = 2.0 * (zx - yw);
  5023. result.m[3] = 0;
  5024. result.m[4] = 2.0 * (xy - zw);
  5025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5026. result.m[6] = 2.0 * (yz + xw);
  5027. result.m[7] = 0;
  5028. result.m[8] = 2.0 * (zx + yw);
  5029. result.m[9] = 2.0 * (yz - xw);
  5030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5031. result.m[11] = 0;
  5032. result.m[12] = 0;
  5033. result.m[13] = 0;
  5034. result.m[14] = 0;
  5035. result.m[15] = 1.0;
  5036. result._markAsUpdated();
  5037. return this;
  5038. };
  5039. /**
  5040. * Updates the current quaternion from the given rotation matrix values
  5041. * @param matrix defines the source matrix
  5042. * @returns the current updated quaternion
  5043. */
  5044. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5045. Quaternion.FromRotationMatrixToRef(matrix, this);
  5046. return this;
  5047. };
  5048. // Statics
  5049. /**
  5050. * Creates a new quaternion from a rotation matrix
  5051. * @param matrix defines the source matrix
  5052. * @returns a new quaternion created from the given rotation matrix values
  5053. */
  5054. Quaternion.FromRotationMatrix = function (matrix) {
  5055. var result = new Quaternion();
  5056. Quaternion.FromRotationMatrixToRef(matrix, result);
  5057. return result;
  5058. };
  5059. /**
  5060. * Updates the given quaternion with the given rotation matrix values
  5061. * @param matrix defines the source matrix
  5062. * @param result defines the target quaternion
  5063. */
  5064. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5065. var data = matrix.m;
  5066. var m11 = data[0], m12 = data[4], m13 = data[8];
  5067. var m21 = data[1], m22 = data[5], m23 = data[9];
  5068. var m31 = data[2], m32 = data[6], m33 = data[10];
  5069. var trace = m11 + m22 + m33;
  5070. var s;
  5071. if (trace > 0) {
  5072. s = 0.5 / Math.sqrt(trace + 1.0);
  5073. result.w = 0.25 / s;
  5074. result.x = (m32 - m23) * s;
  5075. result.y = (m13 - m31) * s;
  5076. result.z = (m21 - m12) * s;
  5077. }
  5078. else if (m11 > m22 && m11 > m33) {
  5079. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5080. result.w = (m32 - m23) / s;
  5081. result.x = 0.25 * s;
  5082. result.y = (m12 + m21) / s;
  5083. result.z = (m13 + m31) / s;
  5084. }
  5085. else if (m22 > m33) {
  5086. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5087. result.w = (m13 - m31) / s;
  5088. result.x = (m12 + m21) / s;
  5089. result.y = 0.25 * s;
  5090. result.z = (m23 + m32) / s;
  5091. }
  5092. else {
  5093. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5094. result.w = (m21 - m12) / s;
  5095. result.x = (m13 + m31) / s;
  5096. result.y = (m23 + m32) / s;
  5097. result.z = 0.25 * s;
  5098. }
  5099. };
  5100. /**
  5101. * Returns the dot product (float) between the quaternions "left" and "right"
  5102. * @param left defines the left operand
  5103. * @param right defines the right operand
  5104. * @returns the dot product
  5105. */
  5106. Quaternion.Dot = function (left, right) {
  5107. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5108. };
  5109. /**
  5110. * Checks if the two quaternions are close to each other
  5111. * @param quat0 defines the first quaternion to check
  5112. * @param quat1 defines the second quaternion to check
  5113. * @returns true if the two quaternions are close to each other
  5114. */
  5115. Quaternion.AreClose = function (quat0, quat1) {
  5116. var dot = Quaternion.Dot(quat0, quat1);
  5117. return dot >= 0;
  5118. };
  5119. /**
  5120. * Creates an empty quaternion
  5121. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5122. */
  5123. Quaternion.Zero = function () {
  5124. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5125. };
  5126. /**
  5127. * Inverse a given quaternion
  5128. * @param q defines the source quaternion
  5129. * @returns a new quaternion as the inverted current quaternion
  5130. */
  5131. Quaternion.Inverse = function (q) {
  5132. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5133. };
  5134. /**
  5135. * Creates an identity quaternion
  5136. * @returns the identity quaternion
  5137. */
  5138. Quaternion.Identity = function () {
  5139. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5140. };
  5141. /**
  5142. * Gets a boolean indicating if the given quaternion is identity
  5143. * @param quaternion defines the quaternion to check
  5144. * @returns true if the quaternion is identity
  5145. */
  5146. Quaternion.IsIdentity = function (quaternion) {
  5147. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5148. };
  5149. /**
  5150. * Creates a quaternion from a rotation around an axis
  5151. * @param axis defines the axis to use
  5152. * @param angle defines the angle to use
  5153. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5154. */
  5155. Quaternion.RotationAxis = function (axis, angle) {
  5156. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5157. };
  5158. /**
  5159. * Creates a rotation around an axis and stores it into the given quaternion
  5160. * @param axis defines the axis to use
  5161. * @param angle defines the angle to use
  5162. * @param result defines the target quaternion
  5163. * @returns the target quaternion
  5164. */
  5165. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5166. var sin = Math.sin(angle / 2);
  5167. axis.normalize();
  5168. result.w = Math.cos(angle / 2);
  5169. result.x = axis.x * sin;
  5170. result.y = axis.y * sin;
  5171. result.z = axis.z * sin;
  5172. return result;
  5173. };
  5174. /**
  5175. * Creates a new quaternion from data stored into an array
  5176. * @param array defines the data source
  5177. * @param offset defines the offset in the source array where the data starts
  5178. * @returns a new quaternion
  5179. */
  5180. Quaternion.FromArray = function (array, offset) {
  5181. if (!offset) {
  5182. offset = 0;
  5183. }
  5184. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5185. };
  5186. /**
  5187. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5188. * @param yaw defines the rotation around Y axis
  5189. * @param pitch defines the rotation around X axis
  5190. * @param roll defines the rotation around Z axis
  5191. * @returns the new quaternion
  5192. */
  5193. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5194. var q = new Quaternion();
  5195. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5196. return q;
  5197. };
  5198. /**
  5199. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5200. * @param yaw defines the rotation around Y axis
  5201. * @param pitch defines the rotation around X axis
  5202. * @param roll defines the rotation around Z axis
  5203. * @param result defines the target quaternion
  5204. */
  5205. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5206. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5207. var halfRoll = roll * 0.5;
  5208. var halfPitch = pitch * 0.5;
  5209. var halfYaw = yaw * 0.5;
  5210. var sinRoll = Math.sin(halfRoll);
  5211. var cosRoll = Math.cos(halfRoll);
  5212. var sinPitch = Math.sin(halfPitch);
  5213. var cosPitch = Math.cos(halfPitch);
  5214. var sinYaw = Math.sin(halfYaw);
  5215. var cosYaw = Math.cos(halfYaw);
  5216. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5217. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5218. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5219. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5220. };
  5221. /**
  5222. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5223. * @param alpha defines the rotation around first axis
  5224. * @param beta defines the rotation around second axis
  5225. * @param gamma defines the rotation around third axis
  5226. * @returns the new quaternion
  5227. */
  5228. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5229. var result = new Quaternion();
  5230. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5231. return result;
  5232. };
  5233. /**
  5234. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5235. * @param alpha defines the rotation around first axis
  5236. * @param beta defines the rotation around second axis
  5237. * @param gamma defines the rotation around third axis
  5238. * @param result defines the target quaternion
  5239. */
  5240. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5241. // Produces a quaternion from Euler angles in the z-x-z orientation
  5242. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5243. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5244. var halfBeta = beta * 0.5;
  5245. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5246. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5247. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5248. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5249. };
  5250. /**
  5251. * 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)
  5252. * @param axis1 defines the first axis
  5253. * @param axis2 defines the second axis
  5254. * @param axis3 defines the third axis
  5255. * @returns the new quaternion
  5256. */
  5257. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5258. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5259. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5260. return quat;
  5261. };
  5262. /**
  5263. * 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
  5264. * @param axis1 defines the first axis
  5265. * @param axis2 defines the second axis
  5266. * @param axis3 defines the third axis
  5267. * @param ref defines the target quaternion
  5268. */
  5269. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5270. var rotMat = MathTmp.Matrix[0];
  5271. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5272. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5273. };
  5274. /**
  5275. * Interpolates between two quaternions
  5276. * @param left defines first quaternion
  5277. * @param right defines second quaternion
  5278. * @param amount defines the gradient to use
  5279. * @returns the new interpolated quaternion
  5280. */
  5281. Quaternion.Slerp = function (left, right, amount) {
  5282. var result = Quaternion.Identity();
  5283. Quaternion.SlerpToRef(left, right, amount, result);
  5284. return result;
  5285. };
  5286. /**
  5287. * Interpolates between two quaternions and stores it into a target quaternion
  5288. * @param left defines first quaternion
  5289. * @param right defines second quaternion
  5290. * @param amount defines the gradient to use
  5291. * @param result defines the target quaternion
  5292. */
  5293. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5294. var num2;
  5295. var num3;
  5296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5297. var flag = false;
  5298. if (num4 < 0) {
  5299. flag = true;
  5300. num4 = -num4;
  5301. }
  5302. if (num4 > 0.999999) {
  5303. num3 = 1 - amount;
  5304. num2 = flag ? -amount : amount;
  5305. }
  5306. else {
  5307. var num5 = Math.acos(num4);
  5308. var num6 = (1.0 / Math.sin(num5));
  5309. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5310. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5311. }
  5312. result.x = (num3 * left.x) + (num2 * right.x);
  5313. result.y = (num3 * left.y) + (num2 * right.y);
  5314. result.z = (num3 * left.z) + (num2 * right.z);
  5315. result.w = (num3 * left.w) + (num2 * right.w);
  5316. };
  5317. /**
  5318. * Interpolate between two quaternions using Hermite interpolation
  5319. * @param value1 defines first quaternion
  5320. * @param tangent1 defines the incoming tangent
  5321. * @param value2 defines second quaternion
  5322. * @param tangent2 defines the outgoing tangent
  5323. * @param amount defines the target quaternion
  5324. * @returns the new interpolated quaternion
  5325. */
  5326. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5327. var squared = amount * amount;
  5328. var cubed = amount * squared;
  5329. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5330. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5331. var part3 = (cubed - (2.0 * squared)) + amount;
  5332. var part4 = cubed - squared;
  5333. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5334. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5335. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5336. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5337. return new Quaternion(x, y, z, w);
  5338. };
  5339. return Quaternion;
  5340. }());
  5341. BABYLON.Quaternion = Quaternion;
  5342. /**
  5343. * Class used to store matrix data (4x4)
  5344. */
  5345. var Matrix = /** @class */ (function () {
  5346. /**
  5347. * Creates an empty matrix (filled with zeros)
  5348. */
  5349. function Matrix() {
  5350. this._isIdentity = false;
  5351. this._isIdentityDirty = true;
  5352. /**
  5353. * Gets or sets the internal data of the matrix
  5354. */
  5355. this.m = new Float32Array(16);
  5356. this._markAsUpdated();
  5357. }
  5358. /** @hidden */
  5359. Matrix.prototype._markAsUpdated = function () {
  5360. this.updateFlag = Matrix._updateFlagSeed++;
  5361. this._isIdentityDirty = true;
  5362. };
  5363. // Properties
  5364. /**
  5365. * Check if the current matrix is indentity
  5366. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5367. * @returns true is the matrix is the identity matrix
  5368. */
  5369. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5370. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5371. if (this._isIdentityDirty) {
  5372. this._isIdentityDirty = false;
  5373. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5374. this._isIdentity = false;
  5375. }
  5376. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5377. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5378. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5379. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5380. this._isIdentity = false;
  5381. }
  5382. else {
  5383. this._isIdentity = true;
  5384. }
  5385. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5386. this._isIdentity = false;
  5387. }
  5388. }
  5389. return this._isIdentity;
  5390. };
  5391. /**
  5392. * Gets the determinant of the matrix
  5393. * @returns the matrix determinant
  5394. */
  5395. Matrix.prototype.determinant = function () {
  5396. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5397. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5398. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5399. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5400. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5401. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5402. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5403. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5404. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5405. };
  5406. // Methods
  5407. /**
  5408. * Returns the matrix as a Float32Array
  5409. * @returns the matrix underlying array
  5410. */
  5411. Matrix.prototype.toArray = function () {
  5412. return this.m;
  5413. };
  5414. /**
  5415. * Returns the matrix as a Float32Array
  5416. * @returns the matrix underlying array.
  5417. */
  5418. Matrix.prototype.asArray = function () {
  5419. return this.toArray();
  5420. };
  5421. /**
  5422. * Inverts the current matrix in place
  5423. * @returns the current inverted matrix
  5424. */
  5425. Matrix.prototype.invert = function () {
  5426. this.invertToRef(this);
  5427. return this;
  5428. };
  5429. /**
  5430. * Sets all the matrix elements to zero
  5431. * @returns the current matrix
  5432. */
  5433. Matrix.prototype.reset = function () {
  5434. for (var index = 0; index < 16; index++) {
  5435. this.m[index] = 0.0;
  5436. }
  5437. this._markAsUpdated();
  5438. return this;
  5439. };
  5440. /**
  5441. * Adds the current matrix with a second one
  5442. * @param other defines the matrix to add
  5443. * @returns a new matrix as the addition of the current matrix and the given one
  5444. */
  5445. Matrix.prototype.add = function (other) {
  5446. var result = new Matrix();
  5447. this.addToRef(other, result);
  5448. return result;
  5449. };
  5450. /**
  5451. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5452. * @param other defines the matrix to add
  5453. * @param result defines the target matrix
  5454. * @returns the current matrix
  5455. */
  5456. Matrix.prototype.addToRef = function (other, result) {
  5457. for (var index = 0; index < 16; index++) {
  5458. result.m[index] = this.m[index] + other.m[index];
  5459. }
  5460. result._markAsUpdated();
  5461. return this;
  5462. };
  5463. /**
  5464. * Adds in place the given matrix to the current matrix
  5465. * @param other defines the second operand
  5466. * @returns the current updated matrix
  5467. */
  5468. Matrix.prototype.addToSelf = function (other) {
  5469. for (var index = 0; index < 16; index++) {
  5470. this.m[index] += other.m[index];
  5471. }
  5472. this._markAsUpdated();
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the given matrix to the current inverted Matrix
  5477. * @param other defines the target matrix
  5478. * @returns the unmodified current matrix
  5479. */
  5480. Matrix.prototype.invertToRef = function (other) {
  5481. var l1 = this.m[0];
  5482. var l2 = this.m[1];
  5483. var l3 = this.m[2];
  5484. var l4 = this.m[3];
  5485. var l5 = this.m[4];
  5486. var l6 = this.m[5];
  5487. var l7 = this.m[6];
  5488. var l8 = this.m[7];
  5489. var l9 = this.m[8];
  5490. var l10 = this.m[9];
  5491. var l11 = this.m[10];
  5492. var l12 = this.m[11];
  5493. var l13 = this.m[12];
  5494. var l14 = this.m[13];
  5495. var l15 = this.m[14];
  5496. var l16 = this.m[15];
  5497. var l17 = (l11 * l16) - (l12 * l15);
  5498. var l18 = (l10 * l16) - (l12 * l14);
  5499. var l19 = (l10 * l15) - (l11 * l14);
  5500. var l20 = (l9 * l16) - (l12 * l13);
  5501. var l21 = (l9 * l15) - (l11 * l13);
  5502. var l22 = (l9 * l14) - (l10 * l13);
  5503. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5504. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5505. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5506. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5507. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5508. var l28 = (l7 * l16) - (l8 * l15);
  5509. var l29 = (l6 * l16) - (l8 * l14);
  5510. var l30 = (l6 * l15) - (l7 * l14);
  5511. var l31 = (l5 * l16) - (l8 * l13);
  5512. var l32 = (l5 * l15) - (l7 * l13);
  5513. var l33 = (l5 * l14) - (l6 * l13);
  5514. var l34 = (l7 * l12) - (l8 * l11);
  5515. var l35 = (l6 * l12) - (l8 * l10);
  5516. var l36 = (l6 * l11) - (l7 * l10);
  5517. var l37 = (l5 * l12) - (l8 * l9);
  5518. var l38 = (l5 * l11) - (l7 * l9);
  5519. var l39 = (l5 * l10) - (l6 * l9);
  5520. other.m[0] = l23 * l27;
  5521. other.m[4] = l24 * l27;
  5522. other.m[8] = l25 * l27;
  5523. other.m[12] = l26 * l27;
  5524. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5525. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5526. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5527. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5528. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5529. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5530. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5531. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5532. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5533. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5534. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5535. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5536. other._markAsUpdated();
  5537. return this;
  5538. };
  5539. /**
  5540. * Inserts the translation vector (using 3 floats) in the current matrix
  5541. * @param x defines the 1st component of the translation
  5542. * @param y defines the 2nd component of the translation
  5543. * @param z defines the 3rd component of the translation
  5544. * @returns the current updated matrix
  5545. */
  5546. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5547. this.m[12] = x;
  5548. this.m[13] = y;
  5549. this.m[14] = z;
  5550. this._markAsUpdated();
  5551. return this;
  5552. };
  5553. /**
  5554. * Inserts the translation vector in the current matrix
  5555. * @param vector3 defines the translation to insert
  5556. * @returns the current updated matrix
  5557. */
  5558. Matrix.prototype.setTranslation = function (vector3) {
  5559. this.m[12] = vector3.x;
  5560. this.m[13] = vector3.y;
  5561. this.m[14] = vector3.z;
  5562. this._markAsUpdated();
  5563. return this;
  5564. };
  5565. /**
  5566. * Gets the translation value of the current matrix
  5567. * @returns a new Vector3 as the extracted translation from the matrix
  5568. */
  5569. Matrix.prototype.getTranslation = function () {
  5570. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5571. };
  5572. /**
  5573. * Fill a Vector3 with the extracted translation from the matrix
  5574. * @param result defines the Vector3 where to store the translation
  5575. * @returns the current matrix
  5576. */
  5577. Matrix.prototype.getTranslationToRef = function (result) {
  5578. result.x = this.m[12];
  5579. result.y = this.m[13];
  5580. result.z = this.m[14];
  5581. return this;
  5582. };
  5583. /**
  5584. * Remove rotation and scaling part from the matrix
  5585. * @returns the updated matrix
  5586. */
  5587. Matrix.prototype.removeRotationAndScaling = function () {
  5588. this.setRowFromFloats(0, 1, 0, 0, 0);
  5589. this.setRowFromFloats(1, 0, 1, 0, 0);
  5590. this.setRowFromFloats(2, 0, 0, 1, 0);
  5591. return this;
  5592. };
  5593. /**
  5594. * Multiply two matrices
  5595. * @param other defines the second operand
  5596. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5597. */
  5598. Matrix.prototype.multiply = function (other) {
  5599. var result = new Matrix();
  5600. this.multiplyToRef(other, result);
  5601. return result;
  5602. };
  5603. /**
  5604. * Copy the current matrix from the given one
  5605. * @param other defines the source matrix
  5606. * @returns the current updated matrix
  5607. */
  5608. Matrix.prototype.copyFrom = function (other) {
  5609. for (var index = 0; index < 16; index++) {
  5610. this.m[index] = other.m[index];
  5611. }
  5612. this._markAsUpdated();
  5613. return this;
  5614. };
  5615. /**
  5616. * Populates the given array from the starting index with the current matrix values
  5617. * @param array defines the target array
  5618. * @param offset defines the offset in the target array where to start storing values
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.copyToArray = function (array, offset) {
  5622. if (offset === void 0) { offset = 0; }
  5623. for (var index = 0; index < 16; index++) {
  5624. array[offset + index] = this.m[index];
  5625. }
  5626. return this;
  5627. };
  5628. /**
  5629. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5630. * @param other defines the second operand
  5631. * @param result defines the matrix where to store the multiplication
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.multiplyToRef = function (other, result) {
  5635. this.multiplyToArray(other, result.m, 0);
  5636. result._markAsUpdated();
  5637. return this;
  5638. };
  5639. /**
  5640. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5641. * @param other defines the second operand
  5642. * @param result defines the array where to store the multiplication
  5643. * @param offset defines the offset in the target array where to start storing values
  5644. * @returns the current matrix
  5645. */
  5646. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5647. var tm0 = this.m[0];
  5648. var tm1 = this.m[1];
  5649. var tm2 = this.m[2];
  5650. var tm3 = this.m[3];
  5651. var tm4 = this.m[4];
  5652. var tm5 = this.m[5];
  5653. var tm6 = this.m[6];
  5654. var tm7 = this.m[7];
  5655. var tm8 = this.m[8];
  5656. var tm9 = this.m[9];
  5657. var tm10 = this.m[10];
  5658. var tm11 = this.m[11];
  5659. var tm12 = this.m[12];
  5660. var tm13 = this.m[13];
  5661. var tm14 = this.m[14];
  5662. var tm15 = this.m[15];
  5663. var om0 = other.m[0];
  5664. var om1 = other.m[1];
  5665. var om2 = other.m[2];
  5666. var om3 = other.m[3];
  5667. var om4 = other.m[4];
  5668. var om5 = other.m[5];
  5669. var om6 = other.m[6];
  5670. var om7 = other.m[7];
  5671. var om8 = other.m[8];
  5672. var om9 = other.m[9];
  5673. var om10 = other.m[10];
  5674. var om11 = other.m[11];
  5675. var om12 = other.m[12];
  5676. var om13 = other.m[13];
  5677. var om14 = other.m[14];
  5678. var om15 = other.m[15];
  5679. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5680. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5681. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5682. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5683. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5684. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5685. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5686. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5687. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5688. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5689. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5690. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5691. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5692. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5693. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5694. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5695. return this;
  5696. };
  5697. /**
  5698. * Check equality between this matrix and a second one
  5699. * @param value defines the second matrix to compare
  5700. * @returns true is the current matrix and the given one values are strictly equal
  5701. */
  5702. Matrix.prototype.equals = function (value) {
  5703. return value &&
  5704. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5705. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5706. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5707. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5708. };
  5709. /**
  5710. * Clone the current matrix
  5711. * @returns a new matrix from the current matrix
  5712. */
  5713. Matrix.prototype.clone = function () {
  5714. 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]);
  5715. };
  5716. /**
  5717. * Returns the name of the current matrix class
  5718. * @returns the string "Matrix"
  5719. */
  5720. Matrix.prototype.getClassName = function () {
  5721. return "Matrix";
  5722. };
  5723. /**
  5724. * Gets the hash code of the current matrix
  5725. * @returns the hash code
  5726. */
  5727. Matrix.prototype.getHashCode = function () {
  5728. var hash = this.m[0] || 0;
  5729. for (var i = 1; i < 16; i++) {
  5730. hash = (hash * 397) ^ (this.m[i] || 0);
  5731. }
  5732. return hash;
  5733. };
  5734. /**
  5735. * Decomposes the current Matrix into a translation, rotation and scaling components
  5736. * @param scale defines the scale vector3 given as a reference to update
  5737. * @param rotation defines the rotation quaternion given as a reference to update
  5738. * @param translation defines the translation vector3 given as a reference to update
  5739. * @returns true if operation was successful
  5740. */
  5741. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5742. if (translation) {
  5743. translation.x = this.m[12];
  5744. translation.y = this.m[13];
  5745. translation.z = this.m[14];
  5746. }
  5747. scale = scale || MathTmp.Vector3[0];
  5748. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5749. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5750. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5751. if (this.determinant() <= 0) {
  5752. scale.y *= -1;
  5753. }
  5754. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5755. if (rotation) {
  5756. rotation.x = 0;
  5757. rotation.y = 0;
  5758. rotation.z = 0;
  5759. rotation.w = 1;
  5760. }
  5761. return false;
  5762. }
  5763. if (rotation) {
  5764. 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]);
  5765. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5766. }
  5767. return true;
  5768. };
  5769. /**
  5770. * Gets specific row of the matrix
  5771. * @param index defines the number of the row to get
  5772. * @returns the index-th row of the current matrix as a new Vector4
  5773. */
  5774. Matrix.prototype.getRow = function (index) {
  5775. if (index < 0 || index > 3) {
  5776. return null;
  5777. }
  5778. var i = index * 4;
  5779. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5780. };
  5781. /**
  5782. * Sets the index-th row of the current matrix to the vector4 values
  5783. * @param index defines the number of the row to set
  5784. * @param row defines the target vector4
  5785. * @returns the updated current matrix
  5786. */
  5787. Matrix.prototype.setRow = function (index, row) {
  5788. if (index < 0 || index > 3) {
  5789. return this;
  5790. }
  5791. var i = index * 4;
  5792. this.m[i + 0] = row.x;
  5793. this.m[i + 1] = row.y;
  5794. this.m[i + 2] = row.z;
  5795. this.m[i + 3] = row.w;
  5796. this._markAsUpdated();
  5797. return this;
  5798. };
  5799. /**
  5800. * Compute the transpose of the matrix
  5801. * @returns the new transposed matrix
  5802. */
  5803. Matrix.prototype.transpose = function () {
  5804. return Matrix.Transpose(this);
  5805. };
  5806. /**
  5807. * Compute the transpose of the matrix and store it in a given matrix
  5808. * @param result defines the target matrix
  5809. * @returns the current matrix
  5810. */
  5811. Matrix.prototype.transposeToRef = function (result) {
  5812. Matrix.TransposeToRef(this, result);
  5813. return this;
  5814. };
  5815. /**
  5816. * Sets the index-th row of the current matrix with the given 4 x float values
  5817. * @param index defines the row index
  5818. * @param x defines the x component to set
  5819. * @param y defines the y component to set
  5820. * @param z defines the z component to set
  5821. * @param w defines the w component to set
  5822. * @returns the updated current matrix
  5823. */
  5824. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5825. if (index < 0 || index > 3) {
  5826. return this;
  5827. }
  5828. var i = index * 4;
  5829. this.m[i + 0] = x;
  5830. this.m[i + 1] = y;
  5831. this.m[i + 2] = z;
  5832. this.m[i + 3] = w;
  5833. this._markAsUpdated();
  5834. return this;
  5835. };
  5836. /**
  5837. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5838. * @param scale defines the scale factor
  5839. * @returns a new matrix
  5840. */
  5841. Matrix.prototype.scale = function (scale) {
  5842. var result = new Matrix();
  5843. this.scaleToRef(scale, result);
  5844. return result;
  5845. };
  5846. /**
  5847. * Scale the current matrix values by a factor to a given result matrix
  5848. * @param scale defines the scale factor
  5849. * @param result defines the matrix to store the result
  5850. * @returns the current matrix
  5851. */
  5852. Matrix.prototype.scaleToRef = function (scale, result) {
  5853. for (var index = 0; index < 16; index++) {
  5854. result.m[index] = this.m[index] * scale;
  5855. }
  5856. result._markAsUpdated();
  5857. return this;
  5858. };
  5859. /**
  5860. * Scale the current matrix values by a factor and add the result to a given matrix
  5861. * @param scale defines the scale factor
  5862. * @param result defines the Matrix to store the result
  5863. * @returns the current matrix
  5864. */
  5865. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5866. for (var index = 0; index < 16; index++) {
  5867. result.m[index] += this.m[index] * scale;
  5868. }
  5869. result._markAsUpdated();
  5870. return this;
  5871. };
  5872. /**
  5873. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5874. * @param ref matrix to store the result
  5875. */
  5876. Matrix.prototype.toNormalMatrix = function (ref) {
  5877. this.invertToRef(ref);
  5878. ref.transpose();
  5879. var m = ref.m;
  5880. 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);
  5881. };
  5882. /**
  5883. * Gets only rotation part of the current matrix
  5884. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5885. */
  5886. Matrix.prototype.getRotationMatrix = function () {
  5887. var result = Matrix.Identity();
  5888. this.getRotationMatrixToRef(result);
  5889. return result;
  5890. };
  5891. /**
  5892. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5893. * @param result defines the target matrix to store data to
  5894. * @returns the current matrix
  5895. */
  5896. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5897. var m = this.m;
  5898. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5899. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5900. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5901. if (this.determinant() <= 0) {
  5902. sy *= -1;
  5903. }
  5904. if (sx === 0 || sy === 0 || sz === 0) {
  5905. Matrix.IdentityToRef(result);
  5906. }
  5907. else {
  5908. 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);
  5909. }
  5910. return this;
  5911. };
  5912. // Statics
  5913. /**
  5914. * Creates a matrix from an array
  5915. * @param array defines the source array
  5916. * @param offset defines an offset in the source array
  5917. * @returns a new Matrix set from the starting index of the given array
  5918. */
  5919. Matrix.FromArray = function (array, offset) {
  5920. var result = new Matrix();
  5921. if (!offset) {
  5922. offset = 0;
  5923. }
  5924. Matrix.FromArrayToRef(array, offset, result);
  5925. return result;
  5926. };
  5927. /**
  5928. * Copy the content of an array into a given matrix
  5929. * @param array defines the source array
  5930. * @param offset defines an offset in the source array
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.FromArrayToRef = function (array, offset, result) {
  5934. for (var index = 0; index < 16; index++) {
  5935. result.m[index] = array[index + offset];
  5936. }
  5937. result._markAsUpdated();
  5938. };
  5939. /**
  5940. * Stores an array into a matrix after having multiplied each component by a given factor
  5941. * @param array defines the source array
  5942. * @param offset defines the offset in the source array
  5943. * @param scale defines the scaling factor
  5944. * @param result defines the target matrix
  5945. */
  5946. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5947. for (var index = 0; index < 16; index++) {
  5948. result.m[index] = array[index + offset] * scale;
  5949. }
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Stores a list of values (16) inside a given matrix
  5954. * @param initialM11 defines 1st value of 1st row
  5955. * @param initialM12 defines 2nd value of 1st row
  5956. * @param initialM13 defines 3rd value of 1st row
  5957. * @param initialM14 defines 4th value of 1st row
  5958. * @param initialM21 defines 1st value of 2nd row
  5959. * @param initialM22 defines 2nd value of 2nd row
  5960. * @param initialM23 defines 3rd value of 2nd row
  5961. * @param initialM24 defines 4th value of 2nd row
  5962. * @param initialM31 defines 1st value of 3rd row
  5963. * @param initialM32 defines 2nd value of 3rd row
  5964. * @param initialM33 defines 3rd value of 3rd row
  5965. * @param initialM34 defines 4th value of 3rd row
  5966. * @param initialM41 defines 1st value of 4th row
  5967. * @param initialM42 defines 2nd value of 4th row
  5968. * @param initialM43 defines 3rd value of 4th row
  5969. * @param initialM44 defines 4th value of 4th row
  5970. * @param result defines the target matrix
  5971. */
  5972. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5973. result.m[0] = initialM11;
  5974. result.m[1] = initialM12;
  5975. result.m[2] = initialM13;
  5976. result.m[3] = initialM14;
  5977. result.m[4] = initialM21;
  5978. result.m[5] = initialM22;
  5979. result.m[6] = initialM23;
  5980. result.m[7] = initialM24;
  5981. result.m[8] = initialM31;
  5982. result.m[9] = initialM32;
  5983. result.m[10] = initialM33;
  5984. result.m[11] = initialM34;
  5985. result.m[12] = initialM41;
  5986. result.m[13] = initialM42;
  5987. result.m[14] = initialM43;
  5988. result.m[15] = initialM44;
  5989. result._markAsUpdated();
  5990. };
  5991. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5992. /**
  5993. * Gets an identity matrix that must not be updated
  5994. */
  5995. get: function () {
  5996. return Matrix._identityReadOnly;
  5997. },
  5998. enumerable: true,
  5999. configurable: true
  6000. });
  6001. /**
  6002. * Creates new matrix from a list of values (16)
  6003. * @param initialM11 defines 1st value of 1st row
  6004. * @param initialM12 defines 2nd value of 1st row
  6005. * @param initialM13 defines 3rd value of 1st row
  6006. * @param initialM14 defines 4th value of 1st row
  6007. * @param initialM21 defines 1st value of 2nd row
  6008. * @param initialM22 defines 2nd value of 2nd row
  6009. * @param initialM23 defines 3rd value of 2nd row
  6010. * @param initialM24 defines 4th value of 2nd row
  6011. * @param initialM31 defines 1st value of 3rd row
  6012. * @param initialM32 defines 2nd value of 3rd row
  6013. * @param initialM33 defines 3rd value of 3rd row
  6014. * @param initialM34 defines 4th value of 3rd row
  6015. * @param initialM41 defines 1st value of 4th row
  6016. * @param initialM42 defines 2nd value of 4th row
  6017. * @param initialM43 defines 3rd value of 4th row
  6018. * @param initialM44 defines 4th value of 4th row
  6019. * @returns the new matrix
  6020. */
  6021. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6022. var result = new Matrix();
  6023. result.m[0] = initialM11;
  6024. result.m[1] = initialM12;
  6025. result.m[2] = initialM13;
  6026. result.m[3] = initialM14;
  6027. result.m[4] = initialM21;
  6028. result.m[5] = initialM22;
  6029. result.m[6] = initialM23;
  6030. result.m[7] = initialM24;
  6031. result.m[8] = initialM31;
  6032. result.m[9] = initialM32;
  6033. result.m[10] = initialM33;
  6034. result.m[11] = initialM34;
  6035. result.m[12] = initialM41;
  6036. result.m[13] = initialM42;
  6037. result.m[14] = initialM43;
  6038. result.m[15] = initialM44;
  6039. return result;
  6040. };
  6041. /**
  6042. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6043. * @param scale defines the scale vector3
  6044. * @param rotation defines the rotation quaternion
  6045. * @param translation defines the translation vector3
  6046. * @returns a new matrix
  6047. */
  6048. Matrix.Compose = function (scale, rotation, translation) {
  6049. var result = Matrix.Identity();
  6050. Matrix.ComposeToRef(scale, rotation, translation, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6055. * @param scale defines the scale vector3
  6056. * @param rotation defines the rotation quaternion
  6057. * @param translation defines the translation vector3
  6058. * @param result defines the target matrix
  6059. */
  6060. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6061. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6062. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6063. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6064. result.setTranslation(translation);
  6065. };
  6066. /**
  6067. * Creates a new identity matrix
  6068. * @returns a new identity matrix
  6069. */
  6070. Matrix.Identity = function () {
  6071. 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);
  6072. };
  6073. /**
  6074. * Creates a new identity matrix and stores the result in a given matrix
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.IdentityToRef = function (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, 0.0, 0.0, 0.0, 1.0, result);
  6079. };
  6080. /**
  6081. * Creates a new zero matrix
  6082. * @returns a new zero matrix
  6083. */
  6084. Matrix.Zero = function () {
  6085. 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);
  6086. };
  6087. /**
  6088. * Creates a new rotation matrix for "angle" radians around the X axis
  6089. * @param angle defines the angle (in radians) to use
  6090. * @return the new matrix
  6091. */
  6092. Matrix.RotationX = function (angle) {
  6093. var result = new Matrix();
  6094. Matrix.RotationXToRef(angle, result);
  6095. return result;
  6096. };
  6097. /**
  6098. * Creates a new matrix as the invert of a given matrix
  6099. * @param source defines the source matrix
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.Invert = function (source) {
  6103. var result = new Matrix();
  6104. source.invertToRef(result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6109. * @param angle defines the angle (in radians) to use
  6110. * @param result defines the target matrix
  6111. */
  6112. Matrix.RotationXToRef = function (angle, result) {
  6113. var s = Math.sin(angle);
  6114. var c = Math.cos(angle);
  6115. result.m[0] = 1.0;
  6116. result.m[15] = 1.0;
  6117. result.m[5] = c;
  6118. result.m[10] = c;
  6119. result.m[9] = -s;
  6120. result.m[6] = s;
  6121. result.m[1] = 0.0;
  6122. result.m[2] = 0.0;
  6123. result.m[3] = 0.0;
  6124. result.m[4] = 0.0;
  6125. result.m[7] = 0.0;
  6126. result.m[8] = 0.0;
  6127. result.m[11] = 0.0;
  6128. result.m[12] = 0.0;
  6129. result.m[13] = 0.0;
  6130. result.m[14] = 0.0;
  6131. result._markAsUpdated();
  6132. };
  6133. /**
  6134. * Creates a new rotation matrix for "angle" radians around the Y axis
  6135. * @param angle defines the angle (in radians) to use
  6136. * @return the new matrix
  6137. */
  6138. Matrix.RotationY = function (angle) {
  6139. var result = new Matrix();
  6140. Matrix.RotationYToRef(angle, result);
  6141. return result;
  6142. };
  6143. /**
  6144. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6145. * @param angle defines the angle (in radians) to use
  6146. * @param result defines the target matrix
  6147. */
  6148. Matrix.RotationYToRef = function (angle, result) {
  6149. var s = Math.sin(angle);
  6150. var c = Math.cos(angle);
  6151. result.m[5] = 1.0;
  6152. result.m[15] = 1.0;
  6153. result.m[0] = c;
  6154. result.m[2] = -s;
  6155. result.m[8] = s;
  6156. result.m[10] = c;
  6157. result.m[1] = 0.0;
  6158. result.m[3] = 0.0;
  6159. result.m[4] = 0.0;
  6160. result.m[6] = 0.0;
  6161. result.m[7] = 0.0;
  6162. result.m[9] = 0.0;
  6163. result.m[11] = 0.0;
  6164. result.m[12] = 0.0;
  6165. result.m[13] = 0.0;
  6166. result.m[14] = 0.0;
  6167. result._markAsUpdated();
  6168. };
  6169. /**
  6170. * Creates a new rotation matrix for "angle" radians around the Z axis
  6171. * @param angle defines the angle (in radians) to use
  6172. * @return the new matrix
  6173. */
  6174. Matrix.RotationZ = function (angle) {
  6175. var result = new Matrix();
  6176. Matrix.RotationZToRef(angle, result);
  6177. return result;
  6178. };
  6179. /**
  6180. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6181. * @param angle defines the angle (in radians) to use
  6182. * @param result defines the target matrix
  6183. */
  6184. Matrix.RotationZToRef = function (angle, result) {
  6185. var s = Math.sin(angle);
  6186. var c = Math.cos(angle);
  6187. result.m[10] = 1.0;
  6188. result.m[15] = 1.0;
  6189. result.m[0] = c;
  6190. result.m[1] = s;
  6191. result.m[4] = -s;
  6192. result.m[5] = c;
  6193. result.m[2] = 0.0;
  6194. result.m[3] = 0.0;
  6195. result.m[6] = 0.0;
  6196. result.m[7] = 0.0;
  6197. result.m[8] = 0.0;
  6198. result.m[9] = 0.0;
  6199. result.m[11] = 0.0;
  6200. result.m[12] = 0.0;
  6201. result.m[13] = 0.0;
  6202. result.m[14] = 0.0;
  6203. result._markAsUpdated();
  6204. };
  6205. /**
  6206. * Creates a new rotation matrix for "angle" radians around the given axis
  6207. * @param axis defines the axis to use
  6208. * @param angle defines the angle (in radians) to use
  6209. * @return the new matrix
  6210. */
  6211. Matrix.RotationAxis = function (axis, angle) {
  6212. var result = Matrix.Zero();
  6213. Matrix.RotationAxisToRef(axis, angle, result);
  6214. return result;
  6215. };
  6216. /**
  6217. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6218. * @param axis defines the axis to use
  6219. * @param angle defines the angle (in radians) to use
  6220. * @param result defines the target matrix
  6221. */
  6222. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6223. var s = Math.sin(-angle);
  6224. var c = Math.cos(-angle);
  6225. var c1 = 1 - c;
  6226. axis.normalize();
  6227. result.m[0] = (axis.x * axis.x) * c1 + c;
  6228. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6229. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6230. result.m[3] = 0.0;
  6231. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6232. result.m[5] = (axis.y * axis.y) * c1 + c;
  6233. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6234. result.m[7] = 0.0;
  6235. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6236. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6237. result.m[10] = (axis.z * axis.z) * c1 + c;
  6238. result.m[11] = 0.0;
  6239. result.m[15] = 1.0;
  6240. result._markAsUpdated();
  6241. };
  6242. /**
  6243. * Creates a rotation matrix
  6244. * @param yaw defines the yaw angle in radians (Y axis)
  6245. * @param pitch defines the pitch angle in radians (X axis)
  6246. * @param roll defines the roll angle in radians (X axis)
  6247. * @returns the new rotation matrix
  6248. */
  6249. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6250. var result = new Matrix();
  6251. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6252. return result;
  6253. };
  6254. /**
  6255. * Creates a rotation matrix and stores it in a given matrix
  6256. * @param yaw defines the yaw angle in radians (Y axis)
  6257. * @param pitch defines the pitch angle in radians (X axis)
  6258. * @param roll defines the roll angle in radians (X axis)
  6259. * @param result defines the target matrix
  6260. */
  6261. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6262. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6263. this._tempQuaternion.toRotationMatrix(result);
  6264. };
  6265. /**
  6266. * Creates a scaling matrix
  6267. * @param x defines the scale factor on X axis
  6268. * @param y defines the scale factor on Y axis
  6269. * @param z defines the scale factor on Z axis
  6270. * @returns the new matrix
  6271. */
  6272. Matrix.Scaling = function (x, y, z) {
  6273. var result = Matrix.Zero();
  6274. Matrix.ScalingToRef(x, y, z, result);
  6275. return result;
  6276. };
  6277. /**
  6278. * Creates a scaling matrix and stores it in a given matrix
  6279. * @param x defines the scale factor on X axis
  6280. * @param y defines the scale factor on Y axis
  6281. * @param z defines the scale factor on Z axis
  6282. * @param result defines the target matrix
  6283. */
  6284. Matrix.ScalingToRef = function (x, y, z, result) {
  6285. result.m[0] = x;
  6286. result.m[1] = 0.0;
  6287. result.m[2] = 0.0;
  6288. result.m[3] = 0.0;
  6289. result.m[4] = 0.0;
  6290. result.m[5] = y;
  6291. result.m[6] = 0.0;
  6292. result.m[7] = 0.0;
  6293. result.m[8] = 0.0;
  6294. result.m[9] = 0.0;
  6295. result.m[10] = z;
  6296. result.m[11] = 0.0;
  6297. result.m[12] = 0.0;
  6298. result.m[13] = 0.0;
  6299. result.m[14] = 0.0;
  6300. result.m[15] = 1.0;
  6301. result._markAsUpdated();
  6302. };
  6303. /**
  6304. * Creates a translation matrix
  6305. * @param x defines the translation on X axis
  6306. * @param y defines the translation on Y axis
  6307. * @param z defines the translationon Z axis
  6308. * @returns the new matrix
  6309. */
  6310. Matrix.Translation = function (x, y, z) {
  6311. var result = Matrix.Identity();
  6312. Matrix.TranslationToRef(x, y, z, result);
  6313. return result;
  6314. };
  6315. /**
  6316. * Creates a translation matrix and stores it in a given matrix
  6317. * @param x defines the translation on X axis
  6318. * @param y defines the translation on Y axis
  6319. * @param z defines the translationon Z axis
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.TranslationToRef = function (x, y, z, result) {
  6323. 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);
  6324. };
  6325. /**
  6326. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6327. * @param startValue defines the start value
  6328. * @param endValue defines the end value
  6329. * @param gradient defines the gradient factor
  6330. * @returns the new matrix
  6331. */
  6332. Matrix.Lerp = function (startValue, endValue, gradient) {
  6333. var result = Matrix.Zero();
  6334. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6335. return result;
  6336. };
  6337. /**
  6338. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6339. * @param startValue defines the start value
  6340. * @param endValue defines the end value
  6341. * @param gradient defines the gradient factor
  6342. * @param result defines the Matrix object where to store data
  6343. */
  6344. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6345. for (var index = 0; index < 16; index++) {
  6346. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6347. }
  6348. result._markAsUpdated();
  6349. };
  6350. /**
  6351. * Builds a new matrix whose values are computed by:
  6352. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6353. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6354. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6355. * @param startValue defines the first matrix
  6356. * @param endValue defines the second matrix
  6357. * @param gradient defines the gradient between the two matrices
  6358. * @returns the new matrix
  6359. */
  6360. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6361. var result = Matrix.Zero();
  6362. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6363. return result;
  6364. };
  6365. /**
  6366. * Update a matrix to values which are computed by:
  6367. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6368. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6369. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6370. * @param startValue defines the first matrix
  6371. * @param endValue defines the second matrix
  6372. * @param gradient defines the gradient between the two matrices
  6373. * @param result defines the target matrix
  6374. */
  6375. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6376. var startScale = MathTmp.Vector3[0];
  6377. var startRotation = MathTmp.Quaternion[0];
  6378. var startTranslation = MathTmp.Vector3[1];
  6379. startValue.decompose(startScale, startRotation, startTranslation);
  6380. var endScale = MathTmp.Vector3[2];
  6381. var endRotation = MathTmp.Quaternion[1];
  6382. var endTranslation = MathTmp.Vector3[3];
  6383. endValue.decompose(endScale, endRotation, endTranslation);
  6384. var resultScale = MathTmp.Vector3[4];
  6385. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6386. var resultRotation = MathTmp.Quaternion[2];
  6387. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6388. var resultTranslation = MathTmp.Vector3[5];
  6389. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6390. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6391. };
  6392. /**
  6393. * 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"
  6394. * This function works in left handed mode
  6395. * @param eye defines the final position of the entity
  6396. * @param target defines where the entity should look at
  6397. * @param up defines the up vector for the entity
  6398. * @returns the new matrix
  6399. */
  6400. Matrix.LookAtLH = function (eye, target, up) {
  6401. var result = Matrix.Zero();
  6402. Matrix.LookAtLHToRef(eye, target, up, result);
  6403. return result;
  6404. };
  6405. /**
  6406. * 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".
  6407. * This function works in left handed mode
  6408. * @param eye defines the final position of the entity
  6409. * @param target defines where the entity should look at
  6410. * @param up defines the up vector for the entity
  6411. * @param result defines the target matrix
  6412. */
  6413. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6414. // Z axis
  6415. target.subtractToRef(eye, this._zAxis);
  6416. this._zAxis.normalize();
  6417. // X axis
  6418. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6419. if (this._xAxis.lengthSquared() === 0) {
  6420. this._xAxis.x = 1.0;
  6421. }
  6422. else {
  6423. this._xAxis.normalize();
  6424. }
  6425. // Y axis
  6426. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6427. this._yAxis.normalize();
  6428. // Eye angles
  6429. var ex = -Vector3.Dot(this._xAxis, eye);
  6430. var ey = -Vector3.Dot(this._yAxis, eye);
  6431. var ez = -Vector3.Dot(this._zAxis, eye);
  6432. 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);
  6433. };
  6434. /**
  6435. * 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"
  6436. * This function works in right handed mode
  6437. * @param eye defines the final position of the entity
  6438. * @param target defines where the entity should look at
  6439. * @param up defines the up vector for the entity
  6440. * @returns the new matrix
  6441. */
  6442. Matrix.LookAtRH = function (eye, target, up) {
  6443. var result = Matrix.Zero();
  6444. Matrix.LookAtRHToRef(eye, target, up, result);
  6445. return result;
  6446. };
  6447. /**
  6448. * 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".
  6449. * This function works in right handed mode
  6450. * @param eye defines the final position of the entity
  6451. * @param target defines where the entity should look at
  6452. * @param up defines the up vector for the entity
  6453. * @param result defines the target matrix
  6454. */
  6455. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6456. // Z axis
  6457. eye.subtractToRef(target, this._zAxis);
  6458. this._zAxis.normalize();
  6459. // X axis
  6460. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6461. if (this._xAxis.lengthSquared() === 0) {
  6462. this._xAxis.x = 1.0;
  6463. }
  6464. else {
  6465. this._xAxis.normalize();
  6466. }
  6467. // Y axis
  6468. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6469. this._yAxis.normalize();
  6470. // Eye angles
  6471. var ex = -Vector3.Dot(this._xAxis, eye);
  6472. var ey = -Vector3.Dot(this._yAxis, eye);
  6473. var ez = -Vector3.Dot(this._zAxis, eye);
  6474. 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);
  6475. };
  6476. /**
  6477. * Create a left-handed orthographic projection matrix
  6478. * @param width defines the viewport width
  6479. * @param height defines the viewport height
  6480. * @param znear defines the near clip plane
  6481. * @param zfar defines the far clip plane
  6482. * @returns a new matrix as a left-handed orthographic projection matrix
  6483. */
  6484. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6485. var matrix = Matrix.Zero();
  6486. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6487. return matrix;
  6488. };
  6489. /**
  6490. * Store a left-handed orthographic projection to a given matrix
  6491. * @param width defines the viewport width
  6492. * @param height defines the viewport height
  6493. * @param znear defines the near clip plane
  6494. * @param zfar defines the far clip plane
  6495. * @param result defines the target matrix
  6496. */
  6497. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6498. var n = znear;
  6499. var f = zfar;
  6500. var a = 2.0 / width;
  6501. var b = 2.0 / height;
  6502. var c = 2.0 / (f - n);
  6503. var d = -(f + n) / (f - n);
  6504. 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);
  6505. };
  6506. /**
  6507. * Create a left-handed orthographic projection matrix
  6508. * @param left defines the viewport left coordinate
  6509. * @param right defines the viewport right coordinate
  6510. * @param bottom defines the viewport bottom coordinate
  6511. * @param top defines the viewport top coordinate
  6512. * @param znear defines the near clip plane
  6513. * @param zfar defines the far clip plane
  6514. * @returns a new matrix as a left-handed orthographic projection matrix
  6515. */
  6516. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6517. var matrix = Matrix.Zero();
  6518. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6519. return matrix;
  6520. };
  6521. /**
  6522. * Stores a left-handed orthographic projection into a given matrix
  6523. * @param left defines the viewport left coordinate
  6524. * @param right defines the viewport right coordinate
  6525. * @param bottom defines the viewport bottom coordinate
  6526. * @param top defines the viewport top coordinate
  6527. * @param znear defines the near clip plane
  6528. * @param zfar defines the far clip plane
  6529. * @param result defines the target matrix
  6530. */
  6531. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6532. var n = znear;
  6533. var f = zfar;
  6534. var a = 2.0 / (right - left);
  6535. var b = 2.0 / (top - bottom);
  6536. var c = 2.0 / (f - n);
  6537. var d = -(f + n) / (f - n);
  6538. var i0 = (left + right) / (left - right);
  6539. var i1 = (top + bottom) / (bottom - top);
  6540. 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);
  6541. };
  6542. /**
  6543. * Creates a right-handed orthographic projection matrix
  6544. * @param left defines the viewport left coordinate
  6545. * @param right defines the viewport right coordinate
  6546. * @param bottom defines the viewport bottom coordinate
  6547. * @param top defines the viewport top coordinate
  6548. * @param znear defines the near clip plane
  6549. * @param zfar defines the far clip plane
  6550. * @returns a new matrix as a right-handed orthographic projection matrix
  6551. */
  6552. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6553. var matrix = Matrix.Zero();
  6554. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6555. return matrix;
  6556. };
  6557. /**
  6558. * Stores a right-handed orthographic projection into a given matrix
  6559. * @param left defines the viewport left coordinate
  6560. * @param right defines the viewport right coordinate
  6561. * @param bottom defines the viewport bottom coordinate
  6562. * @param top defines the viewport top coordinate
  6563. * @param znear defines the near clip plane
  6564. * @param zfar defines the far clip plane
  6565. * @param result defines the target matrix
  6566. */
  6567. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6569. result.m[10] *= -1.0;
  6570. };
  6571. /**
  6572. * Creates a left-handed perspective projection matrix
  6573. * @param width defines the viewport width
  6574. * @param height defines the viewport height
  6575. * @param znear defines the near clip plane
  6576. * @param zfar defines the far clip plane
  6577. * @returns a new matrix as a left-handed perspective projection matrix
  6578. */
  6579. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6580. var matrix = Matrix.Zero();
  6581. var n = znear;
  6582. var f = zfar;
  6583. var a = 2.0 * n / width;
  6584. var b = 2.0 * n / height;
  6585. var c = (f + n) / (f - n);
  6586. var d = -2.0 * f * n / (f - n);
  6587. 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);
  6588. return matrix;
  6589. };
  6590. /**
  6591. * Creates a left-handed perspective projection matrix
  6592. * @param fov defines the horizontal field of view
  6593. * @param aspect defines the aspect ratio
  6594. * @param znear defines the near clip plane
  6595. * @param zfar defines the far clip plane
  6596. * @returns a new matrix as a left-handed perspective projection matrix
  6597. */
  6598. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6599. var matrix = Matrix.Zero();
  6600. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6601. return matrix;
  6602. };
  6603. /**
  6604. * Stores a left-handed perspective projection into a given matrix
  6605. * @param fov defines the horizontal field of view
  6606. * @param aspect defines the aspect ratio
  6607. * @param znear defines the near clip plane
  6608. * @param zfar defines the far clip plane
  6609. * @param result defines the target matrix
  6610. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6611. */
  6612. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6613. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6614. var n = znear;
  6615. var f = zfar;
  6616. var t = 1.0 / (Math.tan(fov * 0.5));
  6617. var a = isVerticalFovFixed ? (t / aspect) : t;
  6618. var b = isVerticalFovFixed ? t : (t * aspect);
  6619. var c = (f + n) / (f - n);
  6620. var d = -2.0 * f * n / (f - n);
  6621. 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);
  6622. };
  6623. /**
  6624. * Creates a right-handed perspective projection matrix
  6625. * @param fov defines the horizontal field of view
  6626. * @param aspect defines the aspect ratio
  6627. * @param znear defines the near clip plane
  6628. * @param zfar defines the far clip plane
  6629. * @returns a new matrix as a right-handed perspective projection matrix
  6630. */
  6631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6632. var matrix = Matrix.Zero();
  6633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6634. return matrix;
  6635. };
  6636. /**
  6637. * Stores a right-handed perspective projection into a given matrix
  6638. * @param fov defines the horizontal field of view
  6639. * @param aspect defines the aspect ratio
  6640. * @param znear defines the near clip plane
  6641. * @param zfar defines the far clip plane
  6642. * @param result defines the target matrix
  6643. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6644. */
  6645. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6646. //alternatively this could be expressed as:
  6647. // m = PerspectiveFovLHToRef
  6648. // m[10] *= -1.0;
  6649. // m[11] *= -1.0;
  6650. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6651. var n = znear;
  6652. var f = zfar;
  6653. var t = 1.0 / (Math.tan(fov * 0.5));
  6654. var a = isVerticalFovFixed ? (t / aspect) : t;
  6655. var b = isVerticalFovFixed ? t : (t * aspect);
  6656. var c = -(f + n) / (f - n);
  6657. var d = -2 * f * n / (f - n);
  6658. 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);
  6659. };
  6660. /**
  6661. * Stores a perspective projection for WebVR info a given matrix
  6662. * @param fov defines the field of view
  6663. * @param znear defines the near clip plane
  6664. * @param zfar defines the far clip plane
  6665. * @param result defines the target matrix
  6666. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6667. */
  6668. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6669. if (rightHanded === void 0) { rightHanded = false; }
  6670. var rightHandedFactor = rightHanded ? -1 : 1;
  6671. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6672. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6673. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6674. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6675. var xScale = 2.0 / (leftTan + rightTan);
  6676. var yScale = 2.0 / (upTan + downTan);
  6677. result.m[0] = xScale;
  6678. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6679. result.m[5] = yScale;
  6680. result.m[6] = result.m[7] = 0.0;
  6681. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6682. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6683. result.m[10] = -zfar / (znear - zfar);
  6684. result.m[11] = 1.0 * rightHandedFactor;
  6685. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6686. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6687. result._markAsUpdated();
  6688. };
  6689. /**
  6690. * Computes a complete transformation matrix
  6691. * @param viewport defines the viewport to use
  6692. * @param world defines the world matrix
  6693. * @param view defines the view matrix
  6694. * @param projection defines the projection matrix
  6695. * @param zmin defines the near clip plane
  6696. * @param zmax defines the far clip plane
  6697. * @returns the transformation matrix
  6698. */
  6699. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6700. var cw = viewport.width;
  6701. var ch = viewport.height;
  6702. var cx = viewport.x;
  6703. var cy = viewport.y;
  6704. 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);
  6705. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6706. };
  6707. /**
  6708. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6709. * @param matrix defines the matrix to use
  6710. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6711. */
  6712. Matrix.GetAsMatrix2x2 = function (matrix) {
  6713. return new Float32Array([
  6714. matrix.m[0], matrix.m[1],
  6715. matrix.m[4], matrix.m[5]
  6716. ]);
  6717. };
  6718. /**
  6719. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6720. * @param matrix defines the matrix to use
  6721. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6722. */
  6723. Matrix.GetAsMatrix3x3 = function (matrix) {
  6724. return new Float32Array([
  6725. matrix.m[0], matrix.m[1], matrix.m[2],
  6726. matrix.m[4], matrix.m[5], matrix.m[6],
  6727. matrix.m[8], matrix.m[9], matrix.m[10]
  6728. ]);
  6729. };
  6730. /**
  6731. * Compute the transpose of a given matrix
  6732. * @param matrix defines the matrix to transpose
  6733. * @returns the new matrix
  6734. */
  6735. Matrix.Transpose = function (matrix) {
  6736. var result = new Matrix();
  6737. Matrix.TransposeToRef(matrix, result);
  6738. return result;
  6739. };
  6740. /**
  6741. * Compute the transpose of a matrix and store it in a target matrix
  6742. * @param matrix defines the matrix to transpose
  6743. * @param result defines the target matrix
  6744. */
  6745. Matrix.TransposeToRef = function (matrix, result) {
  6746. result.m[0] = matrix.m[0];
  6747. result.m[1] = matrix.m[4];
  6748. result.m[2] = matrix.m[8];
  6749. result.m[3] = matrix.m[12];
  6750. result.m[4] = matrix.m[1];
  6751. result.m[5] = matrix.m[5];
  6752. result.m[6] = matrix.m[9];
  6753. result.m[7] = matrix.m[13];
  6754. result.m[8] = matrix.m[2];
  6755. result.m[9] = matrix.m[6];
  6756. result.m[10] = matrix.m[10];
  6757. result.m[11] = matrix.m[14];
  6758. result.m[12] = matrix.m[3];
  6759. result.m[13] = matrix.m[7];
  6760. result.m[14] = matrix.m[11];
  6761. result.m[15] = matrix.m[15];
  6762. };
  6763. /**
  6764. * Computes a reflection matrix from a plane
  6765. * @param plane defines the reflection plane
  6766. * @returns a new matrix
  6767. */
  6768. Matrix.Reflection = function (plane) {
  6769. var matrix = new Matrix();
  6770. Matrix.ReflectionToRef(plane, matrix);
  6771. return matrix;
  6772. };
  6773. /**
  6774. * Computes a reflection matrix from a plane
  6775. * @param plane defines the reflection plane
  6776. * @param result defines the target matrix
  6777. */
  6778. Matrix.ReflectionToRef = function (plane, result) {
  6779. plane.normalize();
  6780. var x = plane.normal.x;
  6781. var y = plane.normal.y;
  6782. var z = plane.normal.z;
  6783. var temp = -2 * x;
  6784. var temp2 = -2 * y;
  6785. var temp3 = -2 * z;
  6786. result.m[0] = (temp * x) + 1;
  6787. result.m[1] = temp2 * x;
  6788. result.m[2] = temp3 * x;
  6789. result.m[3] = 0.0;
  6790. result.m[4] = temp * y;
  6791. result.m[5] = (temp2 * y) + 1;
  6792. result.m[6] = temp3 * y;
  6793. result.m[7] = 0.0;
  6794. result.m[8] = temp * z;
  6795. result.m[9] = temp2 * z;
  6796. result.m[10] = (temp3 * z) + 1;
  6797. result.m[11] = 0.0;
  6798. result.m[12] = temp * plane.d;
  6799. result.m[13] = temp2 * plane.d;
  6800. result.m[14] = temp3 * plane.d;
  6801. result.m[15] = 1.0;
  6802. result._markAsUpdated();
  6803. };
  6804. /**
  6805. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6806. * @param xaxis defines the value of the 1st axis
  6807. * @param yaxis defines the value of the 2nd axis
  6808. * @param zaxis defines the value of the 3rd axis
  6809. * @param result defines the target matrix
  6810. */
  6811. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6812. result.m[0] = xaxis.x;
  6813. result.m[1] = xaxis.y;
  6814. result.m[2] = xaxis.z;
  6815. result.m[3] = 0.0;
  6816. result.m[4] = yaxis.x;
  6817. result.m[5] = yaxis.y;
  6818. result.m[6] = yaxis.z;
  6819. result.m[7] = 0.0;
  6820. result.m[8] = zaxis.x;
  6821. result.m[9] = zaxis.y;
  6822. result.m[10] = zaxis.z;
  6823. result.m[11] = 0.0;
  6824. result.m[12] = 0.0;
  6825. result.m[13] = 0.0;
  6826. result.m[14] = 0.0;
  6827. result.m[15] = 1.0;
  6828. result._markAsUpdated();
  6829. };
  6830. /**
  6831. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6832. * @param quat defines the quaternion to use
  6833. * @param result defines the target matrix
  6834. */
  6835. Matrix.FromQuaternionToRef = function (quat, result) {
  6836. var xx = quat.x * quat.x;
  6837. var yy = quat.y * quat.y;
  6838. var zz = quat.z * quat.z;
  6839. var xy = quat.x * quat.y;
  6840. var zw = quat.z * quat.w;
  6841. var zx = quat.z * quat.x;
  6842. var yw = quat.y * quat.w;
  6843. var yz = quat.y * quat.z;
  6844. var xw = quat.x * quat.w;
  6845. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6846. result.m[1] = 2.0 * (xy + zw);
  6847. result.m[2] = 2.0 * (zx - yw);
  6848. result.m[3] = 0.0;
  6849. result.m[4] = 2.0 * (xy - zw);
  6850. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6851. result.m[6] = 2.0 * (yz + xw);
  6852. result.m[7] = 0.0;
  6853. result.m[8] = 2.0 * (zx + yw);
  6854. result.m[9] = 2.0 * (yz - xw);
  6855. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6856. result.m[11] = 0.0;
  6857. result.m[12] = 0.0;
  6858. result.m[13] = 0.0;
  6859. result.m[14] = 0.0;
  6860. result.m[15] = 1.0;
  6861. result._markAsUpdated();
  6862. };
  6863. Matrix._tempQuaternion = new Quaternion();
  6864. Matrix._xAxis = Vector3.Zero();
  6865. Matrix._yAxis = Vector3.Zero();
  6866. Matrix._zAxis = Vector3.Zero();
  6867. Matrix._updateFlagSeed = 0;
  6868. Matrix._identityReadOnly = Matrix.Identity();
  6869. return Matrix;
  6870. }());
  6871. BABYLON.Matrix = Matrix;
  6872. /**
  6873. * Represens a plane by the equation ax + by + cz + d = 0
  6874. */
  6875. var Plane = /** @class */ (function () {
  6876. /**
  6877. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6878. * @param a a component of the plane
  6879. * @param b b component of the plane
  6880. * @param c c component of the plane
  6881. * @param d d component of the plane
  6882. */
  6883. function Plane(a, b, c, d) {
  6884. this.normal = new Vector3(a, b, c);
  6885. this.d = d;
  6886. }
  6887. /**
  6888. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6889. */
  6890. Plane.prototype.asArray = function () {
  6891. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6892. };
  6893. // Methods
  6894. /**
  6895. * @returns a new plane copied from the current Plane.
  6896. */
  6897. Plane.prototype.clone = function () {
  6898. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6899. };
  6900. /**
  6901. * @returns the string "Plane".
  6902. */
  6903. Plane.prototype.getClassName = function () {
  6904. return "Plane";
  6905. };
  6906. /**
  6907. * @returns the Plane hash code.
  6908. */
  6909. Plane.prototype.getHashCode = function () {
  6910. var hash = this.normal.getHashCode();
  6911. hash = (hash * 397) ^ (this.d || 0);
  6912. return hash;
  6913. };
  6914. /**
  6915. * Normalize the current Plane in place.
  6916. * @returns the updated Plane.
  6917. */
  6918. Plane.prototype.normalize = function () {
  6919. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6920. var magnitude = 0.0;
  6921. if (norm !== 0) {
  6922. magnitude = 1.0 / norm;
  6923. }
  6924. this.normal.x *= magnitude;
  6925. this.normal.y *= magnitude;
  6926. this.normal.z *= magnitude;
  6927. this.d *= magnitude;
  6928. return this;
  6929. };
  6930. /**
  6931. * Applies a transformation the plane and returns the result
  6932. * @param transformation the transformation matrix to be applied to the plane
  6933. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6934. */
  6935. Plane.prototype.transform = function (transformation) {
  6936. var transposedMatrix = Matrix.Transpose(transformation);
  6937. var x = this.normal.x;
  6938. var y = this.normal.y;
  6939. var z = this.normal.z;
  6940. var d = this.d;
  6941. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6942. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6943. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6944. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6945. return new Plane(normalX, normalY, normalZ, finalD);
  6946. };
  6947. /**
  6948. * Calcualtte the dot product between the point and the plane normal
  6949. * @param point point to calculate the dot product with
  6950. * @returns the dot product (float) of the point coordinates and the plane normal.
  6951. */
  6952. Plane.prototype.dotCoordinate = function (point) {
  6953. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6954. };
  6955. /**
  6956. * Updates the current Plane from the plane defined by the three given points.
  6957. * @param point1 one of the points used to contruct the plane
  6958. * @param point2 one of the points used to contruct the plane
  6959. * @param point3 one of the points used to contruct the plane
  6960. * @returns the updated Plane.
  6961. */
  6962. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6963. var x1 = point2.x - point1.x;
  6964. var y1 = point2.y - point1.y;
  6965. var z1 = point2.z - point1.z;
  6966. var x2 = point3.x - point1.x;
  6967. var y2 = point3.y - point1.y;
  6968. var z2 = point3.z - point1.z;
  6969. var yz = (y1 * z2) - (z1 * y2);
  6970. var xz = (z1 * x2) - (x1 * z2);
  6971. var xy = (x1 * y2) - (y1 * x2);
  6972. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6973. var invPyth;
  6974. if (pyth !== 0) {
  6975. invPyth = 1.0 / pyth;
  6976. }
  6977. else {
  6978. invPyth = 0.0;
  6979. }
  6980. this.normal.x = yz * invPyth;
  6981. this.normal.y = xz * invPyth;
  6982. this.normal.z = xy * invPyth;
  6983. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6984. return this;
  6985. };
  6986. /**
  6987. * Checks if the plane is facing a given direction
  6988. * @param direction the direction to check if the plane is facing
  6989. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6990. * @returns True is the vector "direction" is the same side than the plane normal.
  6991. */
  6992. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6993. var dot = Vector3.Dot(this.normal, direction);
  6994. return (dot <= epsilon);
  6995. };
  6996. /**
  6997. * Calculates the distance to a point
  6998. * @param point point to calculate distance to
  6999. * @returns the signed distance (float) from the given point to the Plane.
  7000. */
  7001. Plane.prototype.signedDistanceTo = function (point) {
  7002. return Vector3.Dot(point, this.normal) + this.d;
  7003. };
  7004. // Statics
  7005. /**
  7006. * Creates a plane from an array
  7007. * @param array the array to create a plane from
  7008. * @returns a new Plane from the given array.
  7009. */
  7010. Plane.FromArray = function (array) {
  7011. return new Plane(array[0], array[1], array[2], array[3]);
  7012. };
  7013. /**
  7014. * Creates a plane from three points
  7015. * @param point1 point used to create the plane
  7016. * @param point2 point used to create the plane
  7017. * @param point3 point used to create the plane
  7018. * @returns a new Plane defined by the three given points.
  7019. */
  7020. Plane.FromPoints = function (point1, point2, point3) {
  7021. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7022. result.copyFromPoints(point1, point2, point3);
  7023. return result;
  7024. };
  7025. /**
  7026. * Creates a plane from an origin point and a normal
  7027. * @param origin origin of the plane to be constructed
  7028. * @param normal normal of the plane to be constructed
  7029. * @returns a new Plane the normal vector to this plane at the given origin point.
  7030. * Note : the vector "normal" is updated because normalized.
  7031. */
  7032. Plane.FromPositionAndNormal = function (origin, normal) {
  7033. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7034. normal.normalize();
  7035. result.normal = normal;
  7036. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7037. return result;
  7038. };
  7039. /**
  7040. * Calculates the distance from a plane and a point
  7041. * @param origin origin of the plane to be constructed
  7042. * @param normal normal of the plane to be constructed
  7043. * @param point point to calculate distance to
  7044. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7045. */
  7046. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7047. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7048. return Vector3.Dot(point, normal) + d;
  7049. };
  7050. return Plane;
  7051. }());
  7052. BABYLON.Plane = Plane;
  7053. /**
  7054. * Class used to represent a viewport on screen
  7055. */
  7056. var Viewport = /** @class */ (function () {
  7057. /**
  7058. * Creates a Viewport object located at (x, y) and sized (width, height)
  7059. * @param x defines viewport left coordinate
  7060. * @param y defines viewport top coordinate
  7061. * @param width defines the viewport width
  7062. * @param height defines the viewport height
  7063. */
  7064. function Viewport(
  7065. /** viewport left coordinate */
  7066. x,
  7067. /** viewport top coordinate */
  7068. y,
  7069. /**viewport width */
  7070. width,
  7071. /** viewport height */
  7072. height) {
  7073. this.x = x;
  7074. this.y = y;
  7075. this.width = width;
  7076. this.height = height;
  7077. }
  7078. /**
  7079. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7080. * @param renderWidthOrEngine defines either an engine or the rendering width
  7081. * @param renderHeight defines the rendering height
  7082. * @returns a new Viewport
  7083. */
  7084. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7085. if (renderWidthOrEngine.getRenderWidth) {
  7086. var engine = renderWidthOrEngine;
  7087. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7088. }
  7089. var renderWidth = renderWidthOrEngine;
  7090. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7091. };
  7092. /**
  7093. * Returns a new Viewport copied from the current one
  7094. * @returns a new Viewport
  7095. */
  7096. Viewport.prototype.clone = function () {
  7097. return new Viewport(this.x, this.y, this.width, this.height);
  7098. };
  7099. return Viewport;
  7100. }());
  7101. BABYLON.Viewport = Viewport;
  7102. /**
  7103. * Reprasents a camera frustum
  7104. */
  7105. var Frustum = /** @class */ (function () {
  7106. function Frustum() {
  7107. }
  7108. /**
  7109. * Gets the planes representing the frustum
  7110. * @param transform matrix to be applied to the returned planes
  7111. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7112. */
  7113. Frustum.GetPlanes = function (transform) {
  7114. var frustumPlanes = [];
  7115. for (var index = 0; index < 6; index++) {
  7116. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7117. }
  7118. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7119. return frustumPlanes;
  7120. };
  7121. /**
  7122. * Gets the near frustum plane transformed by the transform matrix
  7123. * @param transform transformation matrix to be applied to the resulting frustum plane
  7124. * @param frustumPlane the resuling frustum plane
  7125. */
  7126. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7127. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7128. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7129. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7130. frustumPlane.d = transform.m[15] + transform.m[14];
  7131. frustumPlane.normalize();
  7132. };
  7133. /**
  7134. * Gets the far frustum plane transformed by the transform matrix
  7135. * @param transform transformation matrix to be applied to the resulting frustum plane
  7136. * @param frustumPlane the resuling frustum plane
  7137. */
  7138. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7139. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7140. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7141. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7142. frustumPlane.d = transform.m[15] - transform.m[14];
  7143. frustumPlane.normalize();
  7144. };
  7145. /**
  7146. * Gets the left frustum plane transformed by the transform matrix
  7147. * @param transform transformation matrix to be applied to the resulting frustum plane
  7148. * @param frustumPlane the resuling frustum plane
  7149. */
  7150. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7151. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7152. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7153. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7154. frustumPlane.d = transform.m[15] + transform.m[12];
  7155. frustumPlane.normalize();
  7156. };
  7157. /**
  7158. * Gets the right frustum plane transformed by the transform matrix
  7159. * @param transform transformation matrix to be applied to the resulting frustum plane
  7160. * @param frustumPlane the resuling frustum plane
  7161. */
  7162. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7163. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7164. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7165. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7166. frustumPlane.d = transform.m[15] - transform.m[12];
  7167. frustumPlane.normalize();
  7168. };
  7169. /**
  7170. * Gets the top frustum plane transformed by the transform matrix
  7171. * @param transform transformation matrix to be applied to the resulting frustum plane
  7172. * @param frustumPlane the resuling frustum plane
  7173. */
  7174. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7175. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7176. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7177. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7178. frustumPlane.d = transform.m[15] - transform.m[13];
  7179. frustumPlane.normalize();
  7180. };
  7181. /**
  7182. * Gets the bottom frustum plane transformed by the transform matrix
  7183. * @param transform transformation matrix to be applied to the resulting frustum plane
  7184. * @param frustumPlane the resuling frustum plane
  7185. */
  7186. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7187. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7188. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7189. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7190. frustumPlane.d = transform.m[15] + transform.m[13];
  7191. frustumPlane.normalize();
  7192. };
  7193. /**
  7194. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7195. * @param transform transformation matrix to be applied to the resulting frustum planes
  7196. * @param frustumPlanes the resuling frustum planes
  7197. */
  7198. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7199. // Near
  7200. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7201. // Far
  7202. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7203. // Left
  7204. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7205. // Right
  7206. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7207. // Top
  7208. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7209. // Bottom
  7210. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7211. };
  7212. return Frustum;
  7213. }());
  7214. BABYLON.Frustum = Frustum;
  7215. /** Defines supported spaces */
  7216. var Space;
  7217. (function (Space) {
  7218. /** Local (object) space */
  7219. Space[Space["LOCAL"] = 0] = "LOCAL";
  7220. /** World space */
  7221. Space[Space["WORLD"] = 1] = "WORLD";
  7222. /** Bone space */
  7223. Space[Space["BONE"] = 2] = "BONE";
  7224. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7225. /** Defines the 3 main axes */
  7226. var Axis = /** @class */ (function () {
  7227. function Axis() {
  7228. }
  7229. /** X axis */
  7230. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7231. /** Y axis */
  7232. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7233. /** Z axis */
  7234. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7235. return Axis;
  7236. }());
  7237. BABYLON.Axis = Axis;
  7238. ;
  7239. /** Class used to represent a Bezier curve */
  7240. var BezierCurve = /** @class */ (function () {
  7241. function BezierCurve() {
  7242. }
  7243. /**
  7244. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7245. * @param t defines the time
  7246. * @param x1 defines the left coordinate on X axis
  7247. * @param y1 defines the left coordinate on Y axis
  7248. * @param x2 defines the right coordinate on X axis
  7249. * @param y2 defines the right coordinate on Y axis
  7250. * @returns the interpolated value
  7251. */
  7252. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7253. // Extract X (which is equal to time here)
  7254. var f0 = 1 - 3 * x2 + 3 * x1;
  7255. var f1 = 3 * x2 - 6 * x1;
  7256. var f2 = 3 * x1;
  7257. var refinedT = t;
  7258. for (var i = 0; i < 5; i++) {
  7259. var refinedT2 = refinedT * refinedT;
  7260. var refinedT3 = refinedT2 * refinedT;
  7261. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7262. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7263. refinedT -= (x - t) * slope;
  7264. refinedT = Math.min(1, Math.max(0, refinedT));
  7265. }
  7266. // Resolve cubic bezier for the given x
  7267. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7268. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7269. Math.pow(refinedT, 3);
  7270. };
  7271. return BezierCurve;
  7272. }());
  7273. BABYLON.BezierCurve = BezierCurve;
  7274. /**
  7275. * Defines potential orientation for back face culling
  7276. */
  7277. var Orientation;
  7278. (function (Orientation) {
  7279. /**
  7280. * Clockwise
  7281. */
  7282. Orientation[Orientation["CW"] = 0] = "CW";
  7283. /** Counter clockwise */
  7284. Orientation[Orientation["CCW"] = 1] = "CCW";
  7285. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7286. /**
  7287. * Defines angle representation
  7288. */
  7289. var Angle = /** @class */ (function () {
  7290. /**
  7291. * Creates an Angle object of "radians" radians (float).
  7292. */
  7293. function Angle(radians) {
  7294. this._radians = radians;
  7295. if (this._radians < 0.0)
  7296. this._radians += (2.0 * Math.PI);
  7297. }
  7298. /**
  7299. * Get value in degrees
  7300. * @returns the Angle value in degrees (float)
  7301. */
  7302. Angle.prototype.degrees = function () {
  7303. return this._radians * 180.0 / Math.PI;
  7304. };
  7305. /**
  7306. * Get value in radians
  7307. * @returns the Angle value in radians (float)
  7308. */
  7309. Angle.prototype.radians = function () {
  7310. return this._radians;
  7311. };
  7312. /**
  7313. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7314. * @param a defines first vector
  7315. * @param b defines second vector
  7316. * @returns a new Angle
  7317. */
  7318. Angle.BetweenTwoPoints = function (a, b) {
  7319. var delta = b.subtract(a);
  7320. var theta = Math.atan2(delta.y, delta.x);
  7321. return new Angle(theta);
  7322. };
  7323. /**
  7324. * Gets a new Angle object from the given float in radians
  7325. * @param radians defines the angle value in radians
  7326. * @returns a new Angle
  7327. */
  7328. Angle.FromRadians = function (radians) {
  7329. return new Angle(radians);
  7330. };
  7331. /**
  7332. * Gets a new Angle object from the given float in degrees
  7333. * @param degrees defines the angle value in degrees
  7334. * @returns a new Angle
  7335. */
  7336. Angle.FromDegrees = function (degrees) {
  7337. return new Angle(degrees * Math.PI / 180.0);
  7338. };
  7339. return Angle;
  7340. }());
  7341. BABYLON.Angle = Angle;
  7342. /**
  7343. * This represents an arc in a 2d space.
  7344. */
  7345. var Arc2 = /** @class */ (function () {
  7346. /**
  7347. * Creates an Arc object from the three given points : start, middle and end.
  7348. * @param startPoint Defines the start point of the arc
  7349. * @param midPoint Defines the midlle point of the arc
  7350. * @param endPoint Defines the end point of the arc
  7351. */
  7352. function Arc2(
  7353. /** Defines the start point of the arc */
  7354. startPoint,
  7355. /** Defines the mid point of the arc */
  7356. midPoint,
  7357. /** Defines the end point of the arc */
  7358. endPoint) {
  7359. this.startPoint = startPoint;
  7360. this.midPoint = midPoint;
  7361. this.endPoint = endPoint;
  7362. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7363. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7364. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7365. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7366. 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);
  7367. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7368. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7369. var a1 = this.startAngle.degrees();
  7370. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7371. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7372. // angles correction
  7373. if (a2 - a1 > +180.0)
  7374. a2 -= 360.0;
  7375. if (a2 - a1 < -180.0)
  7376. a2 += 360.0;
  7377. if (a3 - a2 > +180.0)
  7378. a3 -= 360.0;
  7379. if (a3 - a2 < -180.0)
  7380. a3 += 360.0;
  7381. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7382. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7383. }
  7384. return Arc2;
  7385. }());
  7386. BABYLON.Arc2 = Arc2;
  7387. /**
  7388. * Represents a 2D path made up of multiple 2D points
  7389. */
  7390. var Path2 = /** @class */ (function () {
  7391. /**
  7392. * Creates a Path2 object from the starting 2D coordinates x and y.
  7393. * @param x the starting points x value
  7394. * @param y the starting points y value
  7395. */
  7396. function Path2(x, y) {
  7397. this._points = new Array();
  7398. this._length = 0.0;
  7399. /**
  7400. * If the path start and end point are the same
  7401. */
  7402. this.closed = false;
  7403. this._points.push(new Vector2(x, y));
  7404. }
  7405. /**
  7406. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7407. * @param x the added points x value
  7408. * @param y the added points y value
  7409. * @returns the updated Path2.
  7410. */
  7411. Path2.prototype.addLineTo = function (x, y) {
  7412. if (this.closed) {
  7413. return this;
  7414. }
  7415. var newPoint = new Vector2(x, y);
  7416. var previousPoint = this._points[this._points.length - 1];
  7417. this._points.push(newPoint);
  7418. this._length += newPoint.subtract(previousPoint).length();
  7419. return this;
  7420. };
  7421. /**
  7422. * 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.
  7423. * @param midX middle point x value
  7424. * @param midY middle point y value
  7425. * @param endX end point x value
  7426. * @param endY end point y value
  7427. * @param numberOfSegments (default: 36)
  7428. * @returns the updated Path2.
  7429. */
  7430. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7431. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7432. if (this.closed) {
  7433. return this;
  7434. }
  7435. var startPoint = this._points[this._points.length - 1];
  7436. var midPoint = new Vector2(midX, midY);
  7437. var endPoint = new Vector2(endX, endY);
  7438. var arc = new Arc2(startPoint, midPoint, endPoint);
  7439. var increment = arc.angle.radians() / numberOfSegments;
  7440. if (arc.orientation === Orientation.CW)
  7441. increment *= -1;
  7442. var currentAngle = arc.startAngle.radians() + increment;
  7443. for (var i = 0; i < numberOfSegments; i++) {
  7444. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7445. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7446. this.addLineTo(x, y);
  7447. currentAngle += increment;
  7448. }
  7449. return this;
  7450. };
  7451. /**
  7452. * Closes the Path2.
  7453. * @returns the Path2.
  7454. */
  7455. Path2.prototype.close = function () {
  7456. this.closed = true;
  7457. return this;
  7458. };
  7459. /**
  7460. * Gets the sum of the distance between each sequential point in the path
  7461. * @returns the Path2 total length (float).
  7462. */
  7463. Path2.prototype.length = function () {
  7464. var result = this._length;
  7465. if (!this.closed) {
  7466. var lastPoint = this._points[this._points.length - 1];
  7467. var firstPoint = this._points[0];
  7468. result += (firstPoint.subtract(lastPoint).length());
  7469. }
  7470. return result;
  7471. };
  7472. /**
  7473. * Gets the points which construct the path
  7474. * @returns the Path2 internal array of points.
  7475. */
  7476. Path2.prototype.getPoints = function () {
  7477. return this._points;
  7478. };
  7479. /**
  7480. * Retreives the point at the distance aways from the starting point
  7481. * @param normalizedLengthPosition the length along the path to retreive the point from
  7482. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7483. */
  7484. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7485. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7486. return Vector2.Zero();
  7487. }
  7488. var lengthPosition = normalizedLengthPosition * this.length();
  7489. var previousOffset = 0;
  7490. for (var i = 0; i < this._points.length; i++) {
  7491. var j = (i + 1) % this._points.length;
  7492. var a = this._points[i];
  7493. var b = this._points[j];
  7494. var bToA = b.subtract(a);
  7495. var nextOffset = (bToA.length() + previousOffset);
  7496. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7497. var dir = bToA.normalize();
  7498. var localOffset = lengthPosition - previousOffset;
  7499. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7500. }
  7501. previousOffset = nextOffset;
  7502. }
  7503. return Vector2.Zero();
  7504. };
  7505. /**
  7506. * Creates a new path starting from an x and y position
  7507. * @param x starting x value
  7508. * @param y starting y value
  7509. * @returns a new Path2 starting at the coordinates (x, y).
  7510. */
  7511. Path2.StartingAt = function (x, y) {
  7512. return new Path2(x, y);
  7513. };
  7514. return Path2;
  7515. }());
  7516. BABYLON.Path2 = Path2;
  7517. /**
  7518. * Represents a 3D path made up of multiple 3D points
  7519. */
  7520. var Path3D = /** @class */ (function () {
  7521. /**
  7522. * new Path3D(path, normal, raw)
  7523. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7524. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7525. * @param path an array of Vector3, the curve axis of the Path3D
  7526. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7527. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7528. */
  7529. function Path3D(
  7530. /**
  7531. * an array of Vector3, the curve axis of the Path3D
  7532. */
  7533. path, firstNormal, raw) {
  7534. if (firstNormal === void 0) { firstNormal = null; }
  7535. this.path = path;
  7536. this._curve = new Array();
  7537. this._distances = new Array();
  7538. this._tangents = new Array();
  7539. this._normals = new Array();
  7540. this._binormals = new Array();
  7541. for (var p = 0; p < path.length; p++) {
  7542. this._curve[p] = path[p].clone(); // hard copy
  7543. }
  7544. this._raw = raw || false;
  7545. this._compute(firstNormal);
  7546. }
  7547. /**
  7548. * Returns the Path3D array of successive Vector3 designing its curve.
  7549. * @returns the Path3D array of successive Vector3 designing its curve.
  7550. */
  7551. Path3D.prototype.getCurve = function () {
  7552. return this._curve;
  7553. };
  7554. /**
  7555. * Returns an array populated with tangent vectors on each Path3D curve point.
  7556. * @returns an array populated with tangent vectors on each Path3D curve point.
  7557. */
  7558. Path3D.prototype.getTangents = function () {
  7559. return this._tangents;
  7560. };
  7561. /**
  7562. * Returns an array populated with normal vectors on each Path3D curve point.
  7563. * @returns an array populated with normal vectors on each Path3D curve point.
  7564. */
  7565. Path3D.prototype.getNormals = function () {
  7566. return this._normals;
  7567. };
  7568. /**
  7569. * Returns an array populated with binormal vectors on each Path3D curve point.
  7570. * @returns an array populated with binormal vectors on each Path3D curve point.
  7571. */
  7572. Path3D.prototype.getBinormals = function () {
  7573. return this._binormals;
  7574. };
  7575. /**
  7576. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7577. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7578. */
  7579. Path3D.prototype.getDistances = function () {
  7580. return this._distances;
  7581. };
  7582. /**
  7583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7584. * @param path path which all values are copied into the curves points
  7585. * @param firstNormal which should be projected onto the curve
  7586. * @returns the same object updated.
  7587. */
  7588. Path3D.prototype.update = function (path, firstNormal) {
  7589. if (firstNormal === void 0) { firstNormal = null; }
  7590. for (var p = 0; p < path.length; p++) {
  7591. this._curve[p].x = path[p].x;
  7592. this._curve[p].y = path[p].y;
  7593. this._curve[p].z = path[p].z;
  7594. }
  7595. this._compute(firstNormal);
  7596. return this;
  7597. };
  7598. // private function compute() : computes tangents, normals and binormals
  7599. Path3D.prototype._compute = function (firstNormal) {
  7600. var l = this._curve.length;
  7601. // first and last tangents
  7602. this._tangents[0] = this._getFirstNonNullVector(0);
  7603. if (!this._raw) {
  7604. this._tangents[0].normalize();
  7605. }
  7606. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7607. if (!this._raw) {
  7608. this._tangents[l - 1].normalize();
  7609. }
  7610. // normals and binormals at first point : arbitrary vector with _normalVector()
  7611. var tg0 = this._tangents[0];
  7612. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7613. this._normals[0] = pp0;
  7614. if (!this._raw) {
  7615. this._normals[0].normalize();
  7616. }
  7617. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7618. if (!this._raw) {
  7619. this._binormals[0].normalize();
  7620. }
  7621. this._distances[0] = 0.0;
  7622. // normals and binormals : next points
  7623. var prev; // previous vector (segment)
  7624. var cur; // current vector (segment)
  7625. var curTang; // current tangent
  7626. // previous normal
  7627. var prevBinor; // previous binormal
  7628. for (var i = 1; i < l; i++) {
  7629. // tangents
  7630. prev = this._getLastNonNullVector(i);
  7631. if (i < l - 1) {
  7632. cur = this._getFirstNonNullVector(i);
  7633. this._tangents[i] = prev.add(cur);
  7634. this._tangents[i].normalize();
  7635. }
  7636. this._distances[i] = this._distances[i - 1] + prev.length();
  7637. // normals and binormals
  7638. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7639. curTang = this._tangents[i];
  7640. prevBinor = this._binormals[i - 1];
  7641. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7642. if (!this._raw) {
  7643. this._normals[i].normalize();
  7644. }
  7645. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7646. if (!this._raw) {
  7647. this._binormals[i].normalize();
  7648. }
  7649. }
  7650. };
  7651. // private function getFirstNonNullVector(index)
  7652. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7653. Path3D.prototype._getFirstNonNullVector = function (index) {
  7654. var i = 1;
  7655. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7656. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7657. i++;
  7658. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7659. }
  7660. return nNVector;
  7661. };
  7662. // private function getLastNonNullVector(index)
  7663. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7664. Path3D.prototype._getLastNonNullVector = function (index) {
  7665. var i = 1;
  7666. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7667. while (nLVector.length() === 0 && index > i + 1) {
  7668. i++;
  7669. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7670. }
  7671. return nLVector;
  7672. };
  7673. // private function normalVector(v0, vt, va) :
  7674. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7675. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7676. Path3D.prototype._normalVector = function (v0, vt, va) {
  7677. var normal0;
  7678. var tgl = vt.length();
  7679. if (tgl === 0.0) {
  7680. tgl = 1.0;
  7681. }
  7682. if (va === undefined || va === null) {
  7683. var point;
  7684. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7685. point = new Vector3(0.0, -1.0, 0.0);
  7686. }
  7687. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7688. point = new Vector3(1.0, 0.0, 0.0);
  7689. }
  7690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7691. point = new Vector3(0.0, 0.0, 1.0);
  7692. }
  7693. else {
  7694. point = Vector3.Zero();
  7695. }
  7696. normal0 = Vector3.Cross(vt, point);
  7697. }
  7698. else {
  7699. normal0 = Vector3.Cross(vt, va);
  7700. Vector3.CrossToRef(normal0, vt, normal0);
  7701. }
  7702. normal0.normalize();
  7703. return normal0;
  7704. };
  7705. return Path3D;
  7706. }());
  7707. BABYLON.Path3D = Path3D;
  7708. /**
  7709. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7710. * A Curve3 is designed from a series of successive Vector3.
  7711. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7712. */
  7713. var Curve3 = /** @class */ (function () {
  7714. /**
  7715. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7716. * A Curve3 is designed from a series of successive Vector3.
  7717. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7718. * @param points points which make up the curve
  7719. */
  7720. function Curve3(points) {
  7721. this._length = 0.0;
  7722. this._points = points;
  7723. this._length = this._computeLength(points);
  7724. }
  7725. /**
  7726. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7727. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7728. * @param v1 (Vector3) the control point
  7729. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7730. * @param nbPoints (integer) the wanted number of points in the curve
  7731. * @returns the created Curve3
  7732. */
  7733. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7734. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7735. var bez = new Array();
  7736. var equation = function (t, val0, val1, val2) {
  7737. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7738. return res;
  7739. };
  7740. for (var i = 0; i <= nbPoints; i++) {
  7741. 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)));
  7742. }
  7743. return new Curve3(bez);
  7744. };
  7745. /**
  7746. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7747. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7748. * @param v1 (Vector3) the first control point
  7749. * @param v2 (Vector3) the second control point
  7750. * @param v3 (Vector3) the end point of the Cubic Bezier
  7751. * @param nbPoints (integer) the wanted number of points in the curve
  7752. * @returns the created Curve3
  7753. */
  7754. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7755. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7756. var bez = new Array();
  7757. var equation = function (t, val0, val1, val2, val3) {
  7758. 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;
  7759. return res;
  7760. };
  7761. for (var i = 0; i <= nbPoints; i++) {
  7762. 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)));
  7763. }
  7764. return new Curve3(bez);
  7765. };
  7766. /**
  7767. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7768. * @param p1 (Vector3) the origin point of the Hermite Spline
  7769. * @param t1 (Vector3) the tangent vector at the origin point
  7770. * @param p2 (Vector3) the end point of the Hermite Spline
  7771. * @param t2 (Vector3) the tangent vector at the end point
  7772. * @param nbPoints (integer) the wanted number of points in the curve
  7773. * @returns the created Curve3
  7774. */
  7775. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7776. var hermite = new Array();
  7777. var step = 1.0 / nbPoints;
  7778. for (var i = 0; i <= nbPoints; i++) {
  7779. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7780. }
  7781. return new Curve3(hermite);
  7782. };
  7783. /**
  7784. * Returns a Curve3 object along a CatmullRom Spline curve :
  7785. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7786. * @param nbPoints (integer) the wanted number of points between each curve control points
  7787. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7788. * @returns the created Curve3
  7789. */
  7790. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7791. var catmullRom = new Array();
  7792. var step = 1.0 / nbPoints;
  7793. var amount = 0.0;
  7794. if (closed) {
  7795. var pointsCount = points.length;
  7796. for (var i = 0; i < pointsCount; i++) {
  7797. amount = 0;
  7798. for (var c = 0; c < nbPoints; c++) {
  7799. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7800. amount += step;
  7801. }
  7802. }
  7803. catmullRom.push(catmullRom[0]);
  7804. }
  7805. else {
  7806. var totalPoints = new Array();
  7807. totalPoints.push(points[0].clone());
  7808. Array.prototype.push.apply(totalPoints, points);
  7809. totalPoints.push(points[points.length - 1].clone());
  7810. for (var i = 0; i < totalPoints.length - 3; i++) {
  7811. amount = 0;
  7812. for (var c = 0; c < nbPoints; c++) {
  7813. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7814. amount += step;
  7815. }
  7816. }
  7817. i--;
  7818. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7819. }
  7820. return new Curve3(catmullRom);
  7821. };
  7822. /**
  7823. * @returns the Curve3 stored array of successive Vector3
  7824. */
  7825. Curve3.prototype.getPoints = function () {
  7826. return this._points;
  7827. };
  7828. /**
  7829. * @returns the computed length (float) of the curve.
  7830. */
  7831. Curve3.prototype.length = function () {
  7832. return this._length;
  7833. };
  7834. /**
  7835. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7836. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7837. * curveA and curveB keep unchanged.
  7838. * @param curve the curve to continue from this curve
  7839. * @returns the newly constructed curve
  7840. */
  7841. Curve3.prototype.continue = function (curve) {
  7842. var lastPoint = this._points[this._points.length - 1];
  7843. var continuedPoints = this._points.slice();
  7844. var curvePoints = curve.getPoints();
  7845. for (var i = 1; i < curvePoints.length; i++) {
  7846. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7847. }
  7848. var continuedCurve = new Curve3(continuedPoints);
  7849. return continuedCurve;
  7850. };
  7851. Curve3.prototype._computeLength = function (path) {
  7852. var l = 0;
  7853. for (var i = 1; i < path.length; i++) {
  7854. l += (path[i].subtract(path[i - 1])).length();
  7855. }
  7856. return l;
  7857. };
  7858. return Curve3;
  7859. }());
  7860. BABYLON.Curve3 = Curve3;
  7861. // Vertex formats
  7862. /**
  7863. * Contains position and normal vectors for a vertex
  7864. */
  7865. var PositionNormalVertex = /** @class */ (function () {
  7866. /**
  7867. * Creates a PositionNormalVertex
  7868. * @param position the position of the vertex (defaut: 0,0,0)
  7869. * @param normal the normal of the vertex (defaut: 0,1,0)
  7870. */
  7871. function PositionNormalVertex(
  7872. /** the position of the vertex (defaut: 0,0,0) */
  7873. position,
  7874. /** the normal of the vertex (defaut: 0,1,0) */
  7875. normal) {
  7876. if (position === void 0) { position = Vector3.Zero(); }
  7877. if (normal === void 0) { normal = Vector3.Up(); }
  7878. this.position = position;
  7879. this.normal = normal;
  7880. }
  7881. /**
  7882. * Clones the PositionNormalVertex
  7883. * @returns the cloned PositionNormalVertex
  7884. */
  7885. PositionNormalVertex.prototype.clone = function () {
  7886. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7887. };
  7888. return PositionNormalVertex;
  7889. }());
  7890. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7891. /**
  7892. * Contains position, normal and uv vectors for a vertex
  7893. */
  7894. var PositionNormalTextureVertex = /** @class */ (function () {
  7895. /**
  7896. * Creates a PositionNormalTextureVertex
  7897. * @param position the position of the vertex (defaut: 0,0,0)
  7898. * @param normal the normal of the vertex (defaut: 0,1,0)
  7899. * @param uv the uv of the vertex (default: 0,0)
  7900. */
  7901. function PositionNormalTextureVertex(
  7902. /** the position of the vertex (defaut: 0,0,0) */
  7903. position,
  7904. /** the normal of the vertex (defaut: 0,1,0) */
  7905. normal,
  7906. /** the uv of the vertex (default: 0,0) */
  7907. uv) {
  7908. if (position === void 0) { position = Vector3.Zero(); }
  7909. if (normal === void 0) { normal = Vector3.Up(); }
  7910. if (uv === void 0) { uv = Vector2.Zero(); }
  7911. this.position = position;
  7912. this.normal = normal;
  7913. this.uv = uv;
  7914. }
  7915. /**
  7916. * Clones the PositionNormalTextureVertex
  7917. * @returns the cloned PositionNormalTextureVertex
  7918. */
  7919. PositionNormalTextureVertex.prototype.clone = function () {
  7920. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7921. };
  7922. return PositionNormalTextureVertex;
  7923. }());
  7924. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7925. // Temporary pre-allocated objects for engine internal use
  7926. // usage in any internal function :
  7927. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7928. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7929. /**
  7930. * @hidden
  7931. */
  7932. var Tmp = /** @class */ (function () {
  7933. function Tmp() {
  7934. }
  7935. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7936. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7937. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7938. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7939. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7940. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7941. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7942. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7943. Matrix.Zero(), Matrix.Zero(),
  7944. Matrix.Zero(), Matrix.Zero(),
  7945. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7946. return Tmp;
  7947. }());
  7948. BABYLON.Tmp = Tmp;
  7949. /**
  7950. * @hidden
  7951. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7952. */
  7953. var MathTmp = /** @class */ (function () {
  7954. function MathTmp() {
  7955. }
  7956. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7957. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7958. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7959. return MathTmp;
  7960. }());
  7961. })(BABYLON || (BABYLON = {}));
  7962. //# sourceMappingURL=babylon.math.js.map
  7963. var BABYLON;
  7964. (function (BABYLON) {
  7965. var Scalar = /** @class */ (function () {
  7966. function Scalar() {
  7967. }
  7968. /**
  7969. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7970. */
  7971. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7972. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7973. var num = a - b;
  7974. return -epsilon <= num && num <= epsilon;
  7975. };
  7976. /**
  7977. * Returns a string : the upper case translation of the number i to hexadecimal.
  7978. */
  7979. Scalar.ToHex = function (i) {
  7980. var str = i.toString(16);
  7981. if (i <= 15) {
  7982. return ("0" + str).toUpperCase();
  7983. }
  7984. return str.toUpperCase();
  7985. };
  7986. /**
  7987. * Returns -1 if value is negative and +1 is value is positive.
  7988. * Returns the value itself if it's equal to zero.
  7989. */
  7990. Scalar.Sign = function (value) {
  7991. value = +value; // convert to a number
  7992. if (value === 0 || isNaN(value))
  7993. return value;
  7994. return value > 0 ? 1 : -1;
  7995. };
  7996. /**
  7997. * Returns the value itself if it's between min and max.
  7998. * Returns min if the value is lower than min.
  7999. * Returns max if the value is greater than max.
  8000. */
  8001. Scalar.Clamp = function (value, min, max) {
  8002. if (min === void 0) { min = 0; }
  8003. if (max === void 0) { max = 1; }
  8004. return Math.min(max, Math.max(min, value));
  8005. };
  8006. /**
  8007. * Returns the log2 of value.
  8008. */
  8009. Scalar.Log2 = function (value) {
  8010. return Math.log(value) * Math.LOG2E;
  8011. };
  8012. /**
  8013. * Loops the value, so that it is never larger than length and never smaller than 0.
  8014. *
  8015. * This is similar to the modulo operator but it works with floating point numbers.
  8016. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8017. * With t = 5 and length = 2.5, the result would be 0.0.
  8018. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8019. */
  8020. Scalar.Repeat = function (value, length) {
  8021. return value - Math.floor(value / length) * length;
  8022. };
  8023. /**
  8024. * Normalize the value between 0.0 and 1.0 using min and max values
  8025. */
  8026. Scalar.Normalize = function (value, min, max) {
  8027. return (value - min) / (max - min);
  8028. };
  8029. /**
  8030. * Denormalize the value from 0.0 and 1.0 using min and max values
  8031. */
  8032. Scalar.Denormalize = function (normalized, min, max) {
  8033. return (normalized * (max - min) + min);
  8034. };
  8035. /**
  8036. * Calculates the shortest difference between two given angles given in degrees.
  8037. */
  8038. Scalar.DeltaAngle = function (current, target) {
  8039. var num = Scalar.Repeat(target - current, 360.0);
  8040. if (num > 180.0) {
  8041. num -= 360.0;
  8042. }
  8043. return num;
  8044. };
  8045. /**
  8046. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8047. *
  8048. * The returned value will move back and forth between 0 and length
  8049. */
  8050. Scalar.PingPong = function (tx, length) {
  8051. var t = Scalar.Repeat(tx, length * 2.0);
  8052. return length - Math.abs(t - length);
  8053. };
  8054. /**
  8055. * Interpolates between min and max with smoothing at the limits.
  8056. *
  8057. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8058. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8059. */
  8060. Scalar.SmoothStep = function (from, to, tx) {
  8061. var t = Scalar.Clamp(tx);
  8062. t = -2.0 * t * t * t + 3.0 * t * t;
  8063. return to * t + from * (1.0 - t);
  8064. };
  8065. /**
  8066. * Moves a value current towards target.
  8067. *
  8068. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8069. * Negative values of maxDelta pushes the value away from target.
  8070. */
  8071. Scalar.MoveTowards = function (current, target, maxDelta) {
  8072. var result = 0;
  8073. if (Math.abs(target - current) <= maxDelta) {
  8074. result = target;
  8075. }
  8076. else {
  8077. result = current + Scalar.Sign(target - current) * maxDelta;
  8078. }
  8079. return result;
  8080. };
  8081. /**
  8082. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8083. *
  8084. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8085. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8086. */
  8087. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8088. var num = Scalar.DeltaAngle(current, target);
  8089. var result = 0;
  8090. if (-maxDelta < num && num < maxDelta) {
  8091. result = target;
  8092. }
  8093. else {
  8094. target = current + num;
  8095. result = Scalar.MoveTowards(current, target, maxDelta);
  8096. }
  8097. return result;
  8098. };
  8099. /**
  8100. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8101. */
  8102. Scalar.Lerp = function (start, end, amount) {
  8103. return start + ((end - start) * amount);
  8104. };
  8105. /**
  8106. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8107. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8108. */
  8109. Scalar.LerpAngle = function (start, end, amount) {
  8110. var num = Scalar.Repeat(end - start, 360.0);
  8111. if (num > 180.0) {
  8112. num -= 360.0;
  8113. }
  8114. return start + num * Scalar.Clamp(amount);
  8115. };
  8116. /**
  8117. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8118. */
  8119. Scalar.InverseLerp = function (a, b, value) {
  8120. var result = 0;
  8121. if (a != b) {
  8122. result = Scalar.Clamp((value - a) / (b - a));
  8123. }
  8124. else {
  8125. result = 0.0;
  8126. }
  8127. return result;
  8128. };
  8129. /**
  8130. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8131. */
  8132. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8133. var squared = amount * amount;
  8134. var cubed = amount * squared;
  8135. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8136. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8137. var part3 = (cubed - (2.0 * squared)) + amount;
  8138. var part4 = cubed - squared;
  8139. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8140. };
  8141. /**
  8142. * Returns a random float number between and min and max values
  8143. */
  8144. Scalar.RandomRange = function (min, max) {
  8145. if (min === max)
  8146. return min;
  8147. return ((Math.random() * (max - min)) + min);
  8148. };
  8149. /**
  8150. * This function returns percentage of a number in a given range.
  8151. *
  8152. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8153. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8154. */
  8155. Scalar.RangeToPercent = function (number, min, max) {
  8156. return ((number - min) / (max - min));
  8157. };
  8158. /**
  8159. * This function returns number that corresponds to the percentage in a given range.
  8160. *
  8161. * PercentToRange(0.34,0,100) will return 34.
  8162. */
  8163. Scalar.PercentToRange = function (percent, min, max) {
  8164. return ((max - min) * percent + min);
  8165. };
  8166. /**
  8167. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8168. * @param angle The angle to normalize in radian.
  8169. * @return The converted angle.
  8170. */
  8171. Scalar.NormalizeRadians = function (angle) {
  8172. // More precise but slower version kept for reference.
  8173. // angle = angle % Tools.TwoPi;
  8174. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8175. //if (angle > Math.PI) {
  8176. // angle -= Tools.TwoPi;
  8177. //}
  8178. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8179. return angle;
  8180. };
  8181. /**
  8182. * Two pi constants convenient for computation.
  8183. */
  8184. Scalar.TwoPi = Math.PI * 2;
  8185. return Scalar;
  8186. }());
  8187. BABYLON.Scalar = Scalar;
  8188. })(BABYLON || (BABYLON = {}));
  8189. //# sourceMappingURL=babylon.math.scalar.js.map
  8190. //# sourceMappingURL=babylon.mixins.js.map
  8191. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8192. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8193. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8194. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8195. //# sourceMappingURL=babylon.webgl2.js.map
  8196. var BABYLON;
  8197. (function (BABYLON) {
  8198. var __decoratorInitialStore = {};
  8199. var __mergedStore = {};
  8200. var _copySource = function (creationFunction, source, instanciate) {
  8201. var destination = creationFunction();
  8202. // Tags
  8203. if (BABYLON.Tags) {
  8204. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8205. }
  8206. var classStore = getMergedStore(destination);
  8207. // Properties
  8208. for (var property in classStore) {
  8209. var propertyDescriptor = classStore[property];
  8210. var sourceProperty = source[property];
  8211. var propertyType = propertyDescriptor.type;
  8212. if (sourceProperty !== undefined && sourceProperty !== null) {
  8213. switch (propertyType) {
  8214. case 0: // Value
  8215. case 6: // Mesh reference
  8216. case 11: // Camera reference
  8217. destination[property] = sourceProperty;
  8218. break;
  8219. case 1: // Texture
  8220. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8221. break;
  8222. case 2: // Color3
  8223. case 3: // FresnelParameters
  8224. case 4: // Vector2
  8225. case 5: // Vector3
  8226. case 7: // Color Curves
  8227. case 10: // Quaternion
  8228. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8229. break;
  8230. }
  8231. }
  8232. }
  8233. return destination;
  8234. };
  8235. function getDirectStore(target) {
  8236. var classKey = target.getClassName();
  8237. if (!__decoratorInitialStore[classKey]) {
  8238. __decoratorInitialStore[classKey] = {};
  8239. }
  8240. return __decoratorInitialStore[classKey];
  8241. }
  8242. /**
  8243. * Return the list of properties flagged as serializable
  8244. * @param target: host object
  8245. */
  8246. function getMergedStore(target) {
  8247. var classKey = target.getClassName();
  8248. if (__mergedStore[classKey]) {
  8249. return __mergedStore[classKey];
  8250. }
  8251. __mergedStore[classKey] = {};
  8252. var store = __mergedStore[classKey];
  8253. var currentTarget = target;
  8254. var currentKey = classKey;
  8255. while (currentKey) {
  8256. var initialStore = __decoratorInitialStore[currentKey];
  8257. for (var property in initialStore) {
  8258. store[property] = initialStore[property];
  8259. }
  8260. var parent_1 = void 0;
  8261. var done = false;
  8262. do {
  8263. parent_1 = Object.getPrototypeOf(currentTarget);
  8264. if (!parent_1.getClassName) {
  8265. done = true;
  8266. break;
  8267. }
  8268. if (parent_1.getClassName() !== currentKey) {
  8269. break;
  8270. }
  8271. currentTarget = parent_1;
  8272. } while (parent_1);
  8273. if (done) {
  8274. break;
  8275. }
  8276. currentKey = parent_1.getClassName();
  8277. currentTarget = parent_1;
  8278. }
  8279. return store;
  8280. }
  8281. function generateSerializableMember(type, sourceName) {
  8282. return function (target, propertyKey) {
  8283. var classStore = getDirectStore(target);
  8284. if (!classStore[propertyKey]) {
  8285. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8286. }
  8287. };
  8288. }
  8289. function generateExpandMember(setCallback, targetKey) {
  8290. if (targetKey === void 0) { targetKey = null; }
  8291. return function (target, propertyKey) {
  8292. var key = targetKey || ("_" + propertyKey);
  8293. Object.defineProperty(target, propertyKey, {
  8294. get: function () {
  8295. return this[key];
  8296. },
  8297. set: function (value) {
  8298. if (this[key] === value) {
  8299. return;
  8300. }
  8301. this[key] = value;
  8302. target[setCallback].apply(this);
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. };
  8308. }
  8309. function expandToProperty(callback, targetKey) {
  8310. if (targetKey === void 0) { targetKey = null; }
  8311. return generateExpandMember(callback, targetKey);
  8312. }
  8313. BABYLON.expandToProperty = expandToProperty;
  8314. function serialize(sourceName) {
  8315. return generateSerializableMember(0, sourceName); // value member
  8316. }
  8317. BABYLON.serialize = serialize;
  8318. function serializeAsTexture(sourceName) {
  8319. return generateSerializableMember(1, sourceName); // texture member
  8320. }
  8321. BABYLON.serializeAsTexture = serializeAsTexture;
  8322. function serializeAsColor3(sourceName) {
  8323. return generateSerializableMember(2, sourceName); // color3 member
  8324. }
  8325. BABYLON.serializeAsColor3 = serializeAsColor3;
  8326. function serializeAsFresnelParameters(sourceName) {
  8327. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8328. }
  8329. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8330. function serializeAsVector2(sourceName) {
  8331. return generateSerializableMember(4, sourceName); // vector2 member
  8332. }
  8333. BABYLON.serializeAsVector2 = serializeAsVector2;
  8334. function serializeAsVector3(sourceName) {
  8335. return generateSerializableMember(5, sourceName); // vector3 member
  8336. }
  8337. BABYLON.serializeAsVector3 = serializeAsVector3;
  8338. function serializeAsMeshReference(sourceName) {
  8339. return generateSerializableMember(6, sourceName); // mesh reference member
  8340. }
  8341. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8342. function serializeAsColorCurves(sourceName) {
  8343. return generateSerializableMember(7, sourceName); // color curves
  8344. }
  8345. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8346. function serializeAsColor4(sourceName) {
  8347. return generateSerializableMember(8, sourceName); // color 4
  8348. }
  8349. BABYLON.serializeAsColor4 = serializeAsColor4;
  8350. function serializeAsImageProcessingConfiguration(sourceName) {
  8351. return generateSerializableMember(9, sourceName); // image processing
  8352. }
  8353. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8354. function serializeAsQuaternion(sourceName) {
  8355. return generateSerializableMember(10, sourceName); // quaternion member
  8356. }
  8357. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8358. /**
  8359. * Decorator used to define property that can be serialized as reference to a camera
  8360. * @param sourceName defines the name of the property to decorate
  8361. */
  8362. function serializeAsCameraReference(sourceName) {
  8363. return generateSerializableMember(11, sourceName); // camera reference member
  8364. }
  8365. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8366. var SerializationHelper = /** @class */ (function () {
  8367. function SerializationHelper() {
  8368. }
  8369. SerializationHelper.Serialize = function (entity, serializationObject) {
  8370. if (!serializationObject) {
  8371. serializationObject = {};
  8372. }
  8373. // Tags
  8374. if (BABYLON.Tags) {
  8375. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8376. }
  8377. var serializedProperties = getMergedStore(entity);
  8378. // Properties
  8379. for (var property in serializedProperties) {
  8380. var propertyDescriptor = serializedProperties[property];
  8381. var targetPropertyName = propertyDescriptor.sourceName || property;
  8382. var propertyType = propertyDescriptor.type;
  8383. var sourceProperty = entity[property];
  8384. if (sourceProperty !== undefined && sourceProperty !== null) {
  8385. switch (propertyType) {
  8386. case 0: // Value
  8387. serializationObject[targetPropertyName] = sourceProperty;
  8388. break;
  8389. case 1: // Texture
  8390. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8391. break;
  8392. case 2: // Color3
  8393. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8394. break;
  8395. case 3: // FresnelParameters
  8396. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8397. break;
  8398. case 4: // Vector2
  8399. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8400. break;
  8401. case 5: // Vector3
  8402. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8403. break;
  8404. case 6: // Mesh reference
  8405. serializationObject[targetPropertyName] = sourceProperty.id;
  8406. break;
  8407. case 7: // Color Curves
  8408. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8409. break;
  8410. case 8: // Color 4
  8411. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8412. break;
  8413. case 9: // Image Processing
  8414. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8415. break;
  8416. case 10: // Quaternion
  8417. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8418. break;
  8419. case 11: // Camera reference
  8420. serializationObject[targetPropertyName] = sourceProperty.id;
  8421. break;
  8422. }
  8423. }
  8424. }
  8425. return serializationObject;
  8426. };
  8427. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8428. if (rootUrl === void 0) { rootUrl = null; }
  8429. var destination = creationFunction();
  8430. if (!rootUrl) {
  8431. rootUrl = "";
  8432. }
  8433. // Tags
  8434. if (BABYLON.Tags) {
  8435. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8436. }
  8437. var classStore = getMergedStore(destination);
  8438. // Properties
  8439. for (var property in classStore) {
  8440. var propertyDescriptor = classStore[property];
  8441. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8442. var propertyType = propertyDescriptor.type;
  8443. if (sourceProperty !== undefined && sourceProperty !== null) {
  8444. var dest = destination;
  8445. switch (propertyType) {
  8446. case 0: // Value
  8447. dest[property] = sourceProperty;
  8448. break;
  8449. case 1: // Texture
  8450. if (scene) {
  8451. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8452. }
  8453. break;
  8454. case 2: // Color3
  8455. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8456. break;
  8457. case 3: // FresnelParameters
  8458. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8459. break;
  8460. case 4: // Vector2
  8461. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8462. break;
  8463. case 5: // Vector3
  8464. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8465. break;
  8466. case 6: // Mesh reference
  8467. if (scene) {
  8468. dest[property] = scene.getLastMeshByID(sourceProperty);
  8469. }
  8470. break;
  8471. case 7: // Color Curves
  8472. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8473. break;
  8474. case 8: // Color 4
  8475. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8476. break;
  8477. case 9: // Image Processing
  8478. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8479. break;
  8480. case 10: // Quaternion
  8481. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8482. break;
  8483. case 11: // Camera reference
  8484. if (scene) {
  8485. dest[property] = scene.getCameraByID(sourceProperty);
  8486. }
  8487. break;
  8488. }
  8489. }
  8490. }
  8491. return destination;
  8492. };
  8493. SerializationHelper.Clone = function (creationFunction, source) {
  8494. return _copySource(creationFunction, source, false);
  8495. };
  8496. SerializationHelper.Instanciate = function (creationFunction, source) {
  8497. return _copySource(creationFunction, source, true);
  8498. };
  8499. return SerializationHelper;
  8500. }());
  8501. BABYLON.SerializationHelper = SerializationHelper;
  8502. })(BABYLON || (BABYLON = {}));
  8503. //# sourceMappingURL=babylon.decorators.js.map
  8504. var BABYLON;
  8505. (function (BABYLON) {
  8506. /**
  8507. * Wrapper class for promise with external resolve and reject.
  8508. */
  8509. var Deferred = /** @class */ (function () {
  8510. /**
  8511. * Constructor for this deferred object.
  8512. */
  8513. function Deferred() {
  8514. var _this = this;
  8515. this.promise = new Promise(function (resolve, reject) {
  8516. _this._resolve = resolve;
  8517. _this._reject = reject;
  8518. });
  8519. }
  8520. Object.defineProperty(Deferred.prototype, "resolve", {
  8521. /**
  8522. * The resolve method of the promise associated with this deferred object.
  8523. */
  8524. get: function () {
  8525. return this._resolve;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(Deferred.prototype, "reject", {
  8531. /**
  8532. * The reject method of the promise associated with this deferred object.
  8533. */
  8534. get: function () {
  8535. return this._reject;
  8536. },
  8537. enumerable: true,
  8538. configurable: true
  8539. });
  8540. return Deferred;
  8541. }());
  8542. BABYLON.Deferred = Deferred;
  8543. })(BABYLON || (BABYLON = {}));
  8544. //# sourceMappingURL=babylon.deferred.js.map
  8545. var BABYLON;
  8546. (function (BABYLON) {
  8547. /**
  8548. * A class serves as a medium between the observable and its observers
  8549. */
  8550. var EventState = /** @class */ (function () {
  8551. /**
  8552. * Create a new EventState
  8553. * @param mask defines the mask associated with this state
  8554. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8555. * @param target defines the original target of the state
  8556. * @param currentTarget defines the current target of the state
  8557. */
  8558. function EventState(mask, skipNextObservers, target, currentTarget) {
  8559. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8560. this.initalize(mask, skipNextObservers, target, currentTarget);
  8561. }
  8562. /**
  8563. * Initialize the current event state
  8564. * @param mask defines the mask associated with this state
  8565. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8566. * @param target defines the original target of the state
  8567. * @param currentTarget defines the current target of the state
  8568. * @returns the current event state
  8569. */
  8570. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8571. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8572. this.mask = mask;
  8573. this.skipNextObservers = skipNextObservers;
  8574. this.target = target;
  8575. this.currentTarget = currentTarget;
  8576. return this;
  8577. };
  8578. return EventState;
  8579. }());
  8580. BABYLON.EventState = EventState;
  8581. /**
  8582. * Represent an Observer registered to a given Observable object.
  8583. */
  8584. var Observer = /** @class */ (function () {
  8585. /**
  8586. * Creates a new observer
  8587. * @param callback defines the callback to call when the observer is notified
  8588. * @param mask defines the mask of the observer (used to filter notifications)
  8589. * @param scope defines the current scope used to restore the JS context
  8590. */
  8591. function Observer(
  8592. /**
  8593. * Defines the callback to call when the observer is notified
  8594. */
  8595. callback,
  8596. /**
  8597. * Defines the mask of the observer (used to filter notifications)
  8598. */
  8599. mask,
  8600. /**
  8601. * Defines the current scope used to restore the JS context
  8602. */
  8603. scope) {
  8604. if (scope === void 0) { scope = null; }
  8605. this.callback = callback;
  8606. this.mask = mask;
  8607. this.scope = scope;
  8608. /** @hidden */
  8609. this._willBeUnregistered = false;
  8610. /**
  8611. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8612. */
  8613. this.unregisterOnNextCall = false;
  8614. }
  8615. return Observer;
  8616. }());
  8617. BABYLON.Observer = Observer;
  8618. /**
  8619. * Represent a list of observers registered to multiple Observables object.
  8620. */
  8621. var MultiObserver = /** @class */ (function () {
  8622. function MultiObserver() {
  8623. }
  8624. /**
  8625. * Release associated resources
  8626. */
  8627. MultiObserver.prototype.dispose = function () {
  8628. if (this._observers && this._observables) {
  8629. for (var index = 0; index < this._observers.length; index++) {
  8630. this._observables[index].remove(this._observers[index]);
  8631. }
  8632. }
  8633. this._observers = null;
  8634. this._observables = null;
  8635. };
  8636. /**
  8637. * Raise a callback when one of the observable will notify
  8638. * @param observables defines a list of observables to watch
  8639. * @param callback defines the callback to call on notification
  8640. * @param mask defines the mask used to filter notifications
  8641. * @param scope defines the current scope used to restore the JS context
  8642. * @returns the new MultiObserver
  8643. */
  8644. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8645. if (mask === void 0) { mask = -1; }
  8646. if (scope === void 0) { scope = null; }
  8647. var result = new MultiObserver();
  8648. result._observers = new Array();
  8649. result._observables = observables;
  8650. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8651. var observable = observables_1[_i];
  8652. var observer = observable.add(callback, mask, false, scope);
  8653. if (observer) {
  8654. result._observers.push(observer);
  8655. }
  8656. }
  8657. return result;
  8658. };
  8659. return MultiObserver;
  8660. }());
  8661. BABYLON.MultiObserver = MultiObserver;
  8662. /**
  8663. * The Observable class is a simple implementation of the Observable pattern.
  8664. *
  8665. * 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.
  8666. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8667. * 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).
  8668. * 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.
  8669. */
  8670. var Observable = /** @class */ (function () {
  8671. /**
  8672. * Creates a new observable
  8673. * @param onObserverAdded defines a callback to call when a new observer is added
  8674. */
  8675. function Observable(onObserverAdded) {
  8676. this._observers = new Array();
  8677. this._eventState = new EventState(0);
  8678. if (onObserverAdded) {
  8679. this._onObserverAdded = onObserverAdded;
  8680. }
  8681. }
  8682. /**
  8683. * Create a new Observer with the specified callback
  8684. * @param callback the callback that will be executed for that Observer
  8685. * @param mask the mask used to filter observers
  8686. * @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.
  8687. * @param scope optional scope for the callback to be called from
  8688. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8689. * @returns the new observer created for the callback
  8690. */
  8691. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8692. if (mask === void 0) { mask = -1; }
  8693. if (insertFirst === void 0) { insertFirst = false; }
  8694. if (scope === void 0) { scope = null; }
  8695. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8696. if (!callback) {
  8697. return null;
  8698. }
  8699. var observer = new Observer(callback, mask, scope);
  8700. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8701. if (insertFirst) {
  8702. this._observers.unshift(observer);
  8703. }
  8704. else {
  8705. this._observers.push(observer);
  8706. }
  8707. if (this._onObserverAdded) {
  8708. this._onObserverAdded(observer);
  8709. }
  8710. return observer;
  8711. };
  8712. /**
  8713. * Create a new Observer with the specified callback and unregisters after the next notification
  8714. * @param callback the callback that will be executed for that Observer
  8715. * @returns the new observer created for the callback
  8716. */
  8717. Observable.prototype.addOnce = function (callback) {
  8718. return this.add(callback, undefined, undefined, undefined, true);
  8719. };
  8720. /**
  8721. * Remove an Observer from the Observable object
  8722. * @param observer the instance of the Observer to remove
  8723. * @returns false if it doesn't belong to this Observable
  8724. */
  8725. Observable.prototype.remove = function (observer) {
  8726. if (!observer) {
  8727. return false;
  8728. }
  8729. var index = this._observers.indexOf(observer);
  8730. if (index !== -1) {
  8731. this._deferUnregister(observer);
  8732. return true;
  8733. }
  8734. return false;
  8735. };
  8736. /**
  8737. * Remove a callback from the Observable object
  8738. * @param callback the callback to remove
  8739. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8740. * @returns false if it doesn't belong to this Observable
  8741. */
  8742. Observable.prototype.removeCallback = function (callback, scope) {
  8743. for (var index = 0; index < this._observers.length; index++) {
  8744. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8745. this._deferUnregister(this._observers[index]);
  8746. return true;
  8747. }
  8748. }
  8749. return false;
  8750. };
  8751. Observable.prototype._deferUnregister = function (observer) {
  8752. var _this = this;
  8753. observer.unregisterOnNextCall = false;
  8754. observer._willBeUnregistered = true;
  8755. BABYLON.Tools.SetImmediate(function () {
  8756. _this._remove(observer);
  8757. });
  8758. };
  8759. // This should only be called when not iterating over _observers to avoid callback skipping.
  8760. // Removes an observer from the _observer Array.
  8761. Observable.prototype._remove = function (observer) {
  8762. if (!observer) {
  8763. return false;
  8764. }
  8765. var index = this._observers.indexOf(observer);
  8766. if (index !== -1) {
  8767. this._observers.splice(index, 1);
  8768. return true;
  8769. }
  8770. return false;
  8771. };
  8772. /**
  8773. * Notify all Observers by calling their respective callback with the given data
  8774. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8775. * @param eventData defines the data to send to all observers
  8776. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8777. * @param target defines the original target of the state
  8778. * @param currentTarget defines the current target of the state
  8779. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8780. */
  8781. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8782. if (mask === void 0) { mask = -1; }
  8783. if (!this._observers.length) {
  8784. return true;
  8785. }
  8786. var state = this._eventState;
  8787. state.mask = mask;
  8788. state.target = target;
  8789. state.currentTarget = currentTarget;
  8790. state.skipNextObservers = false;
  8791. state.lastReturnValue = eventData;
  8792. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8793. var obs = _a[_i];
  8794. if (obs._willBeUnregistered) {
  8795. continue;
  8796. }
  8797. if (obs.mask & mask) {
  8798. if (obs.scope) {
  8799. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8800. }
  8801. else {
  8802. state.lastReturnValue = obs.callback(eventData, state);
  8803. }
  8804. if (obs.unregisterOnNextCall) {
  8805. this._deferUnregister(obs);
  8806. }
  8807. }
  8808. if (state.skipNextObservers) {
  8809. return false;
  8810. }
  8811. }
  8812. return true;
  8813. };
  8814. /**
  8815. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8816. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8817. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8818. * and it is crucial that all callbacks will be executed.
  8819. * The order of the callbacks is kept, callbacks are not executed parallel.
  8820. *
  8821. * @param eventData The data to be sent to each callback
  8822. * @param mask is used to filter observers defaults to -1
  8823. * @param target defines the callback target (see EventState)
  8824. * @param currentTarget defines he current object in the bubbling phase
  8825. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8826. */
  8827. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8828. var _this = this;
  8829. if (mask === void 0) { mask = -1; }
  8830. // create an empty promise
  8831. var p = Promise.resolve(eventData);
  8832. // no observers? return this promise.
  8833. if (!this._observers.length) {
  8834. return p;
  8835. }
  8836. var state = this._eventState;
  8837. state.mask = mask;
  8838. state.target = target;
  8839. state.currentTarget = currentTarget;
  8840. state.skipNextObservers = false;
  8841. // execute one callback after another (not using Promise.all, the order is important)
  8842. this._observers.forEach(function (obs) {
  8843. if (state.skipNextObservers) {
  8844. return;
  8845. }
  8846. if (obs._willBeUnregistered) {
  8847. return;
  8848. }
  8849. if (obs.mask & mask) {
  8850. if (obs.scope) {
  8851. p = p.then(function (lastReturnedValue) {
  8852. state.lastReturnValue = lastReturnedValue;
  8853. return obs.callback.apply(obs.scope, [eventData, state]);
  8854. });
  8855. }
  8856. else {
  8857. p = p.then(function (lastReturnedValue) {
  8858. state.lastReturnValue = lastReturnedValue;
  8859. return obs.callback(eventData, state);
  8860. });
  8861. }
  8862. if (obs.unregisterOnNextCall) {
  8863. _this._deferUnregister(obs);
  8864. }
  8865. }
  8866. });
  8867. // return the eventData
  8868. return p.then(function () { return eventData; });
  8869. };
  8870. /**
  8871. * Notify a specific observer
  8872. * @param observer defines the observer to notify
  8873. * @param eventData defines the data to be sent to each callback
  8874. * @param mask is used to filter observers defaults to -1
  8875. */
  8876. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8877. if (mask === void 0) { mask = -1; }
  8878. var state = this._eventState;
  8879. state.mask = mask;
  8880. state.skipNextObservers = false;
  8881. observer.callback(eventData, state);
  8882. };
  8883. /**
  8884. * Gets a boolean indicating if the observable has at least one observer
  8885. * @returns true is the Observable has at least one Observer registered
  8886. */
  8887. Observable.prototype.hasObservers = function () {
  8888. return this._observers.length > 0;
  8889. };
  8890. /**
  8891. * Clear the list of observers
  8892. */
  8893. Observable.prototype.clear = function () {
  8894. this._observers = new Array();
  8895. this._onObserverAdded = null;
  8896. };
  8897. /**
  8898. * Clone the current observable
  8899. * @returns a new observable
  8900. */
  8901. Observable.prototype.clone = function () {
  8902. var result = new Observable();
  8903. result._observers = this._observers.slice(0);
  8904. return result;
  8905. };
  8906. /**
  8907. * Does this observable handles observer registered with a given mask
  8908. * @param mask defines the mask to be tested
  8909. * @return whether or not one observer registered with the given mask is handeled
  8910. **/
  8911. Observable.prototype.hasSpecificMask = function (mask) {
  8912. if (mask === void 0) { mask = -1; }
  8913. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8914. var obs = _a[_i];
  8915. if (obs.mask & mask || obs.mask === mask) {
  8916. return true;
  8917. }
  8918. }
  8919. return false;
  8920. };
  8921. return Observable;
  8922. }());
  8923. BABYLON.Observable = Observable;
  8924. })(BABYLON || (BABYLON = {}));
  8925. //# sourceMappingURL=babylon.observable.js.map
  8926. var BABYLON;
  8927. (function (BABYLON) {
  8928. /**
  8929. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8930. */
  8931. var SmartArray = /** @class */ (function () {
  8932. /**
  8933. * Instantiates a Smart Array.
  8934. * @param capacity defines the default capacity of the array.
  8935. */
  8936. function SmartArray(capacity) {
  8937. /**
  8938. * The active length of the array.
  8939. */
  8940. this.length = 0;
  8941. this.data = new Array(capacity);
  8942. this._id = SmartArray._GlobalId++;
  8943. }
  8944. /**
  8945. * Pushes a value at the end of the active data.
  8946. * @param value defines the object to push in the array.
  8947. */
  8948. SmartArray.prototype.push = function (value) {
  8949. this.data[this.length++] = value;
  8950. if (this.length > this.data.length) {
  8951. this.data.length *= 2;
  8952. }
  8953. };
  8954. /**
  8955. * Iterates over the active data and apply the lambda to them.
  8956. * @param func defines the action to apply on each value.
  8957. */
  8958. SmartArray.prototype.forEach = function (func) {
  8959. for (var index = 0; index < this.length; index++) {
  8960. func(this.data[index]);
  8961. }
  8962. };
  8963. /**
  8964. * Sorts the full sets of data.
  8965. * @param compareFn defines the comparison function to apply.
  8966. */
  8967. SmartArray.prototype.sort = function (compareFn) {
  8968. this.data.sort(compareFn);
  8969. };
  8970. /**
  8971. * Resets the active data to an empty array.
  8972. */
  8973. SmartArray.prototype.reset = function () {
  8974. this.length = 0;
  8975. };
  8976. /**
  8977. * Releases all the data from the array as well as the array.
  8978. */
  8979. SmartArray.prototype.dispose = function () {
  8980. this.reset();
  8981. if (this.data) {
  8982. this.data.length = 0;
  8983. this.data = [];
  8984. }
  8985. };
  8986. /**
  8987. * Concats the active data with a given array.
  8988. * @param array defines the data to concatenate with.
  8989. */
  8990. SmartArray.prototype.concat = function (array) {
  8991. if (array.length === 0) {
  8992. return;
  8993. }
  8994. if (this.length + array.length > this.data.length) {
  8995. this.data.length = (this.length + array.length) * 2;
  8996. }
  8997. for (var index = 0; index < array.length; index++) {
  8998. this.data[this.length++] = (array.data || array)[index];
  8999. }
  9000. };
  9001. /**
  9002. * Returns the position of a value in the active data.
  9003. * @param value defines the value to find the index for
  9004. * @returns the index if found in the active data otherwise -1
  9005. */
  9006. SmartArray.prototype.indexOf = function (value) {
  9007. var position = this.data.indexOf(value);
  9008. if (position >= this.length) {
  9009. return -1;
  9010. }
  9011. return position;
  9012. };
  9013. /**
  9014. * Returns whether an element is part of the active data.
  9015. * @param value defines the value to look for
  9016. * @returns true if found in the active data otherwise false
  9017. */
  9018. SmartArray.prototype.contains = function (value) {
  9019. return this.indexOf(value) !== -1;
  9020. };
  9021. // Statics
  9022. SmartArray._GlobalId = 0;
  9023. return SmartArray;
  9024. }());
  9025. BABYLON.SmartArray = SmartArray;
  9026. /**
  9027. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9028. * The data in this array can only be present once
  9029. */
  9030. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9031. __extends(SmartArrayNoDuplicate, _super);
  9032. function SmartArrayNoDuplicate() {
  9033. var _this = _super !== null && _super.apply(this, arguments) || this;
  9034. _this._duplicateId = 0;
  9035. return _this;
  9036. }
  9037. /**
  9038. * Pushes a value at the end of the active data.
  9039. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9040. * @param value defines the object to push in the array.
  9041. */
  9042. SmartArrayNoDuplicate.prototype.push = function (value) {
  9043. _super.prototype.push.call(this, value);
  9044. if (!value.__smartArrayFlags) {
  9045. value.__smartArrayFlags = {};
  9046. }
  9047. value.__smartArrayFlags[this._id] = this._duplicateId;
  9048. };
  9049. /**
  9050. * Pushes a value at the end of the active data.
  9051. * If the data is already present, it won t be added again
  9052. * @param value defines the object to push in the array.
  9053. * @returns true if added false if it was already present
  9054. */
  9055. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9056. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9057. return false;
  9058. }
  9059. this.push(value);
  9060. return true;
  9061. };
  9062. /**
  9063. * Resets the active data to an empty array.
  9064. */
  9065. SmartArrayNoDuplicate.prototype.reset = function () {
  9066. _super.prototype.reset.call(this);
  9067. this._duplicateId++;
  9068. };
  9069. /**
  9070. * Concats the active data with a given array.
  9071. * This ensures no dupplicate will be present in the result.
  9072. * @param array defines the data to concatenate with.
  9073. */
  9074. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9075. if (array.length === 0) {
  9076. return;
  9077. }
  9078. if (this.length + array.length > this.data.length) {
  9079. this.data.length = (this.length + array.length) * 2;
  9080. }
  9081. for (var index = 0; index < array.length; index++) {
  9082. var item = (array.data || array)[index];
  9083. this.pushNoDuplicate(item);
  9084. }
  9085. };
  9086. return SmartArrayNoDuplicate;
  9087. }(SmartArray));
  9088. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9089. })(BABYLON || (BABYLON = {}));
  9090. //# sourceMappingURL=babylon.smartArray.js.map
  9091. var BABYLON;
  9092. (function (BABYLON) {
  9093. /** Class used to store color4 gradient */
  9094. var ColorGradient = /** @class */ (function () {
  9095. function ColorGradient() {
  9096. }
  9097. /**
  9098. * Will get a color picked randomly between color1 and color2.
  9099. * If color2 is undefined then color1 will be used
  9100. * @param result defines the target Color4 to store the result in
  9101. */
  9102. ColorGradient.prototype.getColorToRef = function (result) {
  9103. if (!this.color2) {
  9104. result.copyFrom(this.color1);
  9105. return;
  9106. }
  9107. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9108. };
  9109. return ColorGradient;
  9110. }());
  9111. BABYLON.ColorGradient = ColorGradient;
  9112. /** Class used to store color 3 gradient */
  9113. var Color3Gradient = /** @class */ (function () {
  9114. function Color3Gradient() {
  9115. }
  9116. return Color3Gradient;
  9117. }());
  9118. BABYLON.Color3Gradient = Color3Gradient;
  9119. /** Class used to store factor gradient */
  9120. var FactorGradient = /** @class */ (function () {
  9121. function FactorGradient() {
  9122. }
  9123. /**
  9124. * Will get a number picked randomly between factor1 and factor2.
  9125. * If factor2 is undefined then factor1 will be used
  9126. * @returns the picked number
  9127. */
  9128. FactorGradient.prototype.getFactor = function () {
  9129. if (this.factor2 === undefined) {
  9130. return this.factor1;
  9131. }
  9132. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9133. };
  9134. return FactorGradient;
  9135. }());
  9136. BABYLON.FactorGradient = FactorGradient;
  9137. /**
  9138. * Application error to support additional information when loading a file
  9139. */
  9140. var LoadFileError = /** @class */ (function (_super) {
  9141. __extends(LoadFileError, _super);
  9142. /**
  9143. * Creates a new LoadFileError
  9144. * @param message defines the message of the error
  9145. * @param request defines the optional XHR request
  9146. */
  9147. function LoadFileError(message, request) {
  9148. var _this = _super.call(this, message) || this;
  9149. _this.request = request;
  9150. _this.name = "LoadFileError";
  9151. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9152. return _this;
  9153. }
  9154. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9155. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9156. // Polyfill for Object.setPrototypeOf if necessary.
  9157. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9158. return LoadFileError;
  9159. }(Error));
  9160. BABYLON.LoadFileError = LoadFileError;
  9161. /**
  9162. * Class used to define a retry strategy when error happens while loading assets
  9163. */
  9164. var RetryStrategy = /** @class */ (function () {
  9165. function RetryStrategy() {
  9166. }
  9167. /**
  9168. * Function used to defines an exponential back off strategy
  9169. * @param maxRetries defines the maximum number of retries (3 by default)
  9170. * @param baseInterval defines the interval between retries
  9171. * @returns the strategy function to use
  9172. */
  9173. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9174. if (maxRetries === void 0) { maxRetries = 3; }
  9175. if (baseInterval === void 0) { baseInterval = 500; }
  9176. return function (url, request, retryIndex) {
  9177. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9178. return -1;
  9179. }
  9180. return Math.pow(2, retryIndex) * baseInterval;
  9181. };
  9182. };
  9183. return RetryStrategy;
  9184. }());
  9185. BABYLON.RetryStrategy = RetryStrategy;
  9186. // Screenshots
  9187. var screenshotCanvas;
  9188. var cloneValue = function (source, destinationObject) {
  9189. if (!source)
  9190. return null;
  9191. if (source instanceof BABYLON.Mesh) {
  9192. return null;
  9193. }
  9194. if (source instanceof BABYLON.SubMesh) {
  9195. return source.clone(destinationObject);
  9196. }
  9197. else if (source.clone) {
  9198. return source.clone();
  9199. }
  9200. return null;
  9201. };
  9202. /**
  9203. * Class containing a set of static utilities functions
  9204. */
  9205. var Tools = /** @class */ (function () {
  9206. function Tools() {
  9207. }
  9208. /**
  9209. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9210. * @param u defines the coordinate on X axis
  9211. * @param v defines the coordinate on Y axis
  9212. * @param width defines the width of the source data
  9213. * @param height defines the height of the source data
  9214. * @param pixels defines the source byte array
  9215. * @param color defines the output color
  9216. */
  9217. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9218. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9219. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9220. var position = (wrappedU + wrappedV * width) * 4;
  9221. color.r = pixels[position] / 255;
  9222. color.g = pixels[position + 1] / 255;
  9223. color.b = pixels[position + 2] / 255;
  9224. color.a = pixels[position + 3] / 255;
  9225. };
  9226. /**
  9227. * Interpolates between a and b via alpha
  9228. * @param a The lower value (returned when alpha = 0)
  9229. * @param b The upper value (returned when alpha = 1)
  9230. * @param alpha The interpolation-factor
  9231. * @return The mixed value
  9232. */
  9233. Tools.Mix = function (a, b, alpha) {
  9234. return a * (1 - alpha) + b * alpha;
  9235. };
  9236. /**
  9237. * Tries to instantiate a new object from a given class name
  9238. * @param className defines the class name to instantiate
  9239. * @returns the new object or null if the system was not able to do the instantiation
  9240. */
  9241. Tools.Instantiate = function (className) {
  9242. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9243. return Tools.RegisteredExternalClasses[className];
  9244. }
  9245. var arr = className.split(".");
  9246. var fn = (window || this);
  9247. for (var i = 0, len = arr.length; i < len; i++) {
  9248. fn = fn[arr[i]];
  9249. }
  9250. if (typeof fn !== "function") {
  9251. return null;
  9252. }
  9253. return fn;
  9254. };
  9255. /**
  9256. * Provides a slice function that will work even on IE
  9257. * @param data defines the array to slice
  9258. * @param start defines the start of the data (optional)
  9259. * @param end defines the end of the data (optional)
  9260. * @returns the new sliced array
  9261. */
  9262. Tools.Slice = function (data, start, end) {
  9263. if (data.slice) {
  9264. return data.slice(start, end);
  9265. }
  9266. return Array.prototype.slice.call(data, start, end);
  9267. };
  9268. /**
  9269. * Polyfill for setImmediate
  9270. * @param action defines the action to execute after the current execution block
  9271. */
  9272. Tools.SetImmediate = function (action) {
  9273. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9274. window.setImmediate(action);
  9275. }
  9276. else {
  9277. setTimeout(action, 1);
  9278. }
  9279. };
  9280. /**
  9281. * Function indicating if a number is an exponent of 2
  9282. * @param value defines the value to test
  9283. * @returns true if the value is an exponent of 2
  9284. */
  9285. Tools.IsExponentOfTwo = function (value) {
  9286. var count = 1;
  9287. do {
  9288. count *= 2;
  9289. } while (count < value);
  9290. return count === value;
  9291. };
  9292. /**
  9293. * Returns the nearest 32-bit single precision float representation of a Number
  9294. * @param value A Number. If the parameter is of a different type, it will get converted
  9295. * to a number or to NaN if it cannot be converted
  9296. * @returns number
  9297. */
  9298. Tools.FloatRound = function (value) {
  9299. if (Math.fround) {
  9300. return Math.fround(value);
  9301. }
  9302. return (Tools._tmpFloatArray[0] = value);
  9303. };
  9304. /**
  9305. * Find the next highest power of two.
  9306. * @param x Number to start search from.
  9307. * @return Next highest power of two.
  9308. */
  9309. Tools.CeilingPOT = function (x) {
  9310. x--;
  9311. x |= x >> 1;
  9312. x |= x >> 2;
  9313. x |= x >> 4;
  9314. x |= x >> 8;
  9315. x |= x >> 16;
  9316. x++;
  9317. return x;
  9318. };
  9319. /**
  9320. * Find the next lowest power of two.
  9321. * @param x Number to start search from.
  9322. * @return Next lowest power of two.
  9323. */
  9324. Tools.FloorPOT = function (x) {
  9325. x = x | (x >> 1);
  9326. x = x | (x >> 2);
  9327. x = x | (x >> 4);
  9328. x = x | (x >> 8);
  9329. x = x | (x >> 16);
  9330. return x - (x >> 1);
  9331. };
  9332. /**
  9333. * Find the nearest power of two.
  9334. * @param x Number to start search from.
  9335. * @return Next nearest power of two.
  9336. */
  9337. Tools.NearestPOT = function (x) {
  9338. var c = Tools.CeilingPOT(x);
  9339. var f = Tools.FloorPOT(x);
  9340. return (c - x) > (x - f) ? f : c;
  9341. };
  9342. /**
  9343. * Get the closest exponent of two
  9344. * @param value defines the value to approximate
  9345. * @param max defines the maximum value to return
  9346. * @param mode defines how to define the closest value
  9347. * @returns closest exponent of two of the given value
  9348. */
  9349. Tools.GetExponentOfTwo = function (value, max, mode) {
  9350. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9351. var pot;
  9352. switch (mode) {
  9353. case BABYLON.Engine.SCALEMODE_FLOOR:
  9354. pot = Tools.FloorPOT(value);
  9355. break;
  9356. case BABYLON.Engine.SCALEMODE_NEAREST:
  9357. pot = Tools.NearestPOT(value);
  9358. break;
  9359. case BABYLON.Engine.SCALEMODE_CEILING:
  9360. default:
  9361. pot = Tools.CeilingPOT(value);
  9362. break;
  9363. }
  9364. return Math.min(pot, max);
  9365. };
  9366. /**
  9367. * Extracts the filename from a path
  9368. * @param path defines the path to use
  9369. * @returns the filename
  9370. */
  9371. Tools.GetFilename = function (path) {
  9372. var index = path.lastIndexOf("/");
  9373. if (index < 0)
  9374. return path;
  9375. return path.substring(index + 1);
  9376. };
  9377. /**
  9378. * Extracts the "folder" part of a path (everything before the filename).
  9379. * @param uri The URI to extract the info from
  9380. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9381. * @returns The "folder" part of the path
  9382. */
  9383. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9384. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9385. var index = uri.lastIndexOf("/");
  9386. if (index < 0) {
  9387. if (returnUnchangedIfNoSlash) {
  9388. return uri;
  9389. }
  9390. return "";
  9391. }
  9392. return uri.substring(0, index + 1);
  9393. };
  9394. /**
  9395. * Extracts text content from a DOM element hierarchy
  9396. * @param element defines the root element
  9397. * @returns a string
  9398. */
  9399. Tools.GetDOMTextContent = function (element) {
  9400. var result = "";
  9401. var child = element.firstChild;
  9402. while (child) {
  9403. if (child.nodeType === 3) {
  9404. result += child.textContent;
  9405. }
  9406. child = child.nextSibling;
  9407. }
  9408. return result;
  9409. };
  9410. /**
  9411. * Convert an angle in radians to degrees
  9412. * @param angle defines the angle to convert
  9413. * @returns the angle in degrees
  9414. */
  9415. Tools.ToDegrees = function (angle) {
  9416. return angle * 180 / Math.PI;
  9417. };
  9418. /**
  9419. * Convert an angle in degrees to radians
  9420. * @param angle defines the angle to convert
  9421. * @returns the angle in radians
  9422. */
  9423. Tools.ToRadians = function (angle) {
  9424. return angle * Math.PI / 180;
  9425. };
  9426. /**
  9427. * Encode a buffer to a base64 string
  9428. * @param buffer defines the buffer to encode
  9429. * @returns the encoded string
  9430. */
  9431. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9432. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9433. var output = "";
  9434. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9435. var i = 0;
  9436. var bytes = new Uint8Array(buffer);
  9437. while (i < bytes.length) {
  9438. chr1 = bytes[i++];
  9439. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9440. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9441. enc1 = chr1 >> 2;
  9442. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9443. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9444. enc4 = chr3 & 63;
  9445. if (isNaN(chr2)) {
  9446. enc3 = enc4 = 64;
  9447. }
  9448. else if (isNaN(chr3)) {
  9449. enc4 = 64;
  9450. }
  9451. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9452. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9453. }
  9454. return "data:image/png;base64," + output;
  9455. };
  9456. /**
  9457. * Extracts minimum and maximum values from a list of indexed positions
  9458. * @param positions defines the positions to use
  9459. * @param indices defines the indices to the positions
  9460. * @param indexStart defines the start index
  9461. * @param indexCount defines the end index
  9462. * @param bias defines bias value to add to the result
  9463. * @return minimum and maximum values
  9464. */
  9465. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9466. if (bias === void 0) { bias = null; }
  9467. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9468. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9469. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9470. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9471. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9472. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9473. }
  9474. if (bias) {
  9475. minimum.x -= minimum.x * bias.x + bias.y;
  9476. minimum.y -= minimum.y * bias.x + bias.y;
  9477. minimum.z -= minimum.z * bias.x + bias.y;
  9478. maximum.x += maximum.x * bias.x + bias.y;
  9479. maximum.y += maximum.y * bias.x + bias.y;
  9480. maximum.z += maximum.z * bias.x + bias.y;
  9481. }
  9482. return {
  9483. minimum: minimum,
  9484. maximum: maximum
  9485. };
  9486. };
  9487. /**
  9488. * Extracts minimum and maximum values from a list of positions
  9489. * @param positions defines the positions to use
  9490. * @param start defines the start index in the positions array
  9491. * @param count defines the number of positions to handle
  9492. * @param bias defines bias value to add to the result
  9493. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9494. * @return minimum and maximum values
  9495. */
  9496. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9497. if (bias === void 0) { bias = null; }
  9498. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9499. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9500. if (!stride) {
  9501. stride = 3;
  9502. }
  9503. for (var index = start; index < start + count; index++) {
  9504. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9505. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9506. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9507. }
  9508. if (bias) {
  9509. minimum.x -= minimum.x * bias.x + bias.y;
  9510. minimum.y -= minimum.y * bias.x + bias.y;
  9511. minimum.z -= minimum.z * bias.x + bias.y;
  9512. maximum.x += maximum.x * bias.x + bias.y;
  9513. maximum.y += maximum.y * bias.x + bias.y;
  9514. maximum.z += maximum.z * bias.x + bias.y;
  9515. }
  9516. return {
  9517. minimum: minimum,
  9518. maximum: maximum
  9519. };
  9520. };
  9521. /**
  9522. * Returns an array if obj is not an array
  9523. * @param obj defines the object to evaluate as an array
  9524. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9525. * @returns either obj directly if obj is an array or a new array containing obj
  9526. */
  9527. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9528. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9529. return null;
  9530. return Array.isArray(obj) ? obj : [obj];
  9531. };
  9532. /**
  9533. * Gets the pointer prefix to use
  9534. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9535. */
  9536. Tools.GetPointerPrefix = function () {
  9537. var eventPrefix = "pointer";
  9538. // Check if pointer events are supported
  9539. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9540. eventPrefix = "mouse";
  9541. }
  9542. return eventPrefix;
  9543. };
  9544. /**
  9545. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9546. * @param func - the function to be called
  9547. * @param requester - the object that will request the next frame. Falls back to window.
  9548. * @returns frame number
  9549. */
  9550. Tools.QueueNewFrame = function (func, requester) {
  9551. if (!Tools.IsWindowObjectExist()) {
  9552. return setTimeout(func, 16);
  9553. }
  9554. if (!requester) {
  9555. requester = window;
  9556. }
  9557. if (requester.requestAnimationFrame) {
  9558. return requester.requestAnimationFrame(func);
  9559. }
  9560. else if (requester.msRequestAnimationFrame) {
  9561. return requester.msRequestAnimationFrame(func);
  9562. }
  9563. else if (requester.webkitRequestAnimationFrame) {
  9564. return requester.webkitRequestAnimationFrame(func);
  9565. }
  9566. else if (requester.mozRequestAnimationFrame) {
  9567. return requester.mozRequestAnimationFrame(func);
  9568. }
  9569. else if (requester.oRequestAnimationFrame) {
  9570. return requester.oRequestAnimationFrame(func);
  9571. }
  9572. else {
  9573. return window.setTimeout(func, 16);
  9574. }
  9575. };
  9576. /**
  9577. * Ask the browser to promote the current element to fullscreen rendering mode
  9578. * @param element defines the DOM element to promote
  9579. */
  9580. Tools.RequestFullscreen = function (element) {
  9581. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9582. if (!requestFunction)
  9583. return;
  9584. requestFunction.call(element);
  9585. };
  9586. /**
  9587. * Asks the browser to exit fullscreen mode
  9588. */
  9589. Tools.ExitFullscreen = function () {
  9590. if (document.exitFullscreen) {
  9591. document.exitFullscreen();
  9592. }
  9593. else if (document.mozCancelFullScreen) {
  9594. document.mozCancelFullScreen();
  9595. }
  9596. else if (document.webkitCancelFullScreen) {
  9597. document.webkitCancelFullScreen();
  9598. }
  9599. else if (document.msCancelFullScreen) {
  9600. document.msCancelFullScreen();
  9601. }
  9602. };
  9603. /**
  9604. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9605. * @param url define the url we are trying
  9606. * @param element define the dom element where to configure the cors policy
  9607. */
  9608. Tools.SetCorsBehavior = function (url, element) {
  9609. if (url && url.indexOf("data:") === 0) {
  9610. return;
  9611. }
  9612. if (Tools.CorsBehavior) {
  9613. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9614. element.crossOrigin = Tools.CorsBehavior;
  9615. }
  9616. else {
  9617. var result = Tools.CorsBehavior(url);
  9618. if (result) {
  9619. element.crossOrigin = result;
  9620. }
  9621. }
  9622. }
  9623. };
  9624. // External files
  9625. /**
  9626. * Removes unwanted characters from an url
  9627. * @param url defines the url to clean
  9628. * @returns the cleaned url
  9629. */
  9630. Tools.CleanUrl = function (url) {
  9631. url = url.replace(/#/mg, "%23");
  9632. return url;
  9633. };
  9634. /**
  9635. * Loads an image as an HTMLImageElement.
  9636. * @param input url string, ArrayBuffer, or Blob to load
  9637. * @param onLoad callback called when the image successfully loads
  9638. * @param onError callback called when the image fails to load
  9639. * @param database database for caching
  9640. * @returns the HTMLImageElement of the loaded image
  9641. */
  9642. Tools.LoadImage = function (input, onLoad, onError, database) {
  9643. var url;
  9644. var usingObjectURL = false;
  9645. if (input instanceof ArrayBuffer) {
  9646. url = URL.createObjectURL(new Blob([input]));
  9647. usingObjectURL = true;
  9648. }
  9649. else if (input instanceof Blob) {
  9650. url = URL.createObjectURL(input);
  9651. usingObjectURL = true;
  9652. }
  9653. else {
  9654. url = Tools.CleanUrl(input);
  9655. url = Tools.PreprocessUrl(input);
  9656. }
  9657. var img = new Image();
  9658. Tools.SetCorsBehavior(url, img);
  9659. var loadHandler = function () {
  9660. if (usingObjectURL && img.src) {
  9661. URL.revokeObjectURL(img.src);
  9662. }
  9663. img.removeEventListener("load", loadHandler);
  9664. img.removeEventListener("error", errorHandler);
  9665. onLoad(img);
  9666. };
  9667. var errorHandler = function (err) {
  9668. if (usingObjectURL && img.src) {
  9669. URL.revokeObjectURL(img.src);
  9670. }
  9671. img.removeEventListener("load", loadHandler);
  9672. img.removeEventListener("error", errorHandler);
  9673. Tools.Error("Error while trying to load image: " + input);
  9674. if (onError) {
  9675. onError("Error while trying to load image: " + input, err);
  9676. }
  9677. };
  9678. img.addEventListener("load", loadHandler);
  9679. img.addEventListener("error", errorHandler);
  9680. var noIndexedDB = function () {
  9681. img.src = url;
  9682. };
  9683. var loadFromIndexedDB = function () {
  9684. if (database) {
  9685. database.loadImageFromDB(url, img);
  9686. }
  9687. };
  9688. //ANY database to do!
  9689. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9690. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9691. }
  9692. else {
  9693. if (url.indexOf("file:") !== -1) {
  9694. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9695. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9696. try {
  9697. var blobURL;
  9698. try {
  9699. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9700. }
  9701. catch (ex) {
  9702. // Chrome doesn't support oneTimeOnly parameter
  9703. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9704. }
  9705. img.src = blobURL;
  9706. usingObjectURL = true;
  9707. }
  9708. catch (e) {
  9709. img.src = "";
  9710. }
  9711. return img;
  9712. }
  9713. }
  9714. noIndexedDB();
  9715. }
  9716. return img;
  9717. };
  9718. /**
  9719. * Loads a file
  9720. * @param url url string, ArrayBuffer, or Blob to load
  9721. * @param onSuccess callback called when the file successfully loads
  9722. * @param onProgress callback called while file is loading (if the server supports this mode)
  9723. * @param database database for caching
  9724. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9725. * @param onError callback called when the file fails to load
  9726. * @returns a file request object
  9727. */
  9728. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9729. url = Tools.CleanUrl(url);
  9730. url = Tools.PreprocessUrl(url);
  9731. // If file and file input are set
  9732. if (url.indexOf("file:") !== -1) {
  9733. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9734. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9735. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9736. }
  9737. }
  9738. var loadUrl = Tools.BaseUrl + url;
  9739. var aborted = false;
  9740. var fileRequest = {
  9741. onCompleteObservable: new BABYLON.Observable(),
  9742. abort: function () { return aborted = true; },
  9743. };
  9744. var requestFile = function () {
  9745. var request = new XMLHttpRequest();
  9746. var retryHandle = null;
  9747. fileRequest.abort = function () {
  9748. aborted = true;
  9749. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9750. request.abort();
  9751. }
  9752. if (retryHandle !== null) {
  9753. clearTimeout(retryHandle);
  9754. retryHandle = null;
  9755. }
  9756. };
  9757. var retryLoop = function (retryIndex) {
  9758. request.open('GET', loadUrl, true);
  9759. if (useArrayBuffer) {
  9760. request.responseType = "arraybuffer";
  9761. }
  9762. if (onProgress) {
  9763. request.addEventListener("progress", onProgress);
  9764. }
  9765. var onLoadEnd = function () {
  9766. request.removeEventListener("loadend", onLoadEnd);
  9767. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9768. fileRequest.onCompleteObservable.clear();
  9769. };
  9770. request.addEventListener("loadend", onLoadEnd);
  9771. var onReadyStateChange = function () {
  9772. if (aborted) {
  9773. return;
  9774. }
  9775. // In case of undefined state in some browsers.
  9776. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9777. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9778. request.removeEventListener("readystatechange", onReadyStateChange);
  9779. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9780. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9781. return;
  9782. }
  9783. var retryStrategy = Tools.DefaultRetryStrategy;
  9784. if (retryStrategy) {
  9785. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9786. if (waitTime !== -1) {
  9787. // Prevent the request from completing for retry.
  9788. request.removeEventListener("loadend", onLoadEnd);
  9789. request = new XMLHttpRequest();
  9790. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9791. return;
  9792. }
  9793. }
  9794. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9795. if (onError) {
  9796. onError(request, e);
  9797. }
  9798. else {
  9799. throw e;
  9800. }
  9801. }
  9802. };
  9803. request.addEventListener("readystatechange", onReadyStateChange);
  9804. request.send();
  9805. };
  9806. retryLoop(0);
  9807. };
  9808. // Caching all files
  9809. if (database && database.enableSceneOffline) {
  9810. var noIndexedDB_1 = function (request) {
  9811. if (request && request.status > 400) {
  9812. if (onError) {
  9813. onError(request);
  9814. }
  9815. }
  9816. else {
  9817. if (!aborted) {
  9818. requestFile();
  9819. }
  9820. }
  9821. };
  9822. var loadFromIndexedDB = function () {
  9823. // TODO: database needs to support aborting and should return a IFileRequest
  9824. if (aborted) {
  9825. return;
  9826. }
  9827. if (database) {
  9828. database.loadFileFromDB(url, function (data) {
  9829. if (!aborted) {
  9830. onSuccess(data);
  9831. }
  9832. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9833. }, onProgress ? function (event) {
  9834. if (!aborted) {
  9835. onProgress(event);
  9836. }
  9837. } : undefined, noIndexedDB_1, useArrayBuffer);
  9838. }
  9839. };
  9840. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9841. }
  9842. else {
  9843. requestFile();
  9844. }
  9845. return fileRequest;
  9846. };
  9847. /**
  9848. * Load a script (identified by an url). When the url returns, the
  9849. * content of this file is added into a new script element, attached to the DOM (body element)
  9850. * @param scriptUrl defines the url of the script to laod
  9851. * @param onSuccess defines the callback called when the script is loaded
  9852. * @param onError defines the callback to call if an error occurs
  9853. */
  9854. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9855. if (!Tools.IsWindowObjectExist()) {
  9856. return;
  9857. }
  9858. var head = document.getElementsByTagName('head')[0];
  9859. var script = document.createElement('script');
  9860. script.type = 'text/javascript';
  9861. script.src = scriptUrl;
  9862. script.onload = function () {
  9863. if (onSuccess) {
  9864. onSuccess();
  9865. }
  9866. };
  9867. script.onerror = function (e) {
  9868. if (onError) {
  9869. onError("Unable to load script '" + scriptUrl + "'", e);
  9870. }
  9871. };
  9872. head.appendChild(script);
  9873. };
  9874. /**
  9875. * Loads a file from a blob
  9876. * @param fileToLoad defines the blob to use
  9877. * @param callback defines the callback to call when data is loaded
  9878. * @param progressCallback defines the callback to call during loading process
  9879. * @returns a file request object
  9880. */
  9881. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9882. var reader = new FileReader();
  9883. var request = {
  9884. onCompleteObservable: new BABYLON.Observable(),
  9885. abort: function () { return reader.abort(); },
  9886. };
  9887. reader.onloadend = function (e) {
  9888. request.onCompleteObservable.notifyObservers(request);
  9889. };
  9890. reader.onload = function (e) {
  9891. //target doesn't have result from ts 1.3
  9892. callback(e.target['result']);
  9893. };
  9894. reader.onprogress = progressCallback;
  9895. reader.readAsDataURL(fileToLoad);
  9896. return request;
  9897. };
  9898. /**
  9899. * Loads a file
  9900. * @param fileToLoad defines the file to load
  9901. * @param callback defines the callback to call when data is loaded
  9902. * @param progressCallBack defines the callback to call during loading process
  9903. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9904. * @returns a file request object
  9905. */
  9906. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9907. var reader = new FileReader();
  9908. var request = {
  9909. onCompleteObservable: new BABYLON.Observable(),
  9910. abort: function () { return reader.abort(); },
  9911. };
  9912. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9913. reader.onerror = function (e) {
  9914. Tools.Log("Error while reading file: " + fileToLoad.name);
  9915. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9916. };
  9917. reader.onload = function (e) {
  9918. //target doesn't have result from ts 1.3
  9919. callback(e.target['result']);
  9920. };
  9921. if (progressCallBack) {
  9922. reader.onprogress = progressCallBack;
  9923. }
  9924. if (!useArrayBuffer) {
  9925. // Asynchronous read
  9926. reader.readAsText(fileToLoad);
  9927. }
  9928. else {
  9929. reader.readAsArrayBuffer(fileToLoad);
  9930. }
  9931. return request;
  9932. };
  9933. /**
  9934. * Creates a data url from a given string content
  9935. * @param content defines the content to convert
  9936. * @returns the new data url link
  9937. */
  9938. Tools.FileAsURL = function (content) {
  9939. var fileBlob = new Blob([content]);
  9940. var url = window.URL || window.webkitURL;
  9941. var link = url.createObjectURL(fileBlob);
  9942. return link;
  9943. };
  9944. /**
  9945. * Format the given number to a specific decimal format
  9946. * @param value defines the number to format
  9947. * @param decimals defines the number of decimals to use
  9948. * @returns the formatted string
  9949. */
  9950. Tools.Format = function (value, decimals) {
  9951. if (decimals === void 0) { decimals = 2; }
  9952. return value.toFixed(decimals);
  9953. };
  9954. /**
  9955. * Checks if a given vector is inside a specific range
  9956. * @param v defines the vector to test
  9957. * @param min defines the minimum range
  9958. * @param max defines the maximum range
  9959. */
  9960. Tools.CheckExtends = function (v, min, max) {
  9961. if (v.x < min.x)
  9962. min.x = v.x;
  9963. if (v.y < min.y)
  9964. min.y = v.y;
  9965. if (v.z < min.z)
  9966. min.z = v.z;
  9967. if (v.x > max.x)
  9968. max.x = v.x;
  9969. if (v.y > max.y)
  9970. max.y = v.y;
  9971. if (v.z > max.z)
  9972. max.z = v.z;
  9973. };
  9974. /**
  9975. * Tries to copy an object by duplicating every property
  9976. * @param source defines the source object
  9977. * @param destination defines the target object
  9978. * @param doNotCopyList defines a list of properties to avoid
  9979. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9980. */
  9981. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9982. for (var prop in source) {
  9983. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9984. continue;
  9985. }
  9986. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9987. continue;
  9988. }
  9989. var sourceValue = source[prop];
  9990. var typeOfSourceValue = typeof sourceValue;
  9991. if (typeOfSourceValue === "function") {
  9992. continue;
  9993. }
  9994. try {
  9995. if (typeOfSourceValue === "object") {
  9996. if (sourceValue instanceof Array) {
  9997. destination[prop] = [];
  9998. if (sourceValue.length > 0) {
  9999. if (typeof sourceValue[0] == "object") {
  10000. for (var index = 0; index < sourceValue.length; index++) {
  10001. var clonedValue = cloneValue(sourceValue[index], destination);
  10002. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10003. destination[prop].push(clonedValue);
  10004. }
  10005. }
  10006. }
  10007. else {
  10008. destination[prop] = sourceValue.slice(0);
  10009. }
  10010. }
  10011. }
  10012. else {
  10013. destination[prop] = cloneValue(sourceValue, destination);
  10014. }
  10015. }
  10016. else {
  10017. destination[prop] = sourceValue;
  10018. }
  10019. }
  10020. catch (e) {
  10021. // Just ignore error (it could be because of a read-only property)
  10022. }
  10023. }
  10024. };
  10025. /**
  10026. * Gets a boolean indicating if the given object has no own property
  10027. * @param obj defines the object to test
  10028. * @returns true if object has no own property
  10029. */
  10030. Tools.IsEmpty = function (obj) {
  10031. for (var i in obj) {
  10032. if (obj.hasOwnProperty(i)) {
  10033. return false;
  10034. }
  10035. }
  10036. return true;
  10037. };
  10038. /**
  10039. * Function used to register events at window level
  10040. * @param events defines the events to register
  10041. */
  10042. Tools.RegisterTopRootEvents = function (events) {
  10043. for (var index = 0; index < events.length; index++) {
  10044. var event = events[index];
  10045. window.addEventListener(event.name, event.handler, false);
  10046. try {
  10047. if (window.parent) {
  10048. window.parent.addEventListener(event.name, event.handler, false);
  10049. }
  10050. }
  10051. catch (e) {
  10052. // Silently fails...
  10053. }
  10054. }
  10055. };
  10056. /**
  10057. * Function used to unregister events from window level
  10058. * @param events defines the events to unregister
  10059. */
  10060. Tools.UnregisterTopRootEvents = function (events) {
  10061. for (var index = 0; index < events.length; index++) {
  10062. var event = events[index];
  10063. window.removeEventListener(event.name, event.handler);
  10064. try {
  10065. if (window.parent) {
  10066. window.parent.removeEventListener(event.name, event.handler);
  10067. }
  10068. }
  10069. catch (e) {
  10070. // Silently fails...
  10071. }
  10072. }
  10073. };
  10074. /**
  10075. * Dumps the current bound framebuffer
  10076. * @param width defines the rendering width
  10077. * @param height defines the rendering height
  10078. * @param engine defines the hosting engine
  10079. * @param successCallback defines the callback triggered once the data are available
  10080. * @param mimeType defines the mime type of the result
  10081. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10082. */
  10083. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10084. if (mimeType === void 0) { mimeType = "image/png"; }
  10085. // Read the contents of the framebuffer
  10086. var numberOfChannelsByLine = width * 4;
  10087. var halfHeight = height / 2;
  10088. //Reading datas from WebGL
  10089. var data = engine.readPixels(0, 0, width, height);
  10090. //To flip image on Y axis.
  10091. for (var i = 0; i < halfHeight; i++) {
  10092. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10093. var currentCell = j + i * numberOfChannelsByLine;
  10094. var targetLine = height - i - 1;
  10095. var targetCell = j + targetLine * numberOfChannelsByLine;
  10096. var temp = data[currentCell];
  10097. data[currentCell] = data[targetCell];
  10098. data[targetCell] = temp;
  10099. }
  10100. }
  10101. // Create a 2D canvas to store the result
  10102. if (!screenshotCanvas) {
  10103. screenshotCanvas = document.createElement('canvas');
  10104. }
  10105. screenshotCanvas.width = width;
  10106. screenshotCanvas.height = height;
  10107. var context = screenshotCanvas.getContext('2d');
  10108. if (context) {
  10109. // Copy the pixels to a 2D canvas
  10110. var imageData = context.createImageData(width, height);
  10111. var castData = (imageData.data);
  10112. castData.set(data);
  10113. context.putImageData(imageData, 0, 0);
  10114. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10115. }
  10116. };
  10117. /**
  10118. * Converts the canvas data to blob.
  10119. * This acts as a polyfill for browsers not supporting the to blob function.
  10120. * @param canvas Defines the canvas to extract the data from
  10121. * @param successCallback Defines the callback triggered once the data are available
  10122. * @param mimeType Defines the mime type of the result
  10123. */
  10124. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10125. if (mimeType === void 0) { mimeType = "image/png"; }
  10126. // We need HTMLCanvasElement.toBlob for HD screenshots
  10127. if (!canvas.toBlob) {
  10128. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10129. canvas.toBlob = function (callback, type, quality) {
  10130. var _this = this;
  10131. setTimeout(function () {
  10132. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10133. for (var i = 0; i < len; i++) {
  10134. arr[i] = binStr.charCodeAt(i);
  10135. }
  10136. callback(new Blob([arr]));
  10137. });
  10138. };
  10139. }
  10140. canvas.toBlob(function (blob) {
  10141. successCallback(blob);
  10142. }, mimeType);
  10143. };
  10144. /**
  10145. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10146. * @param successCallback defines the callback triggered once the data are available
  10147. * @param mimeType defines the mime type of the result
  10148. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10149. */
  10150. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10151. if (mimeType === void 0) { mimeType = "image/png"; }
  10152. if (successCallback) {
  10153. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10154. successCallback(base64Image);
  10155. }
  10156. else {
  10157. this.ToBlob(screenshotCanvas, function (blob) {
  10158. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10159. if (("download" in document.createElement("a"))) {
  10160. if (!fileName) {
  10161. var date = new Date();
  10162. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10163. fileName = "screenshot_" + stringDate + ".png";
  10164. }
  10165. Tools.Download(blob, fileName);
  10166. }
  10167. else {
  10168. var url = URL.createObjectURL(blob);
  10169. var newWindow = window.open("");
  10170. if (!newWindow)
  10171. return;
  10172. var img = newWindow.document.createElement("img");
  10173. img.onload = function () {
  10174. // no longer need to read the blob so it's revoked
  10175. URL.revokeObjectURL(url);
  10176. };
  10177. img.src = url;
  10178. newWindow.document.body.appendChild(img);
  10179. }
  10180. }, mimeType);
  10181. }
  10182. };
  10183. /**
  10184. * Downloads a blob in the browser
  10185. * @param blob defines the blob to download
  10186. * @param fileName defines the name of the downloaded file
  10187. */
  10188. Tools.Download = function (blob, fileName) {
  10189. if (navigator && navigator.msSaveBlob) {
  10190. navigator.msSaveBlob(blob, fileName);
  10191. return;
  10192. }
  10193. var url = window.URL.createObjectURL(blob);
  10194. var a = document.createElement("a");
  10195. document.body.appendChild(a);
  10196. a.style.display = "none";
  10197. a.href = url;
  10198. a.download = fileName;
  10199. a.addEventListener("click", function () {
  10200. if (a.parentElement) {
  10201. a.parentElement.removeChild(a);
  10202. }
  10203. });
  10204. a.click();
  10205. window.URL.revokeObjectURL(url);
  10206. };
  10207. /**
  10208. * Captures a screenshot of the current rendering
  10209. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10210. * @param engine defines the rendering engine
  10211. * @param camera defines the source camera
  10212. * @param size This parameter can be set to a single number or to an object with the
  10213. * following (optional) properties: precision, width, height. If a single number is passed,
  10214. * it will be used for both width and height. If an object is passed, the screenshot size
  10215. * will be derived from the parameters. The precision property is a multiplier allowing
  10216. * rendering at a higher or lower resolution
  10217. * @param successCallback defines the callback receives a single parameter which contains the
  10218. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10219. * src parameter of an <img> to display it
  10220. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10221. * Check your browser for supported MIME types
  10222. */
  10223. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10224. if (mimeType === void 0) { mimeType = "image/png"; }
  10225. var width;
  10226. var height;
  10227. // If a precision value is specified
  10228. if (size.precision) {
  10229. width = Math.round(engine.getRenderWidth() * size.precision);
  10230. height = Math.round(width / engine.getAspectRatio(camera));
  10231. }
  10232. else if (size.width && size.height) {
  10233. width = size.width;
  10234. height = size.height;
  10235. }
  10236. //If passing only width, computing height to keep display canvas ratio.
  10237. else if (size.width && !size.height) {
  10238. width = size.width;
  10239. height = Math.round(width / engine.getAspectRatio(camera));
  10240. }
  10241. //If passing only height, computing width to keep display canvas ratio.
  10242. else if (size.height && !size.width) {
  10243. height = size.height;
  10244. width = Math.round(height * engine.getAspectRatio(camera));
  10245. }
  10246. //Assuming here that "size" parameter is a number
  10247. else if (!isNaN(size)) {
  10248. height = size;
  10249. width = size;
  10250. }
  10251. else {
  10252. Tools.Error("Invalid 'size' parameter !");
  10253. return;
  10254. }
  10255. if (!screenshotCanvas) {
  10256. screenshotCanvas = document.createElement('canvas');
  10257. }
  10258. screenshotCanvas.width = width;
  10259. screenshotCanvas.height = height;
  10260. var renderContext = screenshotCanvas.getContext("2d");
  10261. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10262. var newWidth = width;
  10263. var newHeight = newWidth / ratio;
  10264. if (newHeight > height) {
  10265. newHeight = height;
  10266. newWidth = newHeight * ratio;
  10267. }
  10268. var offsetX = Math.max(0, width - newWidth) / 2;
  10269. var offsetY = Math.max(0, height - newHeight) / 2;
  10270. var renderingCanvas = engine.getRenderingCanvas();
  10271. if (renderContext && renderingCanvas) {
  10272. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10273. }
  10274. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10275. };
  10276. /**
  10277. * Generates an image screenshot from the specified camera.
  10278. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10279. * @param engine The engine to use for rendering
  10280. * @param camera The camera to use for rendering
  10281. * @param size This parameter can be set to a single number or to an object with the
  10282. * following (optional) properties: precision, width, height. If a single number is passed,
  10283. * it will be used for both width and height. If an object is passed, the screenshot size
  10284. * will be derived from the parameters. The precision property is a multiplier allowing
  10285. * rendering at a higher or lower resolution
  10286. * @param successCallback The callback receives a single parameter which contains the
  10287. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10288. * src parameter of an <img> to display it
  10289. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10290. * Check your browser for supported MIME types
  10291. * @param samples Texture samples (default: 1)
  10292. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10293. * @param fileName A name for for the downloaded file.
  10294. */
  10295. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10296. if (mimeType === void 0) { mimeType = "image/png"; }
  10297. if (samples === void 0) { samples = 1; }
  10298. if (antialiasing === void 0) { antialiasing = false; }
  10299. var width;
  10300. var height;
  10301. //If a precision value is specified
  10302. if (size.precision) {
  10303. width = Math.round(engine.getRenderWidth() * size.precision);
  10304. height = Math.round(width / engine.getAspectRatio(camera));
  10305. size = { width: width, height: height };
  10306. }
  10307. else if (size.width && size.height) {
  10308. width = size.width;
  10309. height = size.height;
  10310. }
  10311. //If passing only width, computing height to keep display canvas ratio.
  10312. else if (size.width && !size.height) {
  10313. width = size.width;
  10314. height = Math.round(width / engine.getAspectRatio(camera));
  10315. size = { width: width, height: height };
  10316. }
  10317. //If passing only height, computing width to keep display canvas ratio.
  10318. else if (size.height && !size.width) {
  10319. height = size.height;
  10320. width = Math.round(height * engine.getAspectRatio(camera));
  10321. size = { width: width, height: height };
  10322. }
  10323. //Assuming here that "size" parameter is a number
  10324. else if (!isNaN(size)) {
  10325. height = size;
  10326. width = size;
  10327. }
  10328. else {
  10329. Tools.Error("Invalid 'size' parameter !");
  10330. return;
  10331. }
  10332. var scene = camera.getScene();
  10333. var previousCamera = null;
  10334. if (scene.activeCamera !== camera) {
  10335. previousCamera = scene.activeCamera;
  10336. scene.activeCamera = camera;
  10337. }
  10338. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10339. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10340. texture.renderList = null;
  10341. texture.samples = samples;
  10342. if (antialiasing) {
  10343. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10344. }
  10345. texture.onAfterRenderObservable.add(function () {
  10346. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10347. });
  10348. scene.incrementRenderId();
  10349. scene.resetCachedMaterial();
  10350. texture.render(true);
  10351. texture.dispose();
  10352. if (previousCamera) {
  10353. scene.activeCamera = previousCamera;
  10354. }
  10355. camera.getProjectionMatrix(true); // Force cache refresh;
  10356. };
  10357. /**
  10358. * Validates if xhr data is correct
  10359. * @param xhr defines the request to validate
  10360. * @param dataType defines the expected data type
  10361. * @returns true if data is correct
  10362. */
  10363. Tools.ValidateXHRData = function (xhr, dataType) {
  10364. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10365. if (dataType === void 0) { dataType = 7; }
  10366. try {
  10367. if (dataType & 1) {
  10368. if (xhr.responseText && xhr.responseText.length > 0) {
  10369. return true;
  10370. }
  10371. else if (dataType === 1) {
  10372. return false;
  10373. }
  10374. }
  10375. if (dataType & 2) {
  10376. // Check header width and height since there is no "TGA" magic number
  10377. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10378. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10379. return true;
  10380. }
  10381. else if (dataType === 2) {
  10382. return false;
  10383. }
  10384. }
  10385. if (dataType & 4) {
  10386. // Check for the "DDS" magic number
  10387. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10388. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10389. return true;
  10390. }
  10391. else {
  10392. return false;
  10393. }
  10394. }
  10395. }
  10396. catch (e) {
  10397. // Global protection
  10398. }
  10399. return false;
  10400. };
  10401. /**
  10402. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10403. * Be aware Math.random() could cause collisions, but:
  10404. * "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"
  10405. * @returns a pseudo random id
  10406. */
  10407. Tools.RandomId = function () {
  10408. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10409. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10410. return v.toString(16);
  10411. });
  10412. };
  10413. /**
  10414. * Test if the given uri is a base64 string
  10415. * @param uri The uri to test
  10416. * @return True if the uri is a base64 string or false otherwise
  10417. */
  10418. Tools.IsBase64 = function (uri) {
  10419. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10420. };
  10421. /**
  10422. * Decode the given base64 uri.
  10423. * @param uri The uri to decode
  10424. * @return The decoded base64 data.
  10425. */
  10426. Tools.DecodeBase64 = function (uri) {
  10427. var decodedString = atob(uri.split(",")[1]);
  10428. var bufferLength = decodedString.length;
  10429. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10430. for (var i = 0; i < bufferLength; i++) {
  10431. bufferView[i] = decodedString.charCodeAt(i);
  10432. }
  10433. return bufferView.buffer;
  10434. };
  10435. Tools._AddLogEntry = function (entry) {
  10436. Tools._LogCache = entry + Tools._LogCache;
  10437. if (Tools.OnNewCacheEntry) {
  10438. Tools.OnNewCacheEntry(entry);
  10439. }
  10440. };
  10441. Tools._FormatMessage = function (message) {
  10442. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10443. var date = new Date();
  10444. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10445. };
  10446. Tools._LogDisabled = function (message) {
  10447. // nothing to do
  10448. };
  10449. Tools._LogEnabled = function (message) {
  10450. var formattedMessage = Tools._FormatMessage(message);
  10451. console.log("BJS - " + formattedMessage);
  10452. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10453. Tools._AddLogEntry(entry);
  10454. };
  10455. Tools._WarnDisabled = function (message) {
  10456. // nothing to do
  10457. };
  10458. Tools._WarnEnabled = function (message) {
  10459. var formattedMessage = Tools._FormatMessage(message);
  10460. console.warn("BJS - " + formattedMessage);
  10461. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10462. Tools._AddLogEntry(entry);
  10463. };
  10464. Tools._ErrorDisabled = function (message) {
  10465. // nothing to do
  10466. };
  10467. Tools._ErrorEnabled = function (message) {
  10468. Tools.errorsCount++;
  10469. var formattedMessage = Tools._FormatMessage(message);
  10470. console.error("BJS - " + formattedMessage);
  10471. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10472. Tools._AddLogEntry(entry);
  10473. };
  10474. Object.defineProperty(Tools, "LogCache", {
  10475. /**
  10476. * Gets current log cache (list of logs)
  10477. */
  10478. get: function () {
  10479. return Tools._LogCache;
  10480. },
  10481. enumerable: true,
  10482. configurable: true
  10483. });
  10484. /**
  10485. * Clears the log cache
  10486. */
  10487. Tools.ClearLogCache = function () {
  10488. Tools._LogCache = "";
  10489. Tools.errorsCount = 0;
  10490. };
  10491. Object.defineProperty(Tools, "LogLevels", {
  10492. /**
  10493. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10494. */
  10495. set: function (level) {
  10496. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10497. Tools.Log = Tools._LogEnabled;
  10498. }
  10499. else {
  10500. Tools.Log = Tools._LogDisabled;
  10501. }
  10502. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10503. Tools.Warn = Tools._WarnEnabled;
  10504. }
  10505. else {
  10506. Tools.Warn = Tools._WarnDisabled;
  10507. }
  10508. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10509. Tools.Error = Tools._ErrorEnabled;
  10510. }
  10511. else {
  10512. Tools.Error = Tools._ErrorDisabled;
  10513. }
  10514. },
  10515. enumerable: true,
  10516. configurable: true
  10517. });
  10518. /**
  10519. * Checks if the loaded document was accessed via `file:`-Protocol.
  10520. * @returns boolean
  10521. */
  10522. Tools.IsFileURL = function () {
  10523. return location.protocol === "file:";
  10524. };
  10525. /**
  10526. * Checks if the window object exists
  10527. * @returns true if the window object exists
  10528. */
  10529. Tools.IsWindowObjectExist = function () {
  10530. return (typeof window) !== "undefined";
  10531. };
  10532. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10533. /**
  10534. * Sets the current performance log level
  10535. */
  10536. set: function (level) {
  10537. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10538. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10539. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10540. return;
  10541. }
  10542. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10543. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10544. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10545. return;
  10546. }
  10547. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10548. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10554. };
  10555. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10556. };
  10557. Tools._StartUserMark = function (counterName, condition) {
  10558. if (condition === void 0) { condition = true; }
  10559. if (!Tools._performance) {
  10560. if (!Tools.IsWindowObjectExist()) {
  10561. return;
  10562. }
  10563. Tools._performance = window.performance;
  10564. }
  10565. if (!condition || !Tools._performance.mark) {
  10566. return;
  10567. }
  10568. Tools._performance.mark(counterName + "-Begin");
  10569. };
  10570. Tools._EndUserMark = function (counterName, condition) {
  10571. if (condition === void 0) { condition = true; }
  10572. if (!condition || !Tools._performance.mark) {
  10573. return;
  10574. }
  10575. Tools._performance.mark(counterName + "-End");
  10576. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10577. };
  10578. Tools._StartPerformanceConsole = function (counterName, condition) {
  10579. if (condition === void 0) { condition = true; }
  10580. if (!condition) {
  10581. return;
  10582. }
  10583. Tools._StartUserMark(counterName, condition);
  10584. if (console.time) {
  10585. console.time(counterName);
  10586. }
  10587. };
  10588. Tools._EndPerformanceConsole = function (counterName, condition) {
  10589. if (condition === void 0) { condition = true; }
  10590. if (!condition) {
  10591. return;
  10592. }
  10593. Tools._EndUserMark(counterName, condition);
  10594. if (console.time) {
  10595. console.timeEnd(counterName);
  10596. }
  10597. };
  10598. Object.defineProperty(Tools, "Now", {
  10599. /**
  10600. * Gets either window.performance.now() if supported or Date.now() else
  10601. */
  10602. get: function () {
  10603. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10604. return window.performance.now();
  10605. }
  10606. return Date.now();
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. /**
  10612. * This method will return the name of the class used to create the instance of the given object.
  10613. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10614. * @param object the object to get the class name from
  10615. * @param isType defines if the object is actually a type
  10616. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10617. */
  10618. Tools.GetClassName = function (object, isType) {
  10619. if (isType === void 0) { isType = false; }
  10620. var name = null;
  10621. if (!isType && object.getClassName) {
  10622. name = object.getClassName();
  10623. }
  10624. else {
  10625. if (object instanceof Object) {
  10626. var classObj = isType ? object : Object.getPrototypeOf(object);
  10627. name = classObj.constructor["__bjsclassName__"];
  10628. }
  10629. if (!name) {
  10630. name = typeof object;
  10631. }
  10632. }
  10633. return name;
  10634. };
  10635. /**
  10636. * Gets the first element of an array satisfying a given predicate
  10637. * @param array defines the array to browse
  10638. * @param predicate defines the predicate to use
  10639. * @returns null if not found or the element
  10640. */
  10641. Tools.First = function (array, predicate) {
  10642. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10643. var el = array_1[_i];
  10644. if (predicate(el)) {
  10645. return el;
  10646. }
  10647. }
  10648. return null;
  10649. };
  10650. /**
  10651. * This method will return the name of the full name of the class, including its owning module (if any).
  10652. * 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).
  10653. * @param object the object to get the class name from
  10654. * @param isType defines if the object is actually a type
  10655. * @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.
  10656. * @ignorenaming
  10657. */
  10658. Tools.getFullClassName = function (object, isType) {
  10659. if (isType === void 0) { isType = false; }
  10660. var className = null;
  10661. var moduleName = null;
  10662. if (!isType && object.getClassName) {
  10663. className = object.getClassName();
  10664. }
  10665. else {
  10666. if (object instanceof Object) {
  10667. var classObj = isType ? object : Object.getPrototypeOf(object);
  10668. className = classObj.constructor["__bjsclassName__"];
  10669. moduleName = classObj.constructor["__bjsmoduleName__"];
  10670. }
  10671. if (!className) {
  10672. className = typeof object;
  10673. }
  10674. }
  10675. if (!className) {
  10676. return null;
  10677. }
  10678. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10679. };
  10680. /**
  10681. * Returns a promise that resolves after the given amount of time.
  10682. * @param delay Number of milliseconds to delay
  10683. * @returns Promise that resolves after the given amount of time
  10684. */
  10685. Tools.DelayAsync = function (delay) {
  10686. return new Promise(function (resolve) {
  10687. setTimeout(function () {
  10688. resolve();
  10689. }, delay);
  10690. });
  10691. };
  10692. /**
  10693. * Gets the current gradient from an array of IValueGradient
  10694. * @param ratio defines the current ratio to get
  10695. * @param gradients defines the array of IValueGradient
  10696. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10697. */
  10698. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10699. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10700. var currentGradient = gradients[gradientIndex];
  10701. var nextGradient = gradients[gradientIndex + 1];
  10702. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10703. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10704. updateFunc(currentGradient, nextGradient, scale);
  10705. return;
  10706. }
  10707. }
  10708. // Use last index if over
  10709. var lastIndex = gradients.length - 1;
  10710. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10711. };
  10712. /**
  10713. * Gets or sets the base URL to use to load assets
  10714. */
  10715. Tools.BaseUrl = "";
  10716. /**
  10717. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10718. */
  10719. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10720. /**
  10721. * Default behaviour for cors in the application.
  10722. * It can be a string if the expected behavior is identical in the entire app.
  10723. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10724. */
  10725. Tools.CorsBehavior = "anonymous";
  10726. /**
  10727. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10728. * @ignorenaming
  10729. */
  10730. Tools.UseFallbackTexture = true;
  10731. /**
  10732. * Use this object to register external classes like custom textures or material
  10733. * to allow the laoders to instantiate them
  10734. */
  10735. Tools.RegisteredExternalClasses = {};
  10736. /**
  10737. * Texture content used if a texture cannot loaded
  10738. * @ignorenaming
  10739. */
  10740. 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";
  10741. Tools._tmpFloatArray = new Float32Array(1);
  10742. /**
  10743. * Gets or sets a function used to pre-process url before using them to load assets
  10744. */
  10745. Tools.PreprocessUrl = function (url) {
  10746. return url;
  10747. };
  10748. // Logs
  10749. /**
  10750. * No log
  10751. */
  10752. Tools.NoneLogLevel = 0;
  10753. /**
  10754. * Only message logs
  10755. */
  10756. Tools.MessageLogLevel = 1;
  10757. /**
  10758. * Only warning logs
  10759. */
  10760. Tools.WarningLogLevel = 2;
  10761. /**
  10762. * Only error logs
  10763. */
  10764. Tools.ErrorLogLevel = 4;
  10765. /**
  10766. * All logs
  10767. */
  10768. Tools.AllLogLevel = 7;
  10769. Tools._LogCache = "";
  10770. /**
  10771. * Gets a value indicating the number of loading errors
  10772. * @ignorenaming
  10773. */
  10774. Tools.errorsCount = 0;
  10775. /**
  10776. * Log a message to the console
  10777. */
  10778. Tools.Log = Tools._LogEnabled;
  10779. /**
  10780. * Write a warning message to the console
  10781. */
  10782. Tools.Warn = Tools._WarnEnabled;
  10783. /**
  10784. * Write an error message to the console
  10785. */
  10786. Tools.Error = Tools._ErrorEnabled;
  10787. // Performances
  10788. /**
  10789. * No performance log
  10790. */
  10791. Tools.PerformanceNoneLogLevel = 0;
  10792. /**
  10793. * Use user marks to log performance
  10794. */
  10795. Tools.PerformanceUserMarkLogLevel = 1;
  10796. /**
  10797. * Log performance to the console
  10798. */
  10799. Tools.PerformanceConsoleLogLevel = 2;
  10800. /**
  10801. * Starts a performance counter
  10802. */
  10803. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10804. /**
  10805. * Ends a specific performance coutner
  10806. */
  10807. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10808. return Tools;
  10809. }());
  10810. BABYLON.Tools = Tools;
  10811. /**
  10812. * This class is used to track a performance counter which is number based.
  10813. * The user has access to many properties which give statistics of different nature.
  10814. *
  10815. * The implementer can track two kinds of Performance Counter: time and count.
  10816. * 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.
  10817. * 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.
  10818. */
  10819. var PerfCounter = /** @class */ (function () {
  10820. /**
  10821. * Creates a new counter
  10822. */
  10823. function PerfCounter() {
  10824. this._startMonitoringTime = 0;
  10825. this._min = 0;
  10826. this._max = 0;
  10827. this._average = 0;
  10828. this._lastSecAverage = 0;
  10829. this._current = 0;
  10830. this._totalValueCount = 0;
  10831. this._totalAccumulated = 0;
  10832. this._lastSecAccumulated = 0;
  10833. this._lastSecTime = 0;
  10834. this._lastSecValueCount = 0;
  10835. }
  10836. Object.defineProperty(PerfCounter.prototype, "min", {
  10837. /**
  10838. * Returns the smallest value ever
  10839. */
  10840. get: function () {
  10841. return this._min;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(PerfCounter.prototype, "max", {
  10847. /**
  10848. * Returns the biggest value ever
  10849. */
  10850. get: function () {
  10851. return this._max;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(PerfCounter.prototype, "average", {
  10857. /**
  10858. * Returns the average value since the performance counter is running
  10859. */
  10860. get: function () {
  10861. return this._average;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10867. /**
  10868. * Returns the average value of the last second the counter was monitored
  10869. */
  10870. get: function () {
  10871. return this._lastSecAverage;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(PerfCounter.prototype, "current", {
  10877. /**
  10878. * Returns the current value
  10879. */
  10880. get: function () {
  10881. return this._current;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(PerfCounter.prototype, "total", {
  10887. /**
  10888. * Gets the accumulated total
  10889. */
  10890. get: function () {
  10891. return this._totalAccumulated;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(PerfCounter.prototype, "count", {
  10897. /**
  10898. * Gets the total value count
  10899. */
  10900. get: function () {
  10901. return this._totalValueCount;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. /**
  10907. * Call this method to start monitoring a new frame.
  10908. * 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.
  10909. */
  10910. PerfCounter.prototype.fetchNewFrame = function () {
  10911. this._totalValueCount++;
  10912. this._current = 0;
  10913. this._lastSecValueCount++;
  10914. };
  10915. /**
  10916. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10917. * @param newCount the count value to add to the monitored count
  10918. * @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.
  10919. */
  10920. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10921. if (!PerfCounter.Enabled) {
  10922. return;
  10923. }
  10924. this._current += newCount;
  10925. if (fetchResult) {
  10926. this._fetchResult();
  10927. }
  10928. };
  10929. /**
  10930. * Start monitoring this performance counter
  10931. */
  10932. PerfCounter.prototype.beginMonitoring = function () {
  10933. if (!PerfCounter.Enabled) {
  10934. return;
  10935. }
  10936. this._startMonitoringTime = Tools.Now;
  10937. };
  10938. /**
  10939. * Compute the time lapsed since the previous beginMonitoring() call.
  10940. * @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
  10941. */
  10942. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10943. if (newFrame === void 0) { newFrame = true; }
  10944. if (!PerfCounter.Enabled) {
  10945. return;
  10946. }
  10947. if (newFrame) {
  10948. this.fetchNewFrame();
  10949. }
  10950. var currentTime = Tools.Now;
  10951. this._current = currentTime - this._startMonitoringTime;
  10952. if (newFrame) {
  10953. this._fetchResult();
  10954. }
  10955. };
  10956. PerfCounter.prototype._fetchResult = function () {
  10957. this._totalAccumulated += this._current;
  10958. this._lastSecAccumulated += this._current;
  10959. // Min/Max update
  10960. this._min = Math.min(this._min, this._current);
  10961. this._max = Math.max(this._max, this._current);
  10962. this._average = this._totalAccumulated / this._totalValueCount;
  10963. // Reset last sec?
  10964. var now = Tools.Now;
  10965. if ((now - this._lastSecTime) > 1000) {
  10966. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10967. this._lastSecTime = now;
  10968. this._lastSecAccumulated = 0;
  10969. this._lastSecValueCount = 0;
  10970. }
  10971. };
  10972. /**
  10973. * Gets or sets a global boolean to turn on and off all the counters
  10974. */
  10975. PerfCounter.Enabled = true;
  10976. return PerfCounter;
  10977. }());
  10978. BABYLON.PerfCounter = PerfCounter;
  10979. /**
  10980. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10981. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10982. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10983. * @param name The name of the class, case should be preserved
  10984. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10985. */
  10986. function className(name, module) {
  10987. return function (target) {
  10988. target["__bjsclassName__"] = name;
  10989. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10990. };
  10991. }
  10992. BABYLON.className = className;
  10993. /**
  10994. * An implementation of a loop for asynchronous functions.
  10995. */
  10996. var AsyncLoop = /** @class */ (function () {
  10997. /**
  10998. * Constructor.
  10999. * @param iterations the number of iterations.
  11000. * @param func the function to run each iteration
  11001. * @param successCallback the callback that will be called upon succesful execution
  11002. * @param offset starting offset.
  11003. */
  11004. function AsyncLoop(
  11005. /**
  11006. * Defines the number of iterations for the loop
  11007. */
  11008. iterations, func, successCallback, offset) {
  11009. if (offset === void 0) { offset = 0; }
  11010. this.iterations = iterations;
  11011. this.index = offset - 1;
  11012. this._done = false;
  11013. this._fn = func;
  11014. this._successCallback = successCallback;
  11015. }
  11016. /**
  11017. * Execute the next iteration. Must be called after the last iteration was finished.
  11018. */
  11019. AsyncLoop.prototype.executeNext = function () {
  11020. if (!this._done) {
  11021. if (this.index + 1 < this.iterations) {
  11022. ++this.index;
  11023. this._fn(this);
  11024. }
  11025. else {
  11026. this.breakLoop();
  11027. }
  11028. }
  11029. };
  11030. /**
  11031. * Break the loop and run the success callback.
  11032. */
  11033. AsyncLoop.prototype.breakLoop = function () {
  11034. this._done = true;
  11035. this._successCallback();
  11036. };
  11037. /**
  11038. * Create and run an async loop.
  11039. * @param iterations the number of iterations.
  11040. * @param fn the function to run each iteration
  11041. * @param successCallback the callback that will be called upon succesful execution
  11042. * @param offset starting offset.
  11043. * @returns the created async loop object
  11044. */
  11045. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11046. if (offset === void 0) { offset = 0; }
  11047. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11048. loop.executeNext();
  11049. return loop;
  11050. };
  11051. /**
  11052. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11053. * @param iterations total number of iterations
  11054. * @param syncedIterations number of synchronous iterations in each async iteration.
  11055. * @param fn the function to call each iteration.
  11056. * @param callback a success call back that will be called when iterating stops.
  11057. * @param breakFunction a break condition (optional)
  11058. * @param timeout timeout settings for the setTimeout function. default - 0.
  11059. * @returns the created async loop object
  11060. */
  11061. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11062. if (timeout === void 0) { timeout = 0; }
  11063. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11064. if (breakFunction && breakFunction())
  11065. loop.breakLoop();
  11066. else {
  11067. setTimeout(function () {
  11068. for (var i = 0; i < syncedIterations; ++i) {
  11069. var iteration = (loop.index * syncedIterations) + i;
  11070. if (iteration >= iterations)
  11071. break;
  11072. fn(iteration);
  11073. if (breakFunction && breakFunction()) {
  11074. loop.breakLoop();
  11075. break;
  11076. }
  11077. }
  11078. loop.executeNext();
  11079. }, timeout);
  11080. }
  11081. }, callback);
  11082. };
  11083. return AsyncLoop;
  11084. }());
  11085. BABYLON.AsyncLoop = AsyncLoop;
  11086. })(BABYLON || (BABYLON = {}));
  11087. //# sourceMappingURL=babylon.tools.js.map
  11088. var BABYLON;
  11089. (function (BABYLON) {
  11090. var PromiseStates;
  11091. (function (PromiseStates) {
  11092. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11093. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11094. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11095. })(PromiseStates || (PromiseStates = {}));
  11096. var FulFillmentAgregator = /** @class */ (function () {
  11097. function FulFillmentAgregator() {
  11098. this.count = 0;
  11099. this.target = 0;
  11100. this.results = [];
  11101. }
  11102. return FulFillmentAgregator;
  11103. }());
  11104. var InternalPromise = /** @class */ (function () {
  11105. function InternalPromise(resolver) {
  11106. var _this = this;
  11107. this._state = PromiseStates.Pending;
  11108. this._children = new Array();
  11109. this._rejectWasConsumed = false;
  11110. if (!resolver) {
  11111. return;
  11112. }
  11113. try {
  11114. resolver(function (value) {
  11115. _this._resolve(value);
  11116. }, function (reason) {
  11117. _this._reject(reason);
  11118. });
  11119. }
  11120. catch (e) {
  11121. this._reject(e);
  11122. }
  11123. }
  11124. Object.defineProperty(InternalPromise.prototype, "_result", {
  11125. get: function () {
  11126. return this._resultValue;
  11127. },
  11128. set: function (value) {
  11129. this._resultValue = value;
  11130. if (this._parent && this._parent._result === undefined) {
  11131. this._parent._result = value;
  11132. }
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. InternalPromise.prototype.catch = function (onRejected) {
  11138. return this.then(undefined, onRejected);
  11139. };
  11140. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11141. var _this = this;
  11142. var newPromise = new InternalPromise();
  11143. newPromise._onFulfilled = onFulfilled;
  11144. newPromise._onRejected = onRejected;
  11145. // Composition
  11146. this._children.push(newPromise);
  11147. newPromise._parent = this;
  11148. if (this._state !== PromiseStates.Pending) {
  11149. BABYLON.Tools.SetImmediate(function () {
  11150. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11151. var returnedValue = newPromise._resolve(_this._result);
  11152. if (returnedValue !== undefined && returnedValue !== null) {
  11153. if (returnedValue._state !== undefined) {
  11154. var returnedPromise = returnedValue;
  11155. newPromise._children.push(returnedPromise);
  11156. returnedPromise._parent = newPromise;
  11157. newPromise = returnedPromise;
  11158. }
  11159. else {
  11160. newPromise._result = returnedValue;
  11161. }
  11162. }
  11163. }
  11164. else {
  11165. newPromise._reject(_this._reason);
  11166. }
  11167. });
  11168. }
  11169. return newPromise;
  11170. };
  11171. InternalPromise.prototype._moveChildren = function (children) {
  11172. var _this = this;
  11173. var _a;
  11174. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11175. this._children.forEach(function (child) {
  11176. child._parent = _this;
  11177. });
  11178. if (this._state === PromiseStates.Fulfilled) {
  11179. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11180. var child = _b[_i];
  11181. child._resolve(this._result);
  11182. }
  11183. }
  11184. else if (this._state === PromiseStates.Rejected) {
  11185. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11186. var child = _d[_c];
  11187. child._reject(this._reason);
  11188. }
  11189. }
  11190. };
  11191. InternalPromise.prototype._resolve = function (value) {
  11192. try {
  11193. this._state = PromiseStates.Fulfilled;
  11194. var returnedValue = null;
  11195. if (this._onFulfilled) {
  11196. returnedValue = this._onFulfilled(value);
  11197. }
  11198. if (returnedValue !== undefined && returnedValue !== null) {
  11199. if (returnedValue._state !== undefined) {
  11200. // Transmit children
  11201. var returnedPromise = returnedValue;
  11202. returnedPromise._parent = this;
  11203. returnedPromise._moveChildren(this._children);
  11204. value = returnedPromise._result;
  11205. }
  11206. else {
  11207. value = returnedValue;
  11208. }
  11209. }
  11210. this._result = value;
  11211. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11212. var child = _a[_i];
  11213. child._resolve(value);
  11214. }
  11215. this._children.length = 0;
  11216. delete this._onFulfilled;
  11217. delete this._onRejected;
  11218. }
  11219. catch (e) {
  11220. this._reject(e, true);
  11221. }
  11222. };
  11223. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11224. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11225. this._state = PromiseStates.Rejected;
  11226. this._reason = reason;
  11227. if (this._onRejected && !onLocalThrow) {
  11228. try {
  11229. this._onRejected(reason);
  11230. this._rejectWasConsumed = true;
  11231. }
  11232. catch (e) {
  11233. reason = e;
  11234. }
  11235. }
  11236. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11237. var child = _a[_i];
  11238. if (this._rejectWasConsumed) {
  11239. child._resolve(null);
  11240. }
  11241. else {
  11242. child._reject(reason);
  11243. }
  11244. }
  11245. this._children.length = 0;
  11246. delete this._onFulfilled;
  11247. delete this._onRejected;
  11248. };
  11249. InternalPromise.resolve = function (value) {
  11250. var newPromise = new InternalPromise();
  11251. newPromise._resolve(value);
  11252. return newPromise;
  11253. };
  11254. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11255. promise.then(function (value) {
  11256. agregator.results[index] = value;
  11257. agregator.count++;
  11258. if (agregator.count === agregator.target) {
  11259. agregator.rootPromise._resolve(agregator.results);
  11260. }
  11261. return null;
  11262. }, function (reason) {
  11263. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11264. agregator.rootPromise._reject(reason);
  11265. }
  11266. });
  11267. };
  11268. InternalPromise.all = function (promises) {
  11269. var newPromise = new InternalPromise();
  11270. var agregator = new FulFillmentAgregator();
  11271. agregator.target = promises.length;
  11272. agregator.rootPromise = newPromise;
  11273. if (promises.length) {
  11274. for (var index = 0; index < promises.length; index++) {
  11275. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11276. }
  11277. }
  11278. else {
  11279. newPromise._resolve([]);
  11280. }
  11281. return newPromise;
  11282. };
  11283. InternalPromise.race = function (promises) {
  11284. var newPromise = new InternalPromise();
  11285. if (promises.length) {
  11286. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11287. var promise = promises_1[_i];
  11288. promise.then(function (value) {
  11289. if (newPromise) {
  11290. newPromise._resolve(value);
  11291. newPromise = null;
  11292. }
  11293. return null;
  11294. }, function (reason) {
  11295. if (newPromise) {
  11296. newPromise._reject(reason);
  11297. newPromise = null;
  11298. }
  11299. });
  11300. }
  11301. }
  11302. return newPromise;
  11303. };
  11304. return InternalPromise;
  11305. }());
  11306. /**
  11307. * Helper class that provides a small promise polyfill
  11308. */
  11309. var PromisePolyfill = /** @class */ (function () {
  11310. function PromisePolyfill() {
  11311. }
  11312. /**
  11313. * Static function used to check if the polyfill is required
  11314. * If this is the case then the function will inject the polyfill to window.Promise
  11315. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11316. */
  11317. PromisePolyfill.Apply = function (force) {
  11318. if (force === void 0) { force = false; }
  11319. if (force || typeof Promise === 'undefined') {
  11320. var root = window;
  11321. root.Promise = InternalPromise;
  11322. }
  11323. };
  11324. return PromisePolyfill;
  11325. }());
  11326. BABYLON.PromisePolyfill = PromisePolyfill;
  11327. })(BABYLON || (BABYLON = {}));
  11328. //# sourceMappingURL=babylon.promise.js.map
  11329. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11330. var BABYLON;
  11331. (function (BABYLON) {
  11332. /**
  11333. * Helper class to push actions to a pool of workers.
  11334. */
  11335. var WorkerPool = /** @class */ (function () {
  11336. /**
  11337. * Constructor
  11338. * @param workers Array of workers to use for actions
  11339. */
  11340. function WorkerPool(workers) {
  11341. this._pendingActions = new Array();
  11342. this._workerInfos = workers.map(function (worker) { return ({
  11343. worker: worker,
  11344. active: false
  11345. }); });
  11346. }
  11347. /**
  11348. * Terminates all workers and clears any pending actions.
  11349. */
  11350. WorkerPool.prototype.dispose = function () {
  11351. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11352. var workerInfo = _a[_i];
  11353. workerInfo.worker.terminate();
  11354. }
  11355. delete this._workerInfos;
  11356. delete this._pendingActions;
  11357. };
  11358. /**
  11359. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11360. * pended until a worker has completed its action.
  11361. * @param action The action to perform. Call onComplete when the action is complete.
  11362. */
  11363. WorkerPool.prototype.push = function (action) {
  11364. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11365. var workerInfo = _a[_i];
  11366. if (!workerInfo.active) {
  11367. this._execute(workerInfo, action);
  11368. return;
  11369. }
  11370. }
  11371. this._pendingActions.push(action);
  11372. };
  11373. WorkerPool.prototype._execute = function (workerInfo, action) {
  11374. var _this = this;
  11375. workerInfo.active = true;
  11376. action(workerInfo.worker, function () {
  11377. workerInfo.active = false;
  11378. var nextAction = _this._pendingActions.shift();
  11379. if (nextAction) {
  11380. _this._execute(workerInfo, nextAction);
  11381. }
  11382. });
  11383. };
  11384. return WorkerPool;
  11385. }());
  11386. BABYLON.WorkerPool = WorkerPool;
  11387. })(BABYLON || (BABYLON = {}));
  11388. //# sourceMappingURL=babylon.workerPool.js.map
  11389. var BABYLON;
  11390. (function (BABYLON) {
  11391. /**
  11392. * @hidden
  11393. **/
  11394. var _AlphaState = /** @class */ (function () {
  11395. /**
  11396. * Initializes the state.
  11397. */
  11398. function _AlphaState() {
  11399. this._isAlphaBlendDirty = false;
  11400. this._isBlendFunctionParametersDirty = false;
  11401. this._isBlendEquationParametersDirty = false;
  11402. this._isBlendConstantsDirty = false;
  11403. this._alphaBlend = false;
  11404. this._blendFunctionParameters = new Array(4);
  11405. this._blendEquationParameters = new Array(2);
  11406. this._blendConstants = new Array(4);
  11407. this.reset();
  11408. }
  11409. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11410. get: function () {
  11411. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11412. },
  11413. enumerable: true,
  11414. configurable: true
  11415. });
  11416. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11417. get: function () {
  11418. return this._alphaBlend;
  11419. },
  11420. set: function (value) {
  11421. if (this._alphaBlend === value) {
  11422. return;
  11423. }
  11424. this._alphaBlend = value;
  11425. this._isAlphaBlendDirty = true;
  11426. },
  11427. enumerable: true,
  11428. configurable: true
  11429. });
  11430. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11431. if (this._blendConstants[0] === r &&
  11432. this._blendConstants[1] === g &&
  11433. this._blendConstants[2] === b &&
  11434. this._blendConstants[3] === a) {
  11435. return;
  11436. }
  11437. this._blendConstants[0] = r;
  11438. this._blendConstants[1] = g;
  11439. this._blendConstants[2] = b;
  11440. this._blendConstants[3] = a;
  11441. this._isBlendConstantsDirty = true;
  11442. };
  11443. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11444. if (this._blendFunctionParameters[0] === value0 &&
  11445. this._blendFunctionParameters[1] === value1 &&
  11446. this._blendFunctionParameters[2] === value2 &&
  11447. this._blendFunctionParameters[3] === value3) {
  11448. return;
  11449. }
  11450. this._blendFunctionParameters[0] = value0;
  11451. this._blendFunctionParameters[1] = value1;
  11452. this._blendFunctionParameters[2] = value2;
  11453. this._blendFunctionParameters[3] = value3;
  11454. this._isBlendFunctionParametersDirty = true;
  11455. };
  11456. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11457. if (this._blendEquationParameters[0] === rgb &&
  11458. this._blendEquationParameters[1] === alpha) {
  11459. return;
  11460. }
  11461. this._blendEquationParameters[0] = rgb;
  11462. this._blendEquationParameters[1] = alpha;
  11463. this._isBlendEquationParametersDirty = true;
  11464. };
  11465. _AlphaState.prototype.reset = function () {
  11466. this._alphaBlend = false;
  11467. this._blendFunctionParameters[0] = null;
  11468. this._blendFunctionParameters[1] = null;
  11469. this._blendFunctionParameters[2] = null;
  11470. this._blendFunctionParameters[3] = null;
  11471. this._blendEquationParameters[0] = null;
  11472. this._blendEquationParameters[1] = null;
  11473. this._blendConstants[0] = null;
  11474. this._blendConstants[1] = null;
  11475. this._blendConstants[2] = null;
  11476. this._blendConstants[3] = null;
  11477. this._isAlphaBlendDirty = true;
  11478. this._isBlendFunctionParametersDirty = false;
  11479. this._isBlendEquationParametersDirty = false;
  11480. this._isBlendConstantsDirty = false;
  11481. };
  11482. _AlphaState.prototype.apply = function (gl) {
  11483. if (!this.isDirty) {
  11484. return;
  11485. }
  11486. // Alpha blend
  11487. if (this._isAlphaBlendDirty) {
  11488. if (this._alphaBlend) {
  11489. gl.enable(gl.BLEND);
  11490. }
  11491. else {
  11492. gl.disable(gl.BLEND);
  11493. }
  11494. this._isAlphaBlendDirty = false;
  11495. }
  11496. // Alpha function
  11497. if (this._isBlendFunctionParametersDirty) {
  11498. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11499. this._isBlendFunctionParametersDirty = false;
  11500. }
  11501. // Alpha equation
  11502. if (this._isBlendEquationParametersDirty) {
  11503. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11504. this._isBlendEquationParametersDirty = false;
  11505. }
  11506. // Constants
  11507. if (this._isBlendConstantsDirty) {
  11508. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11509. this._isBlendConstantsDirty = false;
  11510. }
  11511. };
  11512. return _AlphaState;
  11513. }());
  11514. BABYLON._AlphaState = _AlphaState;
  11515. })(BABYLON || (BABYLON = {}));
  11516. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11517. var BABYLON;
  11518. (function (BABYLON) {
  11519. /**
  11520. * @hidden
  11521. **/
  11522. var _DepthCullingState = /** @class */ (function () {
  11523. /**
  11524. * Initializes the state.
  11525. */
  11526. function _DepthCullingState() {
  11527. this._isDepthTestDirty = false;
  11528. this._isDepthMaskDirty = false;
  11529. this._isDepthFuncDirty = false;
  11530. this._isCullFaceDirty = false;
  11531. this._isCullDirty = false;
  11532. this._isZOffsetDirty = false;
  11533. this._isFrontFaceDirty = false;
  11534. this.reset();
  11535. }
  11536. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11537. get: function () {
  11538. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11539. },
  11540. enumerable: true,
  11541. configurable: true
  11542. });
  11543. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11544. get: function () {
  11545. return this._zOffset;
  11546. },
  11547. set: function (value) {
  11548. if (this._zOffset === value) {
  11549. return;
  11550. }
  11551. this._zOffset = value;
  11552. this._isZOffsetDirty = true;
  11553. },
  11554. enumerable: true,
  11555. configurable: true
  11556. });
  11557. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11558. get: function () {
  11559. return this._cullFace;
  11560. },
  11561. set: function (value) {
  11562. if (this._cullFace === value) {
  11563. return;
  11564. }
  11565. this._cullFace = value;
  11566. this._isCullFaceDirty = true;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11572. get: function () {
  11573. return this._cull;
  11574. },
  11575. set: function (value) {
  11576. if (this._cull === value) {
  11577. return;
  11578. }
  11579. this._cull = value;
  11580. this._isCullDirty = true;
  11581. },
  11582. enumerable: true,
  11583. configurable: true
  11584. });
  11585. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11586. get: function () {
  11587. return this._depthFunc;
  11588. },
  11589. set: function (value) {
  11590. if (this._depthFunc === value) {
  11591. return;
  11592. }
  11593. this._depthFunc = value;
  11594. this._isDepthFuncDirty = true;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11600. get: function () {
  11601. return this._depthMask;
  11602. },
  11603. set: function (value) {
  11604. if (this._depthMask === value) {
  11605. return;
  11606. }
  11607. this._depthMask = value;
  11608. this._isDepthMaskDirty = true;
  11609. },
  11610. enumerable: true,
  11611. configurable: true
  11612. });
  11613. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11614. get: function () {
  11615. return this._depthTest;
  11616. },
  11617. set: function (value) {
  11618. if (this._depthTest === value) {
  11619. return;
  11620. }
  11621. this._depthTest = value;
  11622. this._isDepthTestDirty = true;
  11623. },
  11624. enumerable: true,
  11625. configurable: true
  11626. });
  11627. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11628. get: function () {
  11629. return this._frontFace;
  11630. },
  11631. set: function (value) {
  11632. if (this._frontFace === value) {
  11633. return;
  11634. }
  11635. this._frontFace = value;
  11636. this._isFrontFaceDirty = true;
  11637. },
  11638. enumerable: true,
  11639. configurable: true
  11640. });
  11641. _DepthCullingState.prototype.reset = function () {
  11642. this._depthMask = true;
  11643. this._depthTest = true;
  11644. this._depthFunc = null;
  11645. this._cullFace = null;
  11646. this._cull = null;
  11647. this._zOffset = 0;
  11648. this._frontFace = null;
  11649. this._isDepthTestDirty = true;
  11650. this._isDepthMaskDirty = true;
  11651. this._isDepthFuncDirty = false;
  11652. this._isCullFaceDirty = false;
  11653. this._isCullDirty = false;
  11654. this._isZOffsetDirty = false;
  11655. this._isFrontFaceDirty = false;
  11656. };
  11657. _DepthCullingState.prototype.apply = function (gl) {
  11658. if (!this.isDirty) {
  11659. return;
  11660. }
  11661. // Cull
  11662. if (this._isCullDirty) {
  11663. if (this.cull) {
  11664. gl.enable(gl.CULL_FACE);
  11665. }
  11666. else {
  11667. gl.disable(gl.CULL_FACE);
  11668. }
  11669. this._isCullDirty = false;
  11670. }
  11671. // Cull face
  11672. if (this._isCullFaceDirty) {
  11673. gl.cullFace(this.cullFace);
  11674. this._isCullFaceDirty = false;
  11675. }
  11676. // Depth mask
  11677. if (this._isDepthMaskDirty) {
  11678. gl.depthMask(this.depthMask);
  11679. this._isDepthMaskDirty = false;
  11680. }
  11681. // Depth test
  11682. if (this._isDepthTestDirty) {
  11683. if (this.depthTest) {
  11684. gl.enable(gl.DEPTH_TEST);
  11685. }
  11686. else {
  11687. gl.disable(gl.DEPTH_TEST);
  11688. }
  11689. this._isDepthTestDirty = false;
  11690. }
  11691. // Depth func
  11692. if (this._isDepthFuncDirty) {
  11693. gl.depthFunc(this.depthFunc);
  11694. this._isDepthFuncDirty = false;
  11695. }
  11696. // zOffset
  11697. if (this._isZOffsetDirty) {
  11698. if (this.zOffset) {
  11699. gl.enable(gl.POLYGON_OFFSET_FILL);
  11700. gl.polygonOffset(this.zOffset, 0);
  11701. }
  11702. else {
  11703. gl.disable(gl.POLYGON_OFFSET_FILL);
  11704. }
  11705. this._isZOffsetDirty = false;
  11706. }
  11707. // Front face
  11708. if (this._isFrontFaceDirty) {
  11709. gl.frontFace(this.frontFace);
  11710. this._isFrontFaceDirty = false;
  11711. }
  11712. };
  11713. return _DepthCullingState;
  11714. }());
  11715. BABYLON._DepthCullingState = _DepthCullingState;
  11716. })(BABYLON || (BABYLON = {}));
  11717. //# sourceMappingURL=babylon.depthCullingState.js.map
  11718. var BABYLON;
  11719. (function (BABYLON) {
  11720. /**
  11721. * @hidden
  11722. **/
  11723. var _StencilState = /** @class */ (function () {
  11724. function _StencilState() {
  11725. this._isStencilTestDirty = false;
  11726. this._isStencilMaskDirty = false;
  11727. this._isStencilFuncDirty = false;
  11728. this._isStencilOpDirty = false;
  11729. this.reset();
  11730. }
  11731. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11732. get: function () {
  11733. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11739. get: function () {
  11740. return this._stencilFunc;
  11741. },
  11742. set: function (value) {
  11743. if (this._stencilFunc === value) {
  11744. return;
  11745. }
  11746. this._stencilFunc = value;
  11747. this._isStencilFuncDirty = true;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11753. get: function () {
  11754. return this._stencilFuncRef;
  11755. },
  11756. set: function (value) {
  11757. if (this._stencilFuncRef === value) {
  11758. return;
  11759. }
  11760. this._stencilFuncRef = value;
  11761. this._isStencilFuncDirty = true;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11767. get: function () {
  11768. return this._stencilFuncMask;
  11769. },
  11770. set: function (value) {
  11771. if (this._stencilFuncMask === value) {
  11772. return;
  11773. }
  11774. this._stencilFuncMask = value;
  11775. this._isStencilFuncDirty = true;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11781. get: function () {
  11782. return this._stencilOpStencilFail;
  11783. },
  11784. set: function (value) {
  11785. if (this._stencilOpStencilFail === value) {
  11786. return;
  11787. }
  11788. this._stencilOpStencilFail = value;
  11789. this._isStencilOpDirty = true;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11795. get: function () {
  11796. return this._stencilOpDepthFail;
  11797. },
  11798. set: function (value) {
  11799. if (this._stencilOpDepthFail === value) {
  11800. return;
  11801. }
  11802. this._stencilOpDepthFail = value;
  11803. this._isStencilOpDirty = true;
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11809. get: function () {
  11810. return this._stencilOpStencilDepthPass;
  11811. },
  11812. set: function (value) {
  11813. if (this._stencilOpStencilDepthPass === value) {
  11814. return;
  11815. }
  11816. this._stencilOpStencilDepthPass = value;
  11817. this._isStencilOpDirty = true;
  11818. },
  11819. enumerable: true,
  11820. configurable: true
  11821. });
  11822. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11823. get: function () {
  11824. return this._stencilMask;
  11825. },
  11826. set: function (value) {
  11827. if (this._stencilMask === value) {
  11828. return;
  11829. }
  11830. this._stencilMask = value;
  11831. this._isStencilMaskDirty = true;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11837. get: function () {
  11838. return this._stencilTest;
  11839. },
  11840. set: function (value) {
  11841. if (this._stencilTest === value) {
  11842. return;
  11843. }
  11844. this._stencilTest = value;
  11845. this._isStencilTestDirty = true;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. _StencilState.prototype.reset = function () {
  11851. this._stencilTest = false;
  11852. this._stencilMask = 0xFF;
  11853. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11854. this._stencilFuncRef = 1;
  11855. this._stencilFuncMask = 0xFF;
  11856. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11857. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11858. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11859. this._isStencilTestDirty = true;
  11860. this._isStencilMaskDirty = true;
  11861. this._isStencilFuncDirty = true;
  11862. this._isStencilOpDirty = true;
  11863. };
  11864. _StencilState.prototype.apply = function (gl) {
  11865. if (!this.isDirty) {
  11866. return;
  11867. }
  11868. // Stencil test
  11869. if (this._isStencilTestDirty) {
  11870. if (this.stencilTest) {
  11871. gl.enable(gl.STENCIL_TEST);
  11872. }
  11873. else {
  11874. gl.disable(gl.STENCIL_TEST);
  11875. }
  11876. this._isStencilTestDirty = false;
  11877. }
  11878. // Stencil mask
  11879. if (this._isStencilMaskDirty) {
  11880. gl.stencilMask(this.stencilMask);
  11881. this._isStencilMaskDirty = false;
  11882. }
  11883. // Stencil func
  11884. if (this._isStencilFuncDirty) {
  11885. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11886. this._isStencilFuncDirty = false;
  11887. }
  11888. // Stencil op
  11889. if (this._isStencilOpDirty) {
  11890. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11891. this._isStencilOpDirty = false;
  11892. }
  11893. };
  11894. return _StencilState;
  11895. }());
  11896. BABYLON._StencilState = _StencilState;
  11897. })(BABYLON || (BABYLON = {}));
  11898. //# sourceMappingURL=babylon.stencilState.js.map
  11899. var __assign = (this && this.__assign) || function () {
  11900. __assign = Object.assign || function(t) {
  11901. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11902. s = arguments[i];
  11903. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11904. t[p] = s[p];
  11905. }
  11906. return t;
  11907. };
  11908. return __assign.apply(this, arguments);
  11909. };
  11910. var BABYLON;
  11911. (function (BABYLON) {
  11912. /**
  11913. * Keeps track of all the buffer info used in engine.
  11914. */
  11915. var BufferPointer = /** @class */ (function () {
  11916. function BufferPointer() {
  11917. }
  11918. return BufferPointer;
  11919. }());
  11920. /**
  11921. * Interface for attribute information associated with buffer instanciation
  11922. */
  11923. var InstancingAttributeInfo = /** @class */ (function () {
  11924. function InstancingAttributeInfo() {
  11925. }
  11926. return InstancingAttributeInfo;
  11927. }());
  11928. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11929. /**
  11930. * Define options used to create a render target texture
  11931. */
  11932. var RenderTargetCreationOptions = /** @class */ (function () {
  11933. function RenderTargetCreationOptions() {
  11934. }
  11935. return RenderTargetCreationOptions;
  11936. }());
  11937. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11938. /**
  11939. * Define options used to create a depth texture
  11940. */
  11941. var DepthTextureCreationOptions = /** @class */ (function () {
  11942. function DepthTextureCreationOptions() {
  11943. }
  11944. return DepthTextureCreationOptions;
  11945. }());
  11946. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11947. /**
  11948. * Class used to describe the capabilities of the engine relatively to the current browser
  11949. */
  11950. var EngineCapabilities = /** @class */ (function () {
  11951. function EngineCapabilities() {
  11952. }
  11953. return EngineCapabilities;
  11954. }());
  11955. BABYLON.EngineCapabilities = EngineCapabilities;
  11956. /**
  11957. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11958. */
  11959. var Engine = /** @class */ (function () {
  11960. /**
  11961. * Creates a new engine
  11962. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11963. * @param antialias defines enable antialiasing (default: false)
  11964. * @param options defines further options to be sent to the getContext() function
  11965. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11966. */
  11967. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11968. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11969. var _this = this;
  11970. // Public members
  11971. /**
  11972. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11973. */
  11974. this.forcePOTTextures = false;
  11975. /**
  11976. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11977. */
  11978. this.isFullscreen = false;
  11979. /**
  11980. * Gets a boolean indicating if the pointer is currently locked
  11981. */
  11982. this.isPointerLock = false;
  11983. /**
  11984. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11985. */
  11986. this.cullBackFaces = true;
  11987. /**
  11988. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11989. */
  11990. this.renderEvenInBackground = true;
  11991. /**
  11992. * Gets or sets a boolean indicating that cache can be kept between frames
  11993. */
  11994. this.preventCacheWipeBetweenFrames = false;
  11995. /**
  11996. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11997. **/
  11998. this.enableOfflineSupport = false;
  11999. /**
  12000. * 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)
  12001. **/
  12002. this.disableManifestCheck = false;
  12003. /**
  12004. * Gets the list of created scenes
  12005. */
  12006. this.scenes = new Array();
  12007. /**
  12008. * Gets the list of created postprocesses
  12009. */
  12010. this.postProcesses = new Array();
  12011. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12012. this.validateShaderPrograms = false;
  12013. // Observables
  12014. /**
  12015. * Observable event triggered each time the rendering canvas is resized
  12016. */
  12017. this.onResizeObservable = new BABYLON.Observable();
  12018. /**
  12019. * Observable event triggered each time the canvas loses focus
  12020. */
  12021. this.onCanvasBlurObservable = new BABYLON.Observable();
  12022. /**
  12023. * Observable event triggered each time the canvas gains focus
  12024. */
  12025. this.onCanvasFocusObservable = new BABYLON.Observable();
  12026. /**
  12027. * Observable event triggered each time the canvas receives pointerout event
  12028. */
  12029. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12030. /**
  12031. * Observable event triggered before each texture is initialized
  12032. */
  12033. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12034. //WebVR
  12035. this._vrDisplay = undefined;
  12036. this._vrSupported = false;
  12037. this._vrExclusivePointerMode = false;
  12038. // Uniform buffers list
  12039. /**
  12040. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12041. */
  12042. this.disableUniformBuffers = false;
  12043. /** @hidden */
  12044. this._uniformBuffers = new Array();
  12045. // Observables
  12046. /**
  12047. * Observable raised when the engine begins a new frame
  12048. */
  12049. this.onBeginFrameObservable = new BABYLON.Observable();
  12050. /**
  12051. * Observable raised when the engine ends the current frame
  12052. */
  12053. this.onEndFrameObservable = new BABYLON.Observable();
  12054. /**
  12055. * Observable raised when the engine is about to compile a shader
  12056. */
  12057. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12058. /**
  12059. * Observable raised when the engine has jsut compiled a shader
  12060. */
  12061. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12062. this._windowIsBackground = false;
  12063. this._webGLVersion = 1.0;
  12064. /** @hidden */
  12065. this._badOS = false;
  12066. /** @hidden */
  12067. this._badDesktopOS = false;
  12068. /**
  12069. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12070. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12071. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12072. */
  12073. this.disableTextureBindingOptimization = false;
  12074. /**
  12075. * Observable signaled when VR display mode changes
  12076. */
  12077. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12078. /**
  12079. * Observable signaled when VR request present is complete
  12080. */
  12081. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12082. /**
  12083. * Observable signaled when VR request present starts
  12084. */
  12085. this.onVRRequestPresentStart = new BABYLON.Observable();
  12086. this._colorWrite = true;
  12087. /** @hidden */
  12088. this._drawCalls = new BABYLON.PerfCounter();
  12089. /** @hidden */
  12090. this._textureCollisions = new BABYLON.PerfCounter();
  12091. this._renderingQueueLaunched = false;
  12092. this._activeRenderLoops = new Array();
  12093. // Deterministic lockstepMaxSteps
  12094. this._deterministicLockstep = false;
  12095. this._lockstepMaxSteps = 4;
  12096. // Lost context
  12097. /**
  12098. * Observable signaled when a context lost event is raised
  12099. */
  12100. this.onContextLostObservable = new BABYLON.Observable();
  12101. /**
  12102. * Observable signaled when a context restored event is raised
  12103. */
  12104. this.onContextRestoredObservable = new BABYLON.Observable();
  12105. this._contextWasLost = false;
  12106. this._doNotHandleContextLost = false;
  12107. // FPS
  12108. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12109. this._fps = 60;
  12110. this._deltaTime = 0;
  12111. /**
  12112. * Turn this value on if you want to pause FPS computation when in background
  12113. */
  12114. this.disablePerformanceMonitorInBackground = false;
  12115. // States
  12116. /** @hidden */
  12117. this._depthCullingState = new BABYLON._DepthCullingState();
  12118. /** @hidden */
  12119. this._stencilState = new BABYLON._StencilState();
  12120. /** @hidden */
  12121. this._alphaState = new BABYLON._AlphaState();
  12122. /** @hidden */
  12123. this._alphaMode = Engine.ALPHA_DISABLE;
  12124. // Cache
  12125. this._internalTexturesCache = new Array();
  12126. /** @hidden */
  12127. this._activeChannel = 0;
  12128. this._currentTextureChannel = -1;
  12129. /** @hidden */
  12130. this._boundTexturesCache = {};
  12131. this._compiledEffects = {};
  12132. this._vertexAttribArraysEnabled = [];
  12133. this._uintIndicesCurrentlySet = false;
  12134. this._currentBoundBuffer = new Array();
  12135. /** @hidden */
  12136. this._currentFramebuffer = null;
  12137. this._currentBufferPointers = new Array();
  12138. this._currentInstanceLocations = new Array();
  12139. this._currentInstanceBuffers = new Array();
  12140. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12141. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12142. this._vaoRecordInProgress = false;
  12143. this._mustWipeVertexAttributes = false;
  12144. this._nextFreeTextureSlots = new Array();
  12145. this._maxSimultaneousTextures = 0;
  12146. this._activeRequests = new Array();
  12147. // Hardware supported Compressed Textures
  12148. this._texturesSupported = new Array();
  12149. /**
  12150. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12151. */
  12152. this.premultipliedAlpha = true;
  12153. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12154. this._onVRFullScreenTriggered = function () {
  12155. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12156. //get the old size before we change
  12157. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12158. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12159. //get the width and height, change the render size
  12160. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12161. _this.setHardwareScalingLevel(1);
  12162. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12163. }
  12164. else {
  12165. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12166. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12167. }
  12168. };
  12169. this._unpackFlipYCached = null;
  12170. /**
  12171. * In case you are sharing the context with other applications, it might
  12172. * be interested to not cache the unpack flip y state to ensure a consistent
  12173. * value would be set.
  12174. */
  12175. this.enableUnpackFlipYCached = true;
  12176. this._boundUniforms = {};
  12177. // Register promises
  12178. BABYLON.PromisePolyfill.Apply();
  12179. var canvas = null;
  12180. Engine.Instances.push(this);
  12181. if (!canvasOrContext) {
  12182. return;
  12183. }
  12184. options = options || {};
  12185. if (canvasOrContext.getContext) {
  12186. canvas = canvasOrContext;
  12187. this._renderingCanvas = canvas;
  12188. if (antialias != null) {
  12189. options.antialias = antialias;
  12190. }
  12191. if (options.deterministicLockstep === undefined) {
  12192. options.deterministicLockstep = false;
  12193. }
  12194. if (options.lockstepMaxSteps === undefined) {
  12195. options.lockstepMaxSteps = 4;
  12196. }
  12197. if (options.preserveDrawingBuffer === undefined) {
  12198. options.preserveDrawingBuffer = false;
  12199. }
  12200. if (options.audioEngine === undefined) {
  12201. options.audioEngine = true;
  12202. }
  12203. if (options.stencil === undefined) {
  12204. options.stencil = true;
  12205. }
  12206. if (options.premultipliedAlpha === false) {
  12207. this.premultipliedAlpha = false;
  12208. }
  12209. this._deterministicLockstep = options.deterministicLockstep;
  12210. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12211. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12212. // Exceptions
  12213. if (navigator && navigator.userAgent) {
  12214. var ua = navigator.userAgent;
  12215. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12216. var exception = _a[_i];
  12217. var key = exception.key;
  12218. var targets = exception.targets;
  12219. if (ua.indexOf(key) > -1) {
  12220. if (exception.capture && exception.captureConstraint) {
  12221. var capture = exception.capture;
  12222. var constraint = exception.captureConstraint;
  12223. var regex = new RegExp(capture);
  12224. var matches = regex.exec(ua);
  12225. if (matches && matches.length > 0) {
  12226. var capturedValue = parseInt(matches[matches.length - 1]);
  12227. if (capturedValue >= constraint) {
  12228. continue;
  12229. }
  12230. }
  12231. }
  12232. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12233. var target = targets_1[_b];
  12234. switch (target) {
  12235. case "uniformBuffer":
  12236. this.disableUniformBuffers = true;
  12237. break;
  12238. case "textureBindingOptimization":
  12239. this.disableTextureBindingOptimization = true;
  12240. break;
  12241. }
  12242. }
  12243. }
  12244. }
  12245. }
  12246. // GL
  12247. if (!options.disableWebGL2Support) {
  12248. try {
  12249. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12250. if (this._gl) {
  12251. this._webGLVersion = 2.0;
  12252. }
  12253. }
  12254. catch (e) {
  12255. // Do nothing
  12256. }
  12257. }
  12258. if (!this._gl) {
  12259. if (!canvas) {
  12260. throw new Error("The provided canvas is null or undefined.");
  12261. }
  12262. try {
  12263. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12264. }
  12265. catch (e) {
  12266. throw new Error("WebGL not supported");
  12267. }
  12268. }
  12269. if (!this._gl) {
  12270. throw new Error("WebGL not supported");
  12271. }
  12272. this._onCanvasFocus = function () {
  12273. _this.onCanvasFocusObservable.notifyObservers(_this);
  12274. };
  12275. this._onCanvasBlur = function () {
  12276. _this.onCanvasBlurObservable.notifyObservers(_this);
  12277. };
  12278. canvas.addEventListener("focus", this._onCanvasFocus);
  12279. canvas.addEventListener("blur", this._onCanvasBlur);
  12280. this._onBlur = function () {
  12281. if (_this.disablePerformanceMonitorInBackground) {
  12282. _this._performanceMonitor.disable();
  12283. }
  12284. _this._windowIsBackground = true;
  12285. };
  12286. this._onFocus = function () {
  12287. if (_this.disablePerformanceMonitorInBackground) {
  12288. _this._performanceMonitor.enable();
  12289. }
  12290. _this._windowIsBackground = false;
  12291. };
  12292. this._onCanvasPointerOut = function (ev) {
  12293. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12294. };
  12295. window.addEventListener("blur", this._onBlur);
  12296. window.addEventListener("focus", this._onFocus);
  12297. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12298. // Context lost
  12299. if (!this._doNotHandleContextLost) {
  12300. this._onContextLost = function (evt) {
  12301. evt.preventDefault();
  12302. _this._contextWasLost = true;
  12303. BABYLON.Tools.Warn("WebGL context lost.");
  12304. _this.onContextLostObservable.notifyObservers(_this);
  12305. };
  12306. this._onContextRestored = function (evt) {
  12307. // Adding a timeout to avoid race condition at browser level
  12308. setTimeout(function () {
  12309. // Rebuild gl context
  12310. _this._initGLContext();
  12311. // Rebuild effects
  12312. _this._rebuildEffects();
  12313. // Rebuild textures
  12314. _this._rebuildInternalTextures();
  12315. // Rebuild buffers
  12316. _this._rebuildBuffers();
  12317. // Cache
  12318. _this.wipeCaches(true);
  12319. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12320. _this.onContextRestoredObservable.notifyObservers(_this);
  12321. _this._contextWasLost = false;
  12322. }, 0);
  12323. };
  12324. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12325. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12326. }
  12327. }
  12328. else {
  12329. this._gl = canvasOrContext;
  12330. this._renderingCanvas = this._gl.canvas;
  12331. if (this._gl.renderbufferStorageMultisample) {
  12332. this._webGLVersion = 2.0;
  12333. }
  12334. options.stencil = this._gl.getContextAttributes().stencil;
  12335. }
  12336. // Viewport
  12337. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12338. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12339. this.resize();
  12340. this._isStencilEnable = options.stencil ? true : false;
  12341. this._initGLContext();
  12342. if (canvas) {
  12343. // Fullscreen
  12344. this._onFullscreenChange = function () {
  12345. if (document.fullscreen !== undefined) {
  12346. _this.isFullscreen = document.fullscreen;
  12347. }
  12348. else if (document.mozFullScreen !== undefined) {
  12349. _this.isFullscreen = document.mozFullScreen;
  12350. }
  12351. else if (document.webkitIsFullScreen !== undefined) {
  12352. _this.isFullscreen = document.webkitIsFullScreen;
  12353. }
  12354. else if (document.msIsFullScreen !== undefined) {
  12355. _this.isFullscreen = document.msIsFullScreen;
  12356. }
  12357. // Pointer lock
  12358. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12359. canvas.requestPointerLock = canvas.requestPointerLock ||
  12360. canvas.msRequestPointerLock ||
  12361. canvas.mozRequestPointerLock ||
  12362. canvas.webkitRequestPointerLock;
  12363. if (canvas.requestPointerLock) {
  12364. canvas.requestPointerLock();
  12365. }
  12366. }
  12367. };
  12368. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12369. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12370. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12371. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12372. // Pointer lock
  12373. this._onPointerLockChange = function () {
  12374. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12375. document.webkitPointerLockElement === canvas ||
  12376. document.msPointerLockElement === canvas ||
  12377. document.pointerLockElement === canvas);
  12378. };
  12379. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12380. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12381. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12382. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12383. this._onVRDisplayPointerRestricted = function () {
  12384. if (canvas) {
  12385. canvas.requestPointerLock();
  12386. }
  12387. };
  12388. this._onVRDisplayPointerUnrestricted = function () {
  12389. document.exitPointerLock();
  12390. };
  12391. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12392. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12393. }
  12394. // Create Audio Engine if needed.
  12395. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12396. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12397. }
  12398. // Prepare buffer pointers
  12399. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12400. this._currentBufferPointers[i] = new BufferPointer();
  12401. }
  12402. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12403. // Load WebVR Devices
  12404. if (options.autoEnableWebVR) {
  12405. this.initWebVR();
  12406. }
  12407. // Detect if we are running on a faulty buggy OS.
  12408. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12409. // Detect if we are running on a faulty buggy desktop OS.
  12410. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12411. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12412. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12413. }
  12414. Object.defineProperty(Engine, "LastCreatedEngine", {
  12415. /**
  12416. * Gets the latest created engine
  12417. */
  12418. get: function () {
  12419. if (Engine.Instances.length === 0) {
  12420. return null;
  12421. }
  12422. return Engine.Instances[Engine.Instances.length - 1];
  12423. },
  12424. enumerable: true,
  12425. configurable: true
  12426. });
  12427. Object.defineProperty(Engine, "LastCreatedScene", {
  12428. /**
  12429. * Gets the latest created scene
  12430. */
  12431. get: function () {
  12432. var lastCreatedEngine = Engine.LastCreatedEngine;
  12433. if (!lastCreatedEngine) {
  12434. return null;
  12435. }
  12436. if (lastCreatedEngine.scenes.length === 0) {
  12437. return null;
  12438. }
  12439. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. /**
  12445. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12446. * @param flag defines which part of the materials must be marked as dirty
  12447. * @param predicate defines a predicate used to filter which materials should be affected
  12448. */
  12449. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12450. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12451. var engine = Engine.Instances[engineIndex];
  12452. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12453. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12454. }
  12455. }
  12456. };
  12457. Object.defineProperty(Engine, "Version", {
  12458. /**
  12459. * Returns the current version of the framework
  12460. */
  12461. get: function () {
  12462. return "3.3.0-rc.2";
  12463. },
  12464. enumerable: true,
  12465. configurable: true
  12466. });
  12467. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12468. /**
  12469. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12470. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12471. */
  12472. get: function () {
  12473. return this._vrExclusivePointerMode;
  12474. },
  12475. enumerable: true,
  12476. configurable: true
  12477. });
  12478. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12479. /**
  12480. * Gets a boolean indicating that the engine supports uniform buffers
  12481. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12482. */
  12483. get: function () {
  12484. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12490. /**
  12491. * Gets a boolean indicating that only power of 2 textures are supported
  12492. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12493. */
  12494. get: function () {
  12495. return this._webGLVersion < 2 || this.forcePOTTextures;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12501. /**
  12502. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12503. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12504. */
  12505. get: function () {
  12506. return this._doNotHandleContextLost;
  12507. },
  12508. set: function (value) {
  12509. this._doNotHandleContextLost = value;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12515. /**
  12516. * Gets the performance monitor attached to this engine
  12517. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12518. */
  12519. get: function () {
  12520. return this._performanceMonitor;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12526. /**
  12527. * Gets the list of texture formats supported
  12528. */
  12529. get: function () {
  12530. return this._texturesSupported;
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12536. /**
  12537. * Gets the list of texture formats in use
  12538. */
  12539. get: function () {
  12540. return this._textureFormatInUse;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. Object.defineProperty(Engine.prototype, "currentViewport", {
  12546. /**
  12547. * Gets the current viewport
  12548. */
  12549. get: function () {
  12550. return this._cachedViewport;
  12551. },
  12552. enumerable: true,
  12553. configurable: true
  12554. });
  12555. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12556. /**
  12557. * Gets the default empty texture
  12558. */
  12559. get: function () {
  12560. if (!this._emptyTexture) {
  12561. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12562. }
  12563. return this._emptyTexture;
  12564. },
  12565. enumerable: true,
  12566. configurable: true
  12567. });
  12568. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12569. /**
  12570. * Gets the default empty 3D texture
  12571. */
  12572. get: function () {
  12573. if (!this._emptyTexture3D) {
  12574. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12575. }
  12576. return this._emptyTexture3D;
  12577. },
  12578. enumerable: true,
  12579. configurable: true
  12580. });
  12581. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12582. /**
  12583. * Gets the default empty cube texture
  12584. */
  12585. get: function () {
  12586. if (!this._emptyCubeTexture) {
  12587. var faceData = new Uint8Array(4);
  12588. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12589. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12590. }
  12591. return this._emptyCubeTexture;
  12592. },
  12593. enumerable: true,
  12594. configurable: true
  12595. });
  12596. Engine.prototype._rebuildInternalTextures = function () {
  12597. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12598. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12599. var internalTexture = currentState_1[_i];
  12600. internalTexture._rebuild();
  12601. }
  12602. };
  12603. Engine.prototype._rebuildEffects = function () {
  12604. for (var key in this._compiledEffects) {
  12605. var effect = this._compiledEffects[key];
  12606. effect._prepareEffect();
  12607. }
  12608. BABYLON.Effect.ResetCache();
  12609. };
  12610. Engine.prototype._rebuildBuffers = function () {
  12611. // Index / Vertex
  12612. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12613. var scene = _a[_i];
  12614. scene.resetCachedMaterial();
  12615. scene._rebuildGeometries();
  12616. scene._rebuildTextures();
  12617. }
  12618. // Uniforms
  12619. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12620. var uniformBuffer = _c[_b];
  12621. uniformBuffer._rebuild();
  12622. }
  12623. };
  12624. Engine.prototype._initGLContext = function () {
  12625. // Caps
  12626. this._caps = new EngineCapabilities();
  12627. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12628. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12629. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12630. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12631. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12632. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12633. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12634. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12635. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12636. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12637. // Infos
  12638. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12639. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12640. if (rendererInfo != null) {
  12641. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12642. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12643. }
  12644. if (!this._glVendor) {
  12645. this._glVendor = "Unknown vendor";
  12646. }
  12647. if (!this._glRenderer) {
  12648. this._glRenderer = "Unknown renderer";
  12649. }
  12650. // Constants
  12651. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12652. if (this._gl.RGBA16F !== 0x881A) {
  12653. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12654. }
  12655. if (this._gl.RGBA32F !== 0x8814) {
  12656. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12657. }
  12658. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12659. this._gl.DEPTH24_STENCIL8 = 35056;
  12660. }
  12661. // Extensions
  12662. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12663. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12664. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12665. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12666. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12667. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12668. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12669. 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');
  12670. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12671. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12672. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12673. this._caps.highPrecisionShaderSupported = true;
  12674. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12675. if (this._caps.timerQuery) {
  12676. if (this._webGLVersion === 1) {
  12677. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12678. }
  12679. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12680. }
  12681. // Checks if some of the format renders first to allow the use of webgl inspector.
  12682. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12683. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12684. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12685. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12686. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12687. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12688. if (this._webGLVersion > 1) {
  12689. this._gl.HALF_FLOAT_OES = 0x140B;
  12690. }
  12691. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12692. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12693. // Draw buffers
  12694. if (this._webGLVersion > 1) {
  12695. this._caps.drawBuffersExtension = true;
  12696. }
  12697. else {
  12698. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12699. if (drawBuffersExtension !== null) {
  12700. this._caps.drawBuffersExtension = true;
  12701. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12702. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12703. for (var i = 0; i < 16; i++) {
  12704. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12705. }
  12706. }
  12707. else {
  12708. this._caps.drawBuffersExtension = false;
  12709. }
  12710. }
  12711. // Depth Texture
  12712. if (this._webGLVersion > 1) {
  12713. this._caps.depthTextureExtension = true;
  12714. }
  12715. else {
  12716. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12717. if (depthTextureExtension != null) {
  12718. this._caps.depthTextureExtension = true;
  12719. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12720. }
  12721. }
  12722. // Vertex array object
  12723. if (this._webGLVersion > 1) {
  12724. this._caps.vertexArrayObject = true;
  12725. }
  12726. else {
  12727. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12728. if (vertexArrayObjectExtension != null) {
  12729. this._caps.vertexArrayObject = true;
  12730. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12731. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12732. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12733. }
  12734. else {
  12735. this._caps.vertexArrayObject = false;
  12736. }
  12737. }
  12738. // Instances count
  12739. if (this._webGLVersion > 1) {
  12740. this._caps.instancedArrays = true;
  12741. }
  12742. else {
  12743. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12744. if (instanceExtension != null) {
  12745. this._caps.instancedArrays = true;
  12746. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12747. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12748. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12749. }
  12750. else {
  12751. this._caps.instancedArrays = false;
  12752. }
  12753. }
  12754. // Intelligently add supported compressed formats in order to check for.
  12755. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12756. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12757. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12758. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12759. if (this._caps.astc)
  12760. this.texturesSupported.push('-astc.ktx');
  12761. if (this._caps.s3tc)
  12762. this.texturesSupported.push('-dxt.ktx');
  12763. if (this._caps.pvrtc)
  12764. this.texturesSupported.push('-pvrtc.ktx');
  12765. if (this._caps.etc2)
  12766. this.texturesSupported.push('-etc2.ktx');
  12767. if (this._caps.etc1)
  12768. this.texturesSupported.push('-etc1.ktx');
  12769. if (this._gl.getShaderPrecisionFormat) {
  12770. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12771. if (highp) {
  12772. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12773. }
  12774. }
  12775. // Depth buffer
  12776. this.setDepthBuffer(true);
  12777. this.setDepthFunctionToLessOrEqual();
  12778. this.setDepthWrite(true);
  12779. // Texture maps
  12780. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12781. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12782. this._nextFreeTextureSlots.push(slot);
  12783. }
  12784. };
  12785. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12786. /**
  12787. * Gets version of the current webGL context
  12788. */
  12789. get: function () {
  12790. return this._webGLVersion;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12796. /**
  12797. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12798. */
  12799. get: function () {
  12800. return this._isStencilEnable;
  12801. },
  12802. enumerable: true,
  12803. configurable: true
  12804. });
  12805. Engine.prototype._prepareWorkingCanvas = function () {
  12806. if (this._workingCanvas) {
  12807. return;
  12808. }
  12809. this._workingCanvas = document.createElement("canvas");
  12810. var context = this._workingCanvas.getContext("2d");
  12811. if (context) {
  12812. this._workingContext = context;
  12813. }
  12814. };
  12815. /**
  12816. * Reset the texture cache to empty state
  12817. */
  12818. Engine.prototype.resetTextureCache = function () {
  12819. for (var key in this._boundTexturesCache) {
  12820. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12821. continue;
  12822. }
  12823. var boundTexture = this._boundTexturesCache[key];
  12824. if (boundTexture) {
  12825. this._removeDesignatedSlot(boundTexture);
  12826. }
  12827. this._boundTexturesCache[key] = null;
  12828. }
  12829. if (!this.disableTextureBindingOptimization) {
  12830. this._nextFreeTextureSlots = [];
  12831. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12832. this._nextFreeTextureSlots.push(slot);
  12833. }
  12834. }
  12835. this._currentTextureChannel = -1;
  12836. };
  12837. /**
  12838. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12839. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12840. * @returns true if engine is in deterministic lock step mode
  12841. */
  12842. Engine.prototype.isDeterministicLockStep = function () {
  12843. return this._deterministicLockstep;
  12844. };
  12845. /**
  12846. * Gets the max steps when engine is running in deterministic lock step
  12847. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12848. * @returns the max steps
  12849. */
  12850. Engine.prototype.getLockstepMaxSteps = function () {
  12851. return this._lockstepMaxSteps;
  12852. };
  12853. /**
  12854. * Gets an object containing information about the current webGL context
  12855. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12856. */
  12857. Engine.prototype.getGlInfo = function () {
  12858. return {
  12859. vendor: this._glVendor,
  12860. renderer: this._glRenderer,
  12861. version: this._glVersion
  12862. };
  12863. };
  12864. /**
  12865. * Gets current aspect ratio
  12866. * @param camera defines the camera to use to get the aspect ratio
  12867. * @param useScreen defines if screen size must be used (or the current render target if any)
  12868. * @returns a number defining the aspect ratio
  12869. */
  12870. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12871. if (useScreen === void 0) { useScreen = false; }
  12872. var viewport = camera.viewport;
  12873. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12874. };
  12875. /**
  12876. * Gets current screen aspect ratio
  12877. * @returns a number defining the aspect ratio
  12878. */
  12879. Engine.prototype.getScreenAspectRatio = function () {
  12880. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12881. };
  12882. /**
  12883. * Gets the current render width
  12884. * @param useScreen defines if screen size must be used (or the current render target if any)
  12885. * @returns a number defining the current render width
  12886. */
  12887. Engine.prototype.getRenderWidth = function (useScreen) {
  12888. if (useScreen === void 0) { useScreen = false; }
  12889. if (!useScreen && this._currentRenderTarget) {
  12890. return this._currentRenderTarget.width;
  12891. }
  12892. return this._gl.drawingBufferWidth;
  12893. };
  12894. /**
  12895. * Gets the current render height
  12896. * @param useScreen defines if screen size must be used (or the current render target if any)
  12897. * @returns a number defining the current render height
  12898. */
  12899. Engine.prototype.getRenderHeight = function (useScreen) {
  12900. if (useScreen === void 0) { useScreen = false; }
  12901. if (!useScreen && this._currentRenderTarget) {
  12902. return this._currentRenderTarget.height;
  12903. }
  12904. return this._gl.drawingBufferHeight;
  12905. };
  12906. /**
  12907. * Gets the HTML canvas attached with the current webGL context
  12908. * @returns a HTML canvas
  12909. */
  12910. Engine.prototype.getRenderingCanvas = function () {
  12911. return this._renderingCanvas;
  12912. };
  12913. /**
  12914. * Gets the client rect of the HTML canvas attached with the current webGL context
  12915. * @returns a client rectanglee
  12916. */
  12917. Engine.prototype.getRenderingCanvasClientRect = function () {
  12918. if (!this._renderingCanvas) {
  12919. return null;
  12920. }
  12921. return this._renderingCanvas.getBoundingClientRect();
  12922. };
  12923. /**
  12924. * Defines the hardware scaling level.
  12925. * By default the hardware scaling level is computed from the window device ratio.
  12926. * 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.
  12927. * @param level defines the level to use
  12928. */
  12929. Engine.prototype.setHardwareScalingLevel = function (level) {
  12930. this._hardwareScalingLevel = level;
  12931. this.resize();
  12932. };
  12933. /**
  12934. * Gets the current hardware scaling level.
  12935. * By default the hardware scaling level is computed from the window device ratio.
  12936. * 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.
  12937. * @returns a number indicating the current hardware scaling level
  12938. */
  12939. Engine.prototype.getHardwareScalingLevel = function () {
  12940. return this._hardwareScalingLevel;
  12941. };
  12942. /**
  12943. * Gets the list of loaded textures
  12944. * @returns an array containing all loaded textures
  12945. */
  12946. Engine.prototype.getLoadedTexturesCache = function () {
  12947. return this._internalTexturesCache;
  12948. };
  12949. /**
  12950. * Gets the object containing all engine capabilities
  12951. * @returns the EngineCapabilities object
  12952. */
  12953. Engine.prototype.getCaps = function () {
  12954. return this._caps;
  12955. };
  12956. Object.defineProperty(Engine.prototype, "drawCalls", {
  12957. /** @hidden */
  12958. get: function () {
  12959. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12960. return 0;
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12966. /** @hidden */
  12967. get: function () {
  12968. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12969. return null;
  12970. },
  12971. enumerable: true,
  12972. configurable: true
  12973. });
  12974. /**
  12975. * Gets the current depth function
  12976. * @returns a number defining the depth function
  12977. */
  12978. Engine.prototype.getDepthFunction = function () {
  12979. return this._depthCullingState.depthFunc;
  12980. };
  12981. /**
  12982. * Sets the current depth function
  12983. * @param depthFunc defines the function to use
  12984. */
  12985. Engine.prototype.setDepthFunction = function (depthFunc) {
  12986. this._depthCullingState.depthFunc = depthFunc;
  12987. };
  12988. /**
  12989. * Sets the current depth function to GREATER
  12990. */
  12991. Engine.prototype.setDepthFunctionToGreater = function () {
  12992. this._depthCullingState.depthFunc = this._gl.GREATER;
  12993. };
  12994. /**
  12995. * Sets the current depth function to GEQUAL
  12996. */
  12997. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12998. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12999. };
  13000. /**
  13001. * Sets the current depth function to LESS
  13002. */
  13003. Engine.prototype.setDepthFunctionToLess = function () {
  13004. this._depthCullingState.depthFunc = this._gl.LESS;
  13005. };
  13006. /**
  13007. * Sets the current depth function to LEQUAL
  13008. */
  13009. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13010. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13011. };
  13012. /**
  13013. * Gets a boolean indicating if stencil buffer is enabled
  13014. * @returns the current stencil buffer state
  13015. */
  13016. Engine.prototype.getStencilBuffer = function () {
  13017. return this._stencilState.stencilTest;
  13018. };
  13019. /**
  13020. * Enable or disable the stencil buffer
  13021. * @param enable defines if the stencil buffer must be enabled or disabled
  13022. */
  13023. Engine.prototype.setStencilBuffer = function (enable) {
  13024. this._stencilState.stencilTest = enable;
  13025. };
  13026. /**
  13027. * Gets the current stencil mask
  13028. * @returns a number defining the new stencil mask to use
  13029. */
  13030. Engine.prototype.getStencilMask = function () {
  13031. return this._stencilState.stencilMask;
  13032. };
  13033. /**
  13034. * Sets the current stencil mask
  13035. * @param mask defines the new stencil mask to use
  13036. */
  13037. Engine.prototype.setStencilMask = function (mask) {
  13038. this._stencilState.stencilMask = mask;
  13039. };
  13040. /**
  13041. * Gets the current stencil function
  13042. * @returns a number defining the stencil function to use
  13043. */
  13044. Engine.prototype.getStencilFunction = function () {
  13045. return this._stencilState.stencilFunc;
  13046. };
  13047. /**
  13048. * Gets the current stencil reference value
  13049. * @returns a number defining the stencil reference value to use
  13050. */
  13051. Engine.prototype.getStencilFunctionReference = function () {
  13052. return this._stencilState.stencilFuncRef;
  13053. };
  13054. /**
  13055. * Gets the current stencil mask
  13056. * @returns a number defining the stencil mask to use
  13057. */
  13058. Engine.prototype.getStencilFunctionMask = function () {
  13059. return this._stencilState.stencilFuncMask;
  13060. };
  13061. /**
  13062. * Sets the current stencil function
  13063. * @param stencilFunc defines the new stencil function to use
  13064. */
  13065. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13066. this._stencilState.stencilFunc = stencilFunc;
  13067. };
  13068. /**
  13069. * Sets the current stencil reference
  13070. * @param reference defines the new stencil reference to use
  13071. */
  13072. Engine.prototype.setStencilFunctionReference = function (reference) {
  13073. this._stencilState.stencilFuncRef = reference;
  13074. };
  13075. /**
  13076. * Sets the current stencil mask
  13077. * @param mask defines the new stencil mask to use
  13078. */
  13079. Engine.prototype.setStencilFunctionMask = function (mask) {
  13080. this._stencilState.stencilFuncMask = mask;
  13081. };
  13082. /**
  13083. * Gets the current stencil operation when stencil fails
  13084. * @returns a number defining stencil operation to use when stencil fails
  13085. */
  13086. Engine.prototype.getStencilOperationFail = function () {
  13087. return this._stencilState.stencilOpStencilFail;
  13088. };
  13089. /**
  13090. * Gets the current stencil operation when depth fails
  13091. * @returns a number defining stencil operation to use when depth fails
  13092. */
  13093. Engine.prototype.getStencilOperationDepthFail = function () {
  13094. return this._stencilState.stencilOpDepthFail;
  13095. };
  13096. /**
  13097. * Gets the current stencil operation when stencil passes
  13098. * @returns a number defining stencil operation to use when stencil passes
  13099. */
  13100. Engine.prototype.getStencilOperationPass = function () {
  13101. return this._stencilState.stencilOpStencilDepthPass;
  13102. };
  13103. /**
  13104. * Sets the stencil operation to use when stencil fails
  13105. * @param operation defines the stencil operation to use when stencil fails
  13106. */
  13107. Engine.prototype.setStencilOperationFail = function (operation) {
  13108. this._stencilState.stencilOpStencilFail = operation;
  13109. };
  13110. /**
  13111. * Sets the stencil operation to use when depth fails
  13112. * @param operation defines the stencil operation to use when depth fails
  13113. */
  13114. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13115. this._stencilState.stencilOpDepthFail = operation;
  13116. };
  13117. /**
  13118. * Sets the stencil operation to use when stencil passes
  13119. * @param operation defines the stencil operation to use when stencil passes
  13120. */
  13121. Engine.prototype.setStencilOperationPass = function (operation) {
  13122. this._stencilState.stencilOpStencilDepthPass = operation;
  13123. };
  13124. /**
  13125. * Sets a boolean indicating if the dithering state is enabled or disabled
  13126. * @param value defines the dithering state
  13127. */
  13128. Engine.prototype.setDitheringState = function (value) {
  13129. if (value) {
  13130. this._gl.enable(this._gl.DITHER);
  13131. }
  13132. else {
  13133. this._gl.disable(this._gl.DITHER);
  13134. }
  13135. };
  13136. /**
  13137. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13138. * @param value defines the rasterizer state
  13139. */
  13140. Engine.prototype.setRasterizerState = function (value) {
  13141. if (value) {
  13142. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13143. }
  13144. else {
  13145. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13146. }
  13147. };
  13148. /**
  13149. * stop executing a render loop function and remove it from the execution array
  13150. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13151. */
  13152. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13153. if (!renderFunction) {
  13154. this._activeRenderLoops = [];
  13155. return;
  13156. }
  13157. var index = this._activeRenderLoops.indexOf(renderFunction);
  13158. if (index >= 0) {
  13159. this._activeRenderLoops.splice(index, 1);
  13160. }
  13161. };
  13162. /** @hidden */
  13163. Engine.prototype._renderLoop = function () {
  13164. if (!this._contextWasLost) {
  13165. var shouldRender = true;
  13166. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13167. shouldRender = false;
  13168. }
  13169. if (shouldRender) {
  13170. // Start new frame
  13171. this.beginFrame();
  13172. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13173. var renderFunction = this._activeRenderLoops[index];
  13174. renderFunction();
  13175. }
  13176. // Present
  13177. this.endFrame();
  13178. }
  13179. }
  13180. if (this._activeRenderLoops.length > 0) {
  13181. // Register new frame
  13182. var requester = null;
  13183. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13184. requester = this._vrDisplay;
  13185. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13186. }
  13187. else {
  13188. this._renderingQueueLaunched = false;
  13189. }
  13190. };
  13191. /**
  13192. * Register and execute a render loop. The engine can have more than one render function
  13193. * @param renderFunction defines the function to continuously execute
  13194. */
  13195. Engine.prototype.runRenderLoop = function (renderFunction) {
  13196. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13197. return;
  13198. }
  13199. this._activeRenderLoops.push(renderFunction);
  13200. if (!this._renderingQueueLaunched) {
  13201. this._renderingQueueLaunched = true;
  13202. this._bindedRenderFunction = this._renderLoop.bind(this);
  13203. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13204. }
  13205. };
  13206. /**
  13207. * Toggle full screen mode
  13208. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13209. */
  13210. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13211. if (this.isFullscreen) {
  13212. BABYLON.Tools.ExitFullscreen();
  13213. }
  13214. else {
  13215. this._pointerLockRequested = requestPointerLock;
  13216. if (this._renderingCanvas) {
  13217. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13218. }
  13219. }
  13220. };
  13221. /**
  13222. * Clear the current render buffer or the current render target (if any is set up)
  13223. * @param color defines the color to use
  13224. * @param backBuffer defines if the back buffer must be cleared
  13225. * @param depth defines if the depth buffer must be cleared
  13226. * @param stencil defines if the stencil buffer must be cleared
  13227. */
  13228. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13229. if (stencil === void 0) { stencil = false; }
  13230. this.applyStates();
  13231. var mode = 0;
  13232. if (backBuffer && color) {
  13233. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13234. mode |= this._gl.COLOR_BUFFER_BIT;
  13235. }
  13236. if (depth) {
  13237. this._gl.clearDepth(1.0);
  13238. mode |= this._gl.DEPTH_BUFFER_BIT;
  13239. }
  13240. if (stencil) {
  13241. this._gl.clearStencil(0);
  13242. mode |= this._gl.STENCIL_BUFFER_BIT;
  13243. }
  13244. this._gl.clear(mode);
  13245. };
  13246. /**
  13247. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13248. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13249. * @param y defines the y-coordinate of the corner of the clear rectangle
  13250. * @param width defines the width of the clear rectangle
  13251. * @param height defines the height of the clear rectangle
  13252. * @param clearColor defines the clear color
  13253. */
  13254. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13255. var gl = this._gl;
  13256. // Save state
  13257. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13258. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13259. // Change state
  13260. gl.enable(gl.SCISSOR_TEST);
  13261. gl.scissor(x, y, width, height);
  13262. // Clear
  13263. this.clear(clearColor, true, true, true);
  13264. // Restore state
  13265. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13266. if (curScissor === true) {
  13267. gl.enable(gl.SCISSOR_TEST);
  13268. }
  13269. else {
  13270. gl.disable(gl.SCISSOR_TEST);
  13271. }
  13272. };
  13273. /** @hidden */
  13274. Engine.prototype._viewport = function (x, y, width, height) {
  13275. if (x !== this._viewportCached.x ||
  13276. y !== this._viewportCached.y ||
  13277. width !== this._viewportCached.z ||
  13278. height !== this._viewportCached.w) {
  13279. this._viewportCached.x = x;
  13280. this._viewportCached.y = y;
  13281. this._viewportCached.z = width;
  13282. this._viewportCached.w = height;
  13283. this._gl.viewport(x, y, width, height);
  13284. }
  13285. };
  13286. /**
  13287. * Set the WebGL's viewport
  13288. * @param viewport defines the viewport element to be used
  13289. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13290. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13291. */
  13292. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13293. var width = requiredWidth || this.getRenderWidth();
  13294. var height = requiredHeight || this.getRenderHeight();
  13295. var x = viewport.x || 0;
  13296. var y = viewport.y || 0;
  13297. this._cachedViewport = viewport;
  13298. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13299. };
  13300. /**
  13301. * Directly set the WebGL Viewport
  13302. * @param x defines the x coordinate of the viewport (in screen space)
  13303. * @param y defines the y coordinate of the viewport (in screen space)
  13304. * @param width defines the width of the viewport (in screen space)
  13305. * @param height defines the height of the viewport (in screen space)
  13306. * @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
  13307. */
  13308. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13309. var currentViewport = this._cachedViewport;
  13310. this._cachedViewport = null;
  13311. this._viewport(x, y, width, height);
  13312. return currentViewport;
  13313. };
  13314. /**
  13315. * Begin a new frame
  13316. */
  13317. Engine.prototype.beginFrame = function () {
  13318. this.onBeginFrameObservable.notifyObservers(this);
  13319. this._measureFps();
  13320. };
  13321. /**
  13322. * Enf the current frame
  13323. */
  13324. Engine.prototype.endFrame = function () {
  13325. // Force a flush in case we are using a bad OS.
  13326. if (this._badOS) {
  13327. this.flushFramebuffer();
  13328. }
  13329. // Submit frame to the vr device, if enabled
  13330. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13331. // TODO: We should only submit the frame if we read frameData successfully.
  13332. this._vrDisplay.submitFrame();
  13333. }
  13334. this.onEndFrameObservable.notifyObservers(this);
  13335. };
  13336. /**
  13337. * Resize the view according to the canvas' size
  13338. */
  13339. Engine.prototype.resize = function () {
  13340. // We're not resizing the size of the canvas while in VR mode & presenting
  13341. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13342. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13343. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13344. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13345. }
  13346. };
  13347. /**
  13348. * Force a specific size of the canvas
  13349. * @param width defines the new canvas' width
  13350. * @param height defines the new canvas' height
  13351. */
  13352. Engine.prototype.setSize = function (width, height) {
  13353. if (!this._renderingCanvas) {
  13354. return;
  13355. }
  13356. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13357. return;
  13358. }
  13359. this._renderingCanvas.width = width;
  13360. this._renderingCanvas.height = height;
  13361. for (var index = 0; index < this.scenes.length; index++) {
  13362. var scene = this.scenes[index];
  13363. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13364. var cam = scene.cameras[camIndex];
  13365. cam._currentRenderId = 0;
  13366. }
  13367. }
  13368. if (this.onResizeObservable.hasObservers) {
  13369. this.onResizeObservable.notifyObservers(this);
  13370. }
  13371. };
  13372. // WebVR functions
  13373. /**
  13374. * Gets a boolean indicating if a webVR device was detected
  13375. * @returns true if a webVR device was detected
  13376. */
  13377. Engine.prototype.isVRDevicePresent = function () {
  13378. return !!this._vrDisplay;
  13379. };
  13380. /**
  13381. * Gets the current webVR device
  13382. * @returns the current webVR device (or null)
  13383. */
  13384. Engine.prototype.getVRDevice = function () {
  13385. return this._vrDisplay;
  13386. };
  13387. /**
  13388. * Initializes a webVR display and starts listening to display change events
  13389. * The onVRDisplayChangedObservable will be notified upon these changes
  13390. * @returns The onVRDisplayChangedObservable
  13391. */
  13392. Engine.prototype.initWebVR = function () {
  13393. this.initWebVRAsync();
  13394. return this.onVRDisplayChangedObservable;
  13395. };
  13396. /**
  13397. * Initializes a webVR display and starts listening to display change events
  13398. * The onVRDisplayChangedObservable will be notified upon these changes
  13399. * @returns A promise containing a VRDisplay and if vr is supported
  13400. */
  13401. Engine.prototype.initWebVRAsync = function () {
  13402. var _this = this;
  13403. var notifyObservers = function () {
  13404. var eventArgs = {
  13405. vrDisplay: _this._vrDisplay,
  13406. vrSupported: _this._vrSupported
  13407. };
  13408. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13409. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13410. };
  13411. if (!this._onVrDisplayConnect) {
  13412. this._onVrDisplayConnect = function (event) {
  13413. _this._vrDisplay = event.display;
  13414. notifyObservers();
  13415. };
  13416. this._onVrDisplayDisconnect = function () {
  13417. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13418. _this._vrDisplay = undefined;
  13419. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13420. notifyObservers();
  13421. };
  13422. this._onVrDisplayPresentChange = function () {
  13423. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13424. };
  13425. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13426. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13427. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13428. }
  13429. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13430. this._webVRInitPromise.then(notifyObservers);
  13431. return this._webVRInitPromise;
  13432. };
  13433. /**
  13434. * Call this function to switch to webVR mode
  13435. * Will do nothing if webVR is not supported or if there is no webVR device
  13436. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13437. */
  13438. Engine.prototype.enableVR = function () {
  13439. var _this = this;
  13440. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13441. var onResolved = function () {
  13442. _this.onVRRequestPresentComplete.notifyObservers(true);
  13443. _this._onVRFullScreenTriggered();
  13444. };
  13445. var onRejected = function () {
  13446. _this.onVRRequestPresentComplete.notifyObservers(false);
  13447. };
  13448. this.onVRRequestPresentStart.notifyObservers(this);
  13449. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13450. }
  13451. };
  13452. /**
  13453. * Call this function to leave webVR mode
  13454. * Will do nothing if webVR is not supported or if there is no webVR device
  13455. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13456. */
  13457. Engine.prototype.disableVR = function () {
  13458. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13459. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13460. }
  13461. };
  13462. Engine.prototype._getVRDisplaysAsync = function () {
  13463. var _this = this;
  13464. return new Promise(function (res, rej) {
  13465. if (navigator.getVRDisplays) {
  13466. navigator.getVRDisplays().then(function (devices) {
  13467. _this._vrSupported = true;
  13468. // note that devices may actually be an empty array. This is fine;
  13469. // we expect this._vrDisplay to be undefined in this case.
  13470. _this._vrDisplay = devices[0];
  13471. res({
  13472. vrDisplay: _this._vrDisplay,
  13473. vrSupported: _this._vrSupported
  13474. });
  13475. });
  13476. }
  13477. else {
  13478. _this._vrDisplay = undefined;
  13479. _this._vrSupported = false;
  13480. res({
  13481. vrDisplay: _this._vrDisplay,
  13482. vrSupported: _this._vrSupported
  13483. });
  13484. }
  13485. });
  13486. };
  13487. /**
  13488. * Binds the frame buffer to the specified texture.
  13489. * @param texture The texture to render to or null for the default canvas
  13490. * @param faceIndex The face of the texture to render to in case of cube texture
  13491. * @param requiredWidth The width of the target to render to
  13492. * @param requiredHeight The height of the target to render to
  13493. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13494. * @param depthStencilTexture The depth stencil texture to use to render
  13495. * @param lodLevel defines le lod level to bind to the frame buffer
  13496. */
  13497. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13498. if (lodLevel === void 0) { lodLevel = 0; }
  13499. if (this._currentRenderTarget) {
  13500. this.unBindFramebuffer(this._currentRenderTarget);
  13501. }
  13502. this._currentRenderTarget = texture;
  13503. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13504. var gl = this._gl;
  13505. if (texture.isCube) {
  13506. if (faceIndex === undefined) {
  13507. faceIndex = 0;
  13508. }
  13509. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13510. if (depthStencilTexture) {
  13511. if (depthStencilTexture._generateStencilBuffer) {
  13512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13513. }
  13514. else {
  13515. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13516. }
  13517. }
  13518. }
  13519. if (this._cachedViewport && !forceFullscreenViewport) {
  13520. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13521. }
  13522. else {
  13523. if (!requiredWidth) {
  13524. requiredWidth = texture.width;
  13525. if (lodLevel) {
  13526. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13527. }
  13528. }
  13529. if (!requiredHeight) {
  13530. requiredHeight = texture.height;
  13531. if (lodLevel) {
  13532. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13533. }
  13534. }
  13535. this._viewport(0, 0, requiredWidth, requiredHeight);
  13536. }
  13537. this.wipeCaches();
  13538. };
  13539. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13540. if (this._currentFramebuffer !== framebuffer) {
  13541. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13542. this._currentFramebuffer = framebuffer;
  13543. }
  13544. };
  13545. /**
  13546. * Unbind the current render target texture from the webGL context
  13547. * @param texture defines the render target texture to unbind
  13548. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13549. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13550. */
  13551. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13552. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13553. this._currentRenderTarget = null;
  13554. // If MSAA, we need to bitblt back to main texture
  13555. var gl = this._gl;
  13556. if (texture._MSAAFramebuffer) {
  13557. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13558. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13559. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13560. }
  13561. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13562. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13563. gl.generateMipmap(gl.TEXTURE_2D);
  13564. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13565. }
  13566. if (onBeforeUnbind) {
  13567. if (texture._MSAAFramebuffer) {
  13568. // Bind the correct framebuffer
  13569. this.bindUnboundFramebuffer(texture._framebuffer);
  13570. }
  13571. onBeforeUnbind();
  13572. }
  13573. this.bindUnboundFramebuffer(null);
  13574. };
  13575. /**
  13576. * Unbind a list of render target textures from the webGL context
  13577. * This is used only when drawBuffer extension or webGL2 are active
  13578. * @param textures defines the render target textures to unbind
  13579. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13580. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13581. */
  13582. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13583. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13584. this._currentRenderTarget = null;
  13585. // If MSAA, we need to bitblt back to main texture
  13586. var gl = this._gl;
  13587. if (textures[0]._MSAAFramebuffer) {
  13588. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13589. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13590. var attachments = textures[0]._attachments;
  13591. if (!attachments) {
  13592. attachments = new Array(textures.length);
  13593. textures[0]._attachments = attachments;
  13594. }
  13595. for (var i = 0; i < textures.length; i++) {
  13596. var texture = textures[i];
  13597. for (var j = 0; j < attachments.length; j++) {
  13598. attachments[j] = gl.NONE;
  13599. }
  13600. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13601. gl.readBuffer(attachments[i]);
  13602. gl.drawBuffers(attachments);
  13603. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13604. }
  13605. for (var i = 0; i < attachments.length; i++) {
  13606. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13607. }
  13608. gl.drawBuffers(attachments);
  13609. }
  13610. for (var i = 0; i < textures.length; i++) {
  13611. var texture = textures[i];
  13612. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13613. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13614. gl.generateMipmap(gl.TEXTURE_2D);
  13615. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13616. }
  13617. }
  13618. if (onBeforeUnbind) {
  13619. if (textures[0]._MSAAFramebuffer) {
  13620. // Bind the correct framebuffer
  13621. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13622. }
  13623. onBeforeUnbind();
  13624. }
  13625. this.bindUnboundFramebuffer(null);
  13626. };
  13627. /**
  13628. * Force the mipmap generation for the given render target texture
  13629. * @param texture defines the render target texture to use
  13630. */
  13631. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13632. if (texture.generateMipMaps) {
  13633. var gl = this._gl;
  13634. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13635. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13636. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13637. }
  13638. };
  13639. /**
  13640. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13641. */
  13642. Engine.prototype.flushFramebuffer = function () {
  13643. this._gl.flush();
  13644. };
  13645. /**
  13646. * Unbind the current render target and bind the default framebuffer
  13647. */
  13648. Engine.prototype.restoreDefaultFramebuffer = function () {
  13649. if (this._currentRenderTarget) {
  13650. this.unBindFramebuffer(this._currentRenderTarget);
  13651. }
  13652. else {
  13653. this.bindUnboundFramebuffer(null);
  13654. }
  13655. if (this._cachedViewport) {
  13656. this.setViewport(this._cachedViewport);
  13657. }
  13658. this.wipeCaches();
  13659. };
  13660. // UBOs
  13661. /**
  13662. * Create an uniform buffer
  13663. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13664. * @param elements defines the content of the uniform buffer
  13665. * @returns the webGL uniform buffer
  13666. */
  13667. Engine.prototype.createUniformBuffer = function (elements) {
  13668. var ubo = this._gl.createBuffer();
  13669. if (!ubo) {
  13670. throw new Error("Unable to create uniform buffer");
  13671. }
  13672. this.bindUniformBuffer(ubo);
  13673. if (elements instanceof Float32Array) {
  13674. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13675. }
  13676. else {
  13677. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13678. }
  13679. this.bindUniformBuffer(null);
  13680. ubo.references = 1;
  13681. return ubo;
  13682. };
  13683. /**
  13684. * Create a dynamic uniform buffer
  13685. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13686. * @param elements defines the content of the uniform buffer
  13687. * @returns the webGL uniform buffer
  13688. */
  13689. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13690. var ubo = this._gl.createBuffer();
  13691. if (!ubo) {
  13692. throw new Error("Unable to create dynamic uniform buffer");
  13693. }
  13694. this.bindUniformBuffer(ubo);
  13695. if (elements instanceof Float32Array) {
  13696. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13697. }
  13698. else {
  13699. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13700. }
  13701. this.bindUniformBuffer(null);
  13702. ubo.references = 1;
  13703. return ubo;
  13704. };
  13705. /**
  13706. * Update an existing uniform buffer
  13707. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13708. * @param uniformBuffer defines the target uniform buffer
  13709. * @param elements defines the content to update
  13710. * @param offset defines the offset in the uniform buffer where update should start
  13711. * @param count defines the size of the data to update
  13712. */
  13713. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13714. this.bindUniformBuffer(uniformBuffer);
  13715. if (offset === undefined) {
  13716. offset = 0;
  13717. }
  13718. if (count === undefined) {
  13719. if (elements instanceof Float32Array) {
  13720. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13721. }
  13722. else {
  13723. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13724. }
  13725. }
  13726. else {
  13727. if (elements instanceof Float32Array) {
  13728. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13729. }
  13730. else {
  13731. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13732. }
  13733. }
  13734. this.bindUniformBuffer(null);
  13735. };
  13736. // VBOs
  13737. Engine.prototype._resetVertexBufferBinding = function () {
  13738. this.bindArrayBuffer(null);
  13739. this._cachedVertexBuffers = null;
  13740. };
  13741. /**
  13742. * Creates a vertex buffer
  13743. * @param data the data for the vertex buffer
  13744. * @returns the new WebGL static buffer
  13745. */
  13746. Engine.prototype.createVertexBuffer = function (data) {
  13747. var vbo = this._gl.createBuffer();
  13748. if (!vbo) {
  13749. throw new Error("Unable to create vertex buffer");
  13750. }
  13751. this.bindArrayBuffer(vbo);
  13752. if (data instanceof Array) {
  13753. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13754. }
  13755. else {
  13756. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13757. }
  13758. this._resetVertexBufferBinding();
  13759. vbo.references = 1;
  13760. return vbo;
  13761. };
  13762. /**
  13763. * Creates a dynamic vertex buffer
  13764. * @param data the data for the dynamic vertex buffer
  13765. * @returns the new WebGL dynamic buffer
  13766. */
  13767. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13768. var vbo = this._gl.createBuffer();
  13769. if (!vbo) {
  13770. throw new Error("Unable to create dynamic vertex buffer");
  13771. }
  13772. this.bindArrayBuffer(vbo);
  13773. if (data instanceof Array) {
  13774. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13775. }
  13776. else {
  13777. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13778. }
  13779. this._resetVertexBufferBinding();
  13780. vbo.references = 1;
  13781. return vbo;
  13782. };
  13783. /**
  13784. * Update a dynamic index buffer
  13785. * @param indexBuffer defines the target index buffer
  13786. * @param indices defines the data to update
  13787. * @param offset defines the offset in the target index buffer where update should start
  13788. */
  13789. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13790. if (offset === void 0) { offset = 0; }
  13791. // Force cache update
  13792. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13793. this.bindIndexBuffer(indexBuffer);
  13794. var arrayBuffer;
  13795. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13796. arrayBuffer = indices;
  13797. }
  13798. else {
  13799. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13800. }
  13801. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13802. this._resetIndexBufferBinding();
  13803. };
  13804. /**
  13805. * Updates a dynamic vertex buffer.
  13806. * @param vertexBuffer the vertex buffer to update
  13807. * @param data the data used to update the vertex buffer
  13808. * @param byteOffset the byte offset of the data
  13809. * @param byteLength the byte length of the data
  13810. */
  13811. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13812. this.bindArrayBuffer(vertexBuffer);
  13813. if (byteOffset === undefined) {
  13814. byteOffset = 0;
  13815. }
  13816. if (byteLength === undefined) {
  13817. if (data instanceof Array) {
  13818. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13819. }
  13820. else {
  13821. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13822. }
  13823. }
  13824. else {
  13825. if (data instanceof Array) {
  13826. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13827. }
  13828. else {
  13829. if (data instanceof ArrayBuffer) {
  13830. data = new Uint8Array(data, byteOffset, byteLength);
  13831. }
  13832. else {
  13833. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13834. }
  13835. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13836. }
  13837. }
  13838. this._resetVertexBufferBinding();
  13839. };
  13840. Engine.prototype._resetIndexBufferBinding = function () {
  13841. this.bindIndexBuffer(null);
  13842. this._cachedIndexBuffer = null;
  13843. };
  13844. /**
  13845. * Creates a new index buffer
  13846. * @param indices defines the content of the index buffer
  13847. * @param updatable defines if the index buffer must be updatable
  13848. * @returns a new webGL buffer
  13849. */
  13850. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13851. var vbo = this._gl.createBuffer();
  13852. if (!vbo) {
  13853. throw new Error("Unable to create index buffer");
  13854. }
  13855. this.bindIndexBuffer(vbo);
  13856. // Check for 32 bits indices
  13857. var arrayBuffer;
  13858. var need32Bits = false;
  13859. if (indices instanceof Uint16Array) {
  13860. arrayBuffer = indices;
  13861. }
  13862. else {
  13863. //check 32 bit support
  13864. if (this._caps.uintIndices) {
  13865. if (indices instanceof Uint32Array) {
  13866. arrayBuffer = indices;
  13867. need32Bits = true;
  13868. }
  13869. else {
  13870. //number[] or Int32Array, check if 32 bit is necessary
  13871. for (var index = 0; index < indices.length; index++) {
  13872. if (indices[index] > 65535) {
  13873. need32Bits = true;
  13874. break;
  13875. }
  13876. }
  13877. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13878. }
  13879. }
  13880. else {
  13881. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13882. arrayBuffer = new Uint16Array(indices);
  13883. }
  13884. }
  13885. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13886. this._resetIndexBufferBinding();
  13887. vbo.references = 1;
  13888. vbo.is32Bits = need32Bits;
  13889. return vbo;
  13890. };
  13891. /**
  13892. * Bind a webGL buffer to the webGL context
  13893. * @param buffer defines the buffer to bind
  13894. */
  13895. Engine.prototype.bindArrayBuffer = function (buffer) {
  13896. if (!this._vaoRecordInProgress) {
  13897. this._unbindVertexArrayObject();
  13898. }
  13899. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13900. };
  13901. /**
  13902. * Bind an uniform buffer to the current webGL context
  13903. * @param buffer defines the buffer to bind
  13904. */
  13905. Engine.prototype.bindUniformBuffer = function (buffer) {
  13906. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13907. };
  13908. /**
  13909. * Bind a buffer to the current webGL context at a given location
  13910. * @param buffer defines the buffer to bind
  13911. * @param location defines the index where to bind the buffer
  13912. */
  13913. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13914. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13915. };
  13916. /**
  13917. * Bind a specific block at a given index in a specific shader program
  13918. * @param shaderProgram defines the shader program
  13919. * @param blockName defines the block name
  13920. * @param index defines the index where to bind the block
  13921. */
  13922. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13923. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13924. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13925. };
  13926. ;
  13927. Engine.prototype.bindIndexBuffer = function (buffer) {
  13928. if (!this._vaoRecordInProgress) {
  13929. this._unbindVertexArrayObject();
  13930. }
  13931. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13932. };
  13933. Engine.prototype.bindBuffer = function (buffer, target) {
  13934. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13935. this._gl.bindBuffer(target, buffer);
  13936. this._currentBoundBuffer[target] = buffer;
  13937. }
  13938. };
  13939. /**
  13940. * update the bound buffer with the given data
  13941. * @param data defines the data to update
  13942. */
  13943. Engine.prototype.updateArrayBuffer = function (data) {
  13944. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13945. };
  13946. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13947. var pointer = this._currentBufferPointers[indx];
  13948. var changed = false;
  13949. if (!pointer.active) {
  13950. changed = true;
  13951. pointer.active = true;
  13952. pointer.index = indx;
  13953. pointer.size = size;
  13954. pointer.type = type;
  13955. pointer.normalized = normalized;
  13956. pointer.stride = stride;
  13957. pointer.offset = offset;
  13958. pointer.buffer = buffer;
  13959. }
  13960. else {
  13961. if (pointer.buffer !== buffer) {
  13962. pointer.buffer = buffer;
  13963. changed = true;
  13964. }
  13965. if (pointer.size !== size) {
  13966. pointer.size = size;
  13967. changed = true;
  13968. }
  13969. if (pointer.type !== type) {
  13970. pointer.type = type;
  13971. changed = true;
  13972. }
  13973. if (pointer.normalized !== normalized) {
  13974. pointer.normalized = normalized;
  13975. changed = true;
  13976. }
  13977. if (pointer.stride !== stride) {
  13978. pointer.stride = stride;
  13979. changed = true;
  13980. }
  13981. if (pointer.offset !== offset) {
  13982. pointer.offset = offset;
  13983. changed = true;
  13984. }
  13985. }
  13986. if (changed || this._vaoRecordInProgress) {
  13987. this.bindArrayBuffer(buffer);
  13988. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13989. }
  13990. };
  13991. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13992. if (indexBuffer == null) {
  13993. return;
  13994. }
  13995. if (this._cachedIndexBuffer !== indexBuffer) {
  13996. this._cachedIndexBuffer = indexBuffer;
  13997. this.bindIndexBuffer(indexBuffer);
  13998. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13999. }
  14000. };
  14001. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14002. var attributes = effect.getAttributesNames();
  14003. if (!this._vaoRecordInProgress) {
  14004. this._unbindVertexArrayObject();
  14005. }
  14006. this.unbindAllAttributes();
  14007. for (var index = 0; index < attributes.length; index++) {
  14008. var order = effect.getAttributeLocation(index);
  14009. if (order >= 0) {
  14010. var vertexBuffer = vertexBuffers[attributes[index]];
  14011. if (!vertexBuffer) {
  14012. continue;
  14013. }
  14014. this._gl.enableVertexAttribArray(order);
  14015. if (!this._vaoRecordInProgress) {
  14016. this._vertexAttribArraysEnabled[order] = true;
  14017. }
  14018. var buffer = vertexBuffer.getBuffer();
  14019. if (buffer) {
  14020. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14021. if (vertexBuffer.getIsInstanced()) {
  14022. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14023. if (!this._vaoRecordInProgress) {
  14024. this._currentInstanceLocations.push(order);
  14025. this._currentInstanceBuffers.push(buffer);
  14026. }
  14027. }
  14028. }
  14029. }
  14030. }
  14031. };
  14032. /**
  14033. * Records a vertex array object
  14034. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14035. * @param vertexBuffers defines the list of vertex buffers to store
  14036. * @param indexBuffer defines the index buffer to store
  14037. * @param effect defines the effect to store
  14038. * @returns the new vertex array object
  14039. */
  14040. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14041. var vao = this._gl.createVertexArray();
  14042. this._vaoRecordInProgress = true;
  14043. this._gl.bindVertexArray(vao);
  14044. this._mustWipeVertexAttributes = true;
  14045. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14046. this.bindIndexBuffer(indexBuffer);
  14047. this._vaoRecordInProgress = false;
  14048. this._gl.bindVertexArray(null);
  14049. return vao;
  14050. };
  14051. /**
  14052. * Bind a specific vertex array object
  14053. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14054. * @param vertexArrayObject defines the vertex array object to bind
  14055. * @param indexBuffer defines the index buffer to bind
  14056. */
  14057. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14058. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14059. this._cachedVertexArrayObject = vertexArrayObject;
  14060. this._gl.bindVertexArray(vertexArrayObject);
  14061. this._cachedVertexBuffers = null;
  14062. this._cachedIndexBuffer = null;
  14063. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14064. this._mustWipeVertexAttributes = true;
  14065. }
  14066. };
  14067. /**
  14068. * Bind webGl buffers directly to the webGL context
  14069. * @param vertexBuffer defines the vertex buffer to bind
  14070. * @param indexBuffer defines the index buffer to bind
  14071. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14072. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14073. * @param effect defines the effect associated with the vertex buffer
  14074. */
  14075. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14076. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14077. this._cachedVertexBuffers = vertexBuffer;
  14078. this._cachedEffectForVertexBuffers = effect;
  14079. var attributesCount = effect.getAttributesCount();
  14080. this._unbindVertexArrayObject();
  14081. this.unbindAllAttributes();
  14082. var offset = 0;
  14083. for (var index = 0; index < attributesCount; index++) {
  14084. if (index < vertexDeclaration.length) {
  14085. var order = effect.getAttributeLocation(index);
  14086. if (order >= 0) {
  14087. this._gl.enableVertexAttribArray(order);
  14088. this._vertexAttribArraysEnabled[order] = true;
  14089. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14090. }
  14091. offset += vertexDeclaration[index] * 4;
  14092. }
  14093. }
  14094. }
  14095. this._bindIndexBufferWithCache(indexBuffer);
  14096. };
  14097. Engine.prototype._unbindVertexArrayObject = function () {
  14098. if (!this._cachedVertexArrayObject) {
  14099. return;
  14100. }
  14101. this._cachedVertexArrayObject = null;
  14102. this._gl.bindVertexArray(null);
  14103. };
  14104. /**
  14105. * Bind a list of vertex buffers to the webGL context
  14106. * @param vertexBuffers defines the list of vertex buffers to bind
  14107. * @param indexBuffer defines the index buffer to bind
  14108. * @param effect defines the effect associated with the vertex buffers
  14109. */
  14110. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14111. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14112. this._cachedVertexBuffers = vertexBuffers;
  14113. this._cachedEffectForVertexBuffers = effect;
  14114. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14115. }
  14116. this._bindIndexBufferWithCache(indexBuffer);
  14117. };
  14118. /**
  14119. * Unbind all instance attributes
  14120. */
  14121. Engine.prototype.unbindInstanceAttributes = function () {
  14122. var boundBuffer;
  14123. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14124. var instancesBuffer = this._currentInstanceBuffers[i];
  14125. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14126. boundBuffer = instancesBuffer;
  14127. this.bindArrayBuffer(instancesBuffer);
  14128. }
  14129. var offsetLocation = this._currentInstanceLocations[i];
  14130. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14131. }
  14132. this._currentInstanceBuffers.length = 0;
  14133. this._currentInstanceLocations.length = 0;
  14134. };
  14135. /**
  14136. * Release and free the memory of a vertex array object
  14137. * @param vao defines the vertex array object to delete
  14138. */
  14139. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14140. this._gl.deleteVertexArray(vao);
  14141. };
  14142. /** @hidden */
  14143. Engine.prototype._releaseBuffer = function (buffer) {
  14144. buffer.references--;
  14145. if (buffer.references === 0) {
  14146. this._gl.deleteBuffer(buffer);
  14147. return true;
  14148. }
  14149. return false;
  14150. };
  14151. /**
  14152. * Creates a webGL buffer to use with instanciation
  14153. * @param capacity defines the size of the buffer
  14154. * @returns the webGL buffer
  14155. */
  14156. Engine.prototype.createInstancesBuffer = function (capacity) {
  14157. var buffer = this._gl.createBuffer();
  14158. if (!buffer) {
  14159. throw new Error("Unable to create instance buffer");
  14160. }
  14161. buffer.capacity = capacity;
  14162. this.bindArrayBuffer(buffer);
  14163. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14164. return buffer;
  14165. };
  14166. /**
  14167. * Delete a webGL buffer used with instanciation
  14168. * @param buffer defines the webGL buffer to delete
  14169. */
  14170. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14171. this._gl.deleteBuffer(buffer);
  14172. };
  14173. /**
  14174. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14175. * @param instancesBuffer defines the webGL buffer to update and bind
  14176. * @param data defines the data to store in the buffer
  14177. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14178. */
  14179. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14180. this.bindArrayBuffer(instancesBuffer);
  14181. if (data) {
  14182. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14183. }
  14184. if (offsetLocations[0].index !== undefined) {
  14185. var stride = 0;
  14186. for (var i = 0; i < offsetLocations.length; i++) {
  14187. var ai = offsetLocations[i];
  14188. stride += ai.attributeSize * 4;
  14189. }
  14190. for (var i = 0; i < offsetLocations.length; i++) {
  14191. var ai = offsetLocations[i];
  14192. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14193. this._gl.enableVertexAttribArray(ai.index);
  14194. this._vertexAttribArraysEnabled[ai.index] = true;
  14195. }
  14196. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14197. this._gl.vertexAttribDivisor(ai.index, 1);
  14198. this._currentInstanceLocations.push(ai.index);
  14199. this._currentInstanceBuffers.push(instancesBuffer);
  14200. }
  14201. }
  14202. else {
  14203. for (var index = 0; index < 4; index++) {
  14204. var offsetLocation = offsetLocations[index];
  14205. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14206. this._gl.enableVertexAttribArray(offsetLocation);
  14207. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14208. }
  14209. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14210. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14211. this._currentInstanceLocations.push(offsetLocation);
  14212. this._currentInstanceBuffers.push(instancesBuffer);
  14213. }
  14214. }
  14215. };
  14216. /**
  14217. * Apply all cached states (depth, culling, stencil and alpha)
  14218. */
  14219. Engine.prototype.applyStates = function () {
  14220. this._depthCullingState.apply(this._gl);
  14221. this._stencilState.apply(this._gl);
  14222. this._alphaState.apply(this._gl);
  14223. };
  14224. /**
  14225. * Send a draw order
  14226. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14227. * @param indexStart defines the starting index
  14228. * @param indexCount defines the number of index to draw
  14229. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14230. */
  14231. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14232. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14233. };
  14234. /**
  14235. * Draw a list of points
  14236. * @param verticesStart defines the index of first vertex to draw
  14237. * @param verticesCount defines the count of vertices to draw
  14238. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14239. */
  14240. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14241. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14242. };
  14243. /**
  14244. * Draw a list of unindexed primitives
  14245. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14246. * @param verticesStart defines the index of first vertex to draw
  14247. * @param verticesCount defines the count of vertices to draw
  14248. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14249. */
  14250. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14251. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14252. };
  14253. /**
  14254. * Draw a list of indexed primitives
  14255. * @param fillMode defines the primitive to use
  14256. * @param indexStart defines the starting index
  14257. * @param indexCount defines the number of index to draw
  14258. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14259. */
  14260. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14261. // Apply states
  14262. this.applyStates();
  14263. this._drawCalls.addCount(1, false);
  14264. // Render
  14265. var drawMode = this._drawMode(fillMode);
  14266. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14267. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14268. if (instancesCount) {
  14269. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14270. }
  14271. else {
  14272. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14273. }
  14274. };
  14275. /**
  14276. * Draw a list of unindexed primitives
  14277. * @param fillMode defines the primitive to use
  14278. * @param verticesStart defines the index of first vertex to draw
  14279. * @param verticesCount defines the count of vertices to draw
  14280. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14281. */
  14282. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14283. // Apply states
  14284. this.applyStates();
  14285. this._drawCalls.addCount(1, false);
  14286. var drawMode = this._drawMode(fillMode);
  14287. if (instancesCount) {
  14288. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14289. }
  14290. else {
  14291. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14292. }
  14293. };
  14294. Engine.prototype._drawMode = function (fillMode) {
  14295. switch (fillMode) {
  14296. // Triangle views
  14297. case BABYLON.Material.TriangleFillMode:
  14298. return this._gl.TRIANGLES;
  14299. case BABYLON.Material.PointFillMode:
  14300. return this._gl.POINTS;
  14301. case BABYLON.Material.WireFrameFillMode:
  14302. return this._gl.LINES;
  14303. // Draw modes
  14304. case BABYLON.Material.PointListDrawMode:
  14305. return this._gl.POINTS;
  14306. case BABYLON.Material.LineListDrawMode:
  14307. return this._gl.LINES;
  14308. case BABYLON.Material.LineLoopDrawMode:
  14309. return this._gl.LINE_LOOP;
  14310. case BABYLON.Material.LineStripDrawMode:
  14311. return this._gl.LINE_STRIP;
  14312. case BABYLON.Material.TriangleStripDrawMode:
  14313. return this._gl.TRIANGLE_STRIP;
  14314. case BABYLON.Material.TriangleFanDrawMode:
  14315. return this._gl.TRIANGLE_FAN;
  14316. default:
  14317. return this._gl.TRIANGLES;
  14318. }
  14319. };
  14320. // Shaders
  14321. /** @hidden */
  14322. Engine.prototype._releaseEffect = function (effect) {
  14323. if (this._compiledEffects[effect._key]) {
  14324. delete this._compiledEffects[effect._key];
  14325. this._deleteProgram(effect.getProgram());
  14326. }
  14327. };
  14328. /** @hidden */
  14329. Engine.prototype._deleteProgram = function (program) {
  14330. if (program) {
  14331. program.__SPECTOR_rebuildProgram = null;
  14332. if (program.transformFeedback) {
  14333. this.deleteTransformFeedback(program.transformFeedback);
  14334. program.transformFeedback = null;
  14335. }
  14336. this._gl.deleteProgram(program);
  14337. }
  14338. };
  14339. /**
  14340. * Create a new effect (used to store vertex/fragment shaders)
  14341. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14342. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14343. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14344. * @param samplers defines an array of string used to represent textures
  14345. * @param defines defines the string containing the defines to use to compile the shaders
  14346. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14347. * @param onCompiled defines a function to call when the effect creation is successful
  14348. * @param onError defines a function to call when the effect creation has failed
  14349. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14350. * @returns the new Effect
  14351. */
  14352. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14353. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14354. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14355. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14356. if (this._compiledEffects[name]) {
  14357. var compiledEffect = this._compiledEffects[name];
  14358. if (onCompiled && compiledEffect.isReady()) {
  14359. onCompiled(compiledEffect);
  14360. }
  14361. return compiledEffect;
  14362. }
  14363. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14364. effect._key = name;
  14365. this._compiledEffects[name] = effect;
  14366. return effect;
  14367. };
  14368. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14369. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14370. };
  14371. ;
  14372. Engine.prototype._compileRawShader = function (source, type) {
  14373. var gl = this._gl;
  14374. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14375. gl.shaderSource(shader, source);
  14376. gl.compileShader(shader);
  14377. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14378. var log = gl.getShaderInfoLog(shader);
  14379. if (log) {
  14380. throw new Error(log);
  14381. }
  14382. }
  14383. if (!shader) {
  14384. throw new Error("Something went wrong while compile the shader.");
  14385. }
  14386. return shader;
  14387. };
  14388. ;
  14389. /**
  14390. * Directly creates a webGL program
  14391. * @param vertexCode defines the vertex shader code to use
  14392. * @param fragmentCode defines the fragment shader code to use
  14393. * @param context defines the webGL context to use (if not set, the current one will be used)
  14394. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14395. * @returns the new webGL program
  14396. */
  14397. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14398. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14399. context = context || this._gl;
  14400. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14401. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14402. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14403. };
  14404. /**
  14405. * Creates a webGL program
  14406. * @param vertexCode defines the vertex shader code to use
  14407. * @param fragmentCode defines the fragment shader code to use
  14408. * @param defines defines the string containing the defines to use to compile the shaders
  14409. * @param context defines the webGL context to use (if not set, the current one will be used)
  14410. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14411. * @returns the new webGL program
  14412. */
  14413. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14414. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14415. context = context || this._gl;
  14416. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14417. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14418. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14419. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14420. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14421. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14422. return program;
  14423. };
  14424. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14425. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14426. var shaderProgram = context.createProgram();
  14427. if (!shaderProgram) {
  14428. throw new Error("Unable to create program");
  14429. }
  14430. context.attachShader(shaderProgram, vertexShader);
  14431. context.attachShader(shaderProgram, fragmentShader);
  14432. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14433. var transformFeedback = this.createTransformFeedback();
  14434. this.bindTransformFeedback(transformFeedback);
  14435. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14436. shaderProgram.transformFeedback = transformFeedback;
  14437. }
  14438. context.linkProgram(shaderProgram);
  14439. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14440. this.bindTransformFeedback(null);
  14441. }
  14442. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14443. if (!linked) {
  14444. var error = context.getProgramInfoLog(shaderProgram);
  14445. if (error) {
  14446. throw new Error(error);
  14447. }
  14448. }
  14449. if (this.validateShaderPrograms) {
  14450. context.validateProgram(shaderProgram);
  14451. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14452. if (!validated) {
  14453. var error = context.getProgramInfoLog(shaderProgram);
  14454. if (error) {
  14455. throw new Error(error);
  14456. }
  14457. }
  14458. }
  14459. context.deleteShader(vertexShader);
  14460. context.deleteShader(fragmentShader);
  14461. return shaderProgram;
  14462. };
  14463. /**
  14464. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14465. * @param shaderProgram defines the webGL program to use
  14466. * @param uniformsNames defines the list of uniform names
  14467. * @returns an array of webGL uniform locations
  14468. */
  14469. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14470. var results = new Array();
  14471. for (var index = 0; index < uniformsNames.length; index++) {
  14472. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14473. }
  14474. return results;
  14475. };
  14476. /**
  14477. * Gets the lsit of active attributes for a given webGL program
  14478. * @param shaderProgram defines the webGL program to use
  14479. * @param attributesNames defines the list of attribute names to get
  14480. * @returns an array of indices indicating the offset of each attribute
  14481. */
  14482. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14483. var results = [];
  14484. for (var index = 0; index < attributesNames.length; index++) {
  14485. try {
  14486. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14487. }
  14488. catch (e) {
  14489. results.push(-1);
  14490. }
  14491. }
  14492. return results;
  14493. };
  14494. /**
  14495. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14496. * @param effect defines the effect to activate
  14497. */
  14498. Engine.prototype.enableEffect = function (effect) {
  14499. if (!effect || effect === this._currentEffect) {
  14500. return;
  14501. }
  14502. // Use program
  14503. this.bindSamplers(effect);
  14504. this._currentEffect = effect;
  14505. if (effect.onBind) {
  14506. effect.onBind(effect);
  14507. }
  14508. if (effect._onBindObservable) {
  14509. effect._onBindObservable.notifyObservers(effect);
  14510. }
  14511. };
  14512. /**
  14513. * Set the value of an uniform to an array of int32
  14514. * @param uniform defines the webGL uniform location where to store the value
  14515. * @param array defines the array of int32 to store
  14516. */
  14517. Engine.prototype.setIntArray = function (uniform, array) {
  14518. if (!uniform)
  14519. return;
  14520. this._gl.uniform1iv(uniform, array);
  14521. };
  14522. /**
  14523. * Set the value of an uniform to an array of int32 (stored as vec2)
  14524. * @param uniform defines the webGL uniform location where to store the value
  14525. * @param array defines the array of int32 to store
  14526. */
  14527. Engine.prototype.setIntArray2 = function (uniform, array) {
  14528. if (!uniform || array.length % 2 !== 0)
  14529. return;
  14530. this._gl.uniform2iv(uniform, array);
  14531. };
  14532. /**
  14533. * Set the value of an uniform to an array of int32 (stored as vec3)
  14534. * @param uniform defines the webGL uniform location where to store the value
  14535. * @param array defines the array of int32 to store
  14536. */
  14537. Engine.prototype.setIntArray3 = function (uniform, array) {
  14538. if (!uniform || array.length % 3 !== 0)
  14539. return;
  14540. this._gl.uniform3iv(uniform, array);
  14541. };
  14542. /**
  14543. * Set the value of an uniform to an array of int32 (stored as vec4)
  14544. * @param uniform defines the webGL uniform location where to store the value
  14545. * @param array defines the array of int32 to store
  14546. */
  14547. Engine.prototype.setIntArray4 = function (uniform, array) {
  14548. if (!uniform || array.length % 4 !== 0)
  14549. return;
  14550. this._gl.uniform4iv(uniform, array);
  14551. };
  14552. /**
  14553. * Set the value of an uniform to an array of float32
  14554. * @param uniform defines the webGL uniform location where to store the value
  14555. * @param array defines the array of float32 to store
  14556. */
  14557. Engine.prototype.setFloatArray = function (uniform, array) {
  14558. if (!uniform)
  14559. return;
  14560. this._gl.uniform1fv(uniform, array);
  14561. };
  14562. /**
  14563. * Set the value of an uniform to an array of float32 (stored as vec2)
  14564. * @param uniform defines the webGL uniform location where to store the value
  14565. * @param array defines the array of float32 to store
  14566. */
  14567. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14568. if (!uniform || array.length % 2 !== 0)
  14569. return;
  14570. this._gl.uniform2fv(uniform, array);
  14571. };
  14572. /**
  14573. * Set the value of an uniform to an array of float32 (stored as vec3)
  14574. * @param uniform defines the webGL uniform location where to store the value
  14575. * @param array defines the array of float32 to store
  14576. */
  14577. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14578. if (!uniform || array.length % 3 !== 0)
  14579. return;
  14580. this._gl.uniform3fv(uniform, array);
  14581. };
  14582. /**
  14583. * Set the value of an uniform to an array of float32 (stored as vec4)
  14584. * @param uniform defines the webGL uniform location where to store the value
  14585. * @param array defines the array of float32 to store
  14586. */
  14587. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14588. if (!uniform || array.length % 4 !== 0)
  14589. return;
  14590. this._gl.uniform4fv(uniform, array);
  14591. };
  14592. /**
  14593. * Set the value of an uniform to an array of number
  14594. * @param uniform defines the webGL uniform location where to store the value
  14595. * @param array defines the array of number to store
  14596. */
  14597. Engine.prototype.setArray = function (uniform, array) {
  14598. if (!uniform)
  14599. return;
  14600. this._gl.uniform1fv(uniform, array);
  14601. };
  14602. /**
  14603. * Set the value of an uniform to an array of number (stored as vec2)
  14604. * @param uniform defines the webGL uniform location where to store the value
  14605. * @param array defines the array of number to store
  14606. */
  14607. Engine.prototype.setArray2 = function (uniform, array) {
  14608. if (!uniform || array.length % 2 !== 0)
  14609. return;
  14610. this._gl.uniform2fv(uniform, array);
  14611. };
  14612. /**
  14613. * Set the value of an uniform to an array of number (stored as vec3)
  14614. * @param uniform defines the webGL uniform location where to store the value
  14615. * @param array defines the array of number to store
  14616. */
  14617. Engine.prototype.setArray3 = function (uniform, array) {
  14618. if (!uniform || array.length % 3 !== 0)
  14619. return;
  14620. this._gl.uniform3fv(uniform, array);
  14621. };
  14622. /**
  14623. * Set the value of an uniform to an array of number (stored as vec4)
  14624. * @param uniform defines the webGL uniform location where to store the value
  14625. * @param array defines the array of number to store
  14626. */
  14627. Engine.prototype.setArray4 = function (uniform, array) {
  14628. if (!uniform || array.length % 4 !== 0)
  14629. return;
  14630. this._gl.uniform4fv(uniform, array);
  14631. };
  14632. /**
  14633. * Set the value of an uniform to an array of float32 (stored as matrices)
  14634. * @param uniform defines the webGL uniform location where to store the value
  14635. * @param matrices defines the array of float32 to store
  14636. */
  14637. Engine.prototype.setMatrices = function (uniform, matrices) {
  14638. if (!uniform)
  14639. return;
  14640. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14641. };
  14642. /**
  14643. * Set the value of an uniform to a matrix
  14644. * @param uniform defines the webGL uniform location where to store the value
  14645. * @param matrix defines the matrix to store
  14646. */
  14647. Engine.prototype.setMatrix = function (uniform, matrix) {
  14648. if (!uniform)
  14649. return;
  14650. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14651. };
  14652. /**
  14653. * Set the value of an uniform to a matrix (3x3)
  14654. * @param uniform defines the webGL uniform location where to store the value
  14655. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14656. */
  14657. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14658. if (!uniform)
  14659. return;
  14660. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14661. };
  14662. /**
  14663. * Set the value of an uniform to a matrix (2x2)
  14664. * @param uniform defines the webGL uniform location where to store the value
  14665. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14666. */
  14667. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14668. if (!uniform)
  14669. return;
  14670. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14671. };
  14672. /**
  14673. * Set the value of an uniform to a number (int)
  14674. * @param uniform defines the webGL uniform location where to store the value
  14675. * @param value defines the int number to store
  14676. */
  14677. Engine.prototype.setInt = function (uniform, value) {
  14678. if (!uniform)
  14679. return;
  14680. this._gl.uniform1i(uniform, value);
  14681. };
  14682. /**
  14683. * Set the value of an uniform to a number (float)
  14684. * @param uniform defines the webGL uniform location where to store the value
  14685. * @param value defines the float number to store
  14686. */
  14687. Engine.prototype.setFloat = function (uniform, value) {
  14688. if (!uniform)
  14689. return;
  14690. this._gl.uniform1f(uniform, value);
  14691. };
  14692. /**
  14693. * Set the value of an uniform to a vec2
  14694. * @param uniform defines the webGL uniform location where to store the value
  14695. * @param x defines the 1st component of the value
  14696. * @param y defines the 2nd component of the value
  14697. */
  14698. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14699. if (!uniform)
  14700. return;
  14701. this._gl.uniform2f(uniform, x, y);
  14702. };
  14703. /**
  14704. * Set the value of an uniform to a vec3
  14705. * @param uniform defines the webGL uniform location where to store the value
  14706. * @param x defines the 1st component of the value
  14707. * @param y defines the 2nd component of the value
  14708. * @param z defines the 3rd component of the value
  14709. */
  14710. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14711. if (!uniform)
  14712. return;
  14713. this._gl.uniform3f(uniform, x, y, z);
  14714. };
  14715. /**
  14716. * Set the value of an uniform to a boolean
  14717. * @param uniform defines the webGL uniform location where to store the value
  14718. * @param bool defines the boolean to store
  14719. */
  14720. Engine.prototype.setBool = function (uniform, bool) {
  14721. if (!uniform)
  14722. return;
  14723. this._gl.uniform1i(uniform, bool);
  14724. };
  14725. /**
  14726. * Set the value of an uniform to a vec4
  14727. * @param uniform defines the webGL uniform location where to store the value
  14728. * @param x defines the 1st component of the value
  14729. * @param y defines the 2nd component of the value
  14730. * @param z defines the 3rd component of the value
  14731. * @param w defines the 4th component of the value
  14732. */
  14733. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14734. if (!uniform)
  14735. return;
  14736. this._gl.uniform4f(uniform, x, y, z, w);
  14737. };
  14738. /**
  14739. * Set the value of an uniform to a Color3
  14740. * @param uniform defines the webGL uniform location where to store the value
  14741. * @param color3 defines the color to store
  14742. */
  14743. Engine.prototype.setColor3 = function (uniform, color3) {
  14744. if (!uniform)
  14745. return;
  14746. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14747. };
  14748. /**
  14749. * Set the value of an uniform to a Color3 and an alpha value
  14750. * @param uniform defines the webGL uniform location where to store the value
  14751. * @param color3 defines the color to store
  14752. * @param alpha defines the alpha component to store
  14753. */
  14754. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14755. if (!uniform)
  14756. return;
  14757. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14758. };
  14759. /**
  14760. * Sets a Color4 on a uniform variable
  14761. * @param uniform defines the uniform location
  14762. * @param color4 defines the value to be set
  14763. */
  14764. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14765. if (!uniform)
  14766. return;
  14767. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14768. };
  14769. // States
  14770. /**
  14771. * Set various states to the webGL context
  14772. * @param culling defines backface culling state
  14773. * @param zOffset defines the value to apply to zOffset (0 by default)
  14774. * @param force defines if states must be applied even if cache is up to date
  14775. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14776. */
  14777. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14778. if (zOffset === void 0) { zOffset = 0; }
  14779. if (reverseSide === void 0) { reverseSide = false; }
  14780. // Culling
  14781. if (this._depthCullingState.cull !== culling || force) {
  14782. this._depthCullingState.cull = culling;
  14783. }
  14784. // Cull face
  14785. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14786. if (this._depthCullingState.cullFace !== cullFace || force) {
  14787. this._depthCullingState.cullFace = cullFace;
  14788. }
  14789. // Z offset
  14790. this.setZOffset(zOffset);
  14791. // Front face
  14792. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14793. if (this._depthCullingState.frontFace !== frontFace || force) {
  14794. this._depthCullingState.frontFace = frontFace;
  14795. }
  14796. };
  14797. /**
  14798. * Set the z offset to apply to current rendering
  14799. * @param value defines the offset to apply
  14800. */
  14801. Engine.prototype.setZOffset = function (value) {
  14802. this._depthCullingState.zOffset = value;
  14803. };
  14804. /**
  14805. * Gets the current value of the zOffset
  14806. * @returns the current zOffset state
  14807. */
  14808. Engine.prototype.getZOffset = function () {
  14809. return this._depthCullingState.zOffset;
  14810. };
  14811. /**
  14812. * Enable or disable depth buffering
  14813. * @param enable defines the state to set
  14814. */
  14815. Engine.prototype.setDepthBuffer = function (enable) {
  14816. this._depthCullingState.depthTest = enable;
  14817. };
  14818. /**
  14819. * Gets a boolean indicating if depth writing is enabled
  14820. * @returns the current depth writing state
  14821. */
  14822. Engine.prototype.getDepthWrite = function () {
  14823. return this._depthCullingState.depthMask;
  14824. };
  14825. /**
  14826. * Enable or disable depth writing
  14827. * @param enable defines the state to set
  14828. */
  14829. Engine.prototype.setDepthWrite = function (enable) {
  14830. this._depthCullingState.depthMask = enable;
  14831. };
  14832. /**
  14833. * Enable or disable color writing
  14834. * @param enable defines the state to set
  14835. */
  14836. Engine.prototype.setColorWrite = function (enable) {
  14837. this._gl.colorMask(enable, enable, enable, enable);
  14838. this._colorWrite = enable;
  14839. };
  14840. /**
  14841. * Gets a boolean indicating if color writing is enabled
  14842. * @returns the current color writing state
  14843. */
  14844. Engine.prototype.getColorWrite = function () {
  14845. return this._colorWrite;
  14846. };
  14847. /**
  14848. * Sets alpha constants used by some alpha blending modes
  14849. * @param r defines the red component
  14850. * @param g defines the green component
  14851. * @param b defines the blue component
  14852. * @param a defines the alpha component
  14853. */
  14854. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14855. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14856. };
  14857. /**
  14858. * Sets the current alpha mode
  14859. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14860. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14861. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14862. */
  14863. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14864. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14865. if (this._alphaMode === mode) {
  14866. return;
  14867. }
  14868. switch (mode) {
  14869. case Engine.ALPHA_DISABLE:
  14870. this._alphaState.alphaBlend = false;
  14871. break;
  14872. case Engine.ALPHA_PREMULTIPLIED:
  14873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14874. this._alphaState.alphaBlend = true;
  14875. break;
  14876. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14878. this._alphaState.alphaBlend = true;
  14879. break;
  14880. case Engine.ALPHA_COMBINE:
  14881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14882. this._alphaState.alphaBlend = true;
  14883. break;
  14884. case Engine.ALPHA_ONEONE:
  14885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14886. this._alphaState.alphaBlend = true;
  14887. break;
  14888. case Engine.ALPHA_ADD:
  14889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14890. this._alphaState.alphaBlend = true;
  14891. break;
  14892. case Engine.ALPHA_SUBTRACT:
  14893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14894. this._alphaState.alphaBlend = true;
  14895. break;
  14896. case Engine.ALPHA_MULTIPLY:
  14897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14898. this._alphaState.alphaBlend = true;
  14899. break;
  14900. case Engine.ALPHA_MAXIMIZED:
  14901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14902. this._alphaState.alphaBlend = true;
  14903. break;
  14904. case Engine.ALPHA_INTERPOLATE:
  14905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14906. this._alphaState.alphaBlend = true;
  14907. break;
  14908. case Engine.ALPHA_SCREENMODE:
  14909. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14910. this._alphaState.alphaBlend = true;
  14911. break;
  14912. }
  14913. if (!noDepthWriteChange) {
  14914. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14915. }
  14916. this._alphaMode = mode;
  14917. };
  14918. /**
  14919. * Gets the current alpha mode
  14920. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14921. * @returns the current alpha mode
  14922. */
  14923. Engine.prototype.getAlphaMode = function () {
  14924. return this._alphaMode;
  14925. };
  14926. // Textures
  14927. /**
  14928. * Clears the list of texture accessible through engine.
  14929. * This can help preventing texture load conflict due to name collision.
  14930. */
  14931. Engine.prototype.clearInternalTexturesCache = function () {
  14932. this._internalTexturesCache = [];
  14933. };
  14934. /**
  14935. * Force the entire cache to be cleared
  14936. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14937. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14938. */
  14939. Engine.prototype.wipeCaches = function (bruteForce) {
  14940. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14941. return;
  14942. }
  14943. this._currentEffect = null;
  14944. this._viewportCached.x = 0;
  14945. this._viewportCached.y = 0;
  14946. this._viewportCached.z = 0;
  14947. this._viewportCached.w = 0;
  14948. if (bruteForce) {
  14949. this.resetTextureCache();
  14950. this._currentProgram = null;
  14951. this._stencilState.reset();
  14952. this._depthCullingState.reset();
  14953. this.setDepthFunctionToLessOrEqual();
  14954. this._alphaState.reset();
  14955. this._unpackFlipYCached = null;
  14956. }
  14957. this._resetVertexBufferBinding();
  14958. this._cachedIndexBuffer = null;
  14959. this._cachedEffectForVertexBuffers = null;
  14960. this._unbindVertexArrayObject();
  14961. this.bindIndexBuffer(null);
  14962. };
  14963. /**
  14964. * Set the compressed texture format to use, based on the formats you have, and the formats
  14965. * supported by the hardware / browser.
  14966. *
  14967. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14968. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14969. * to API arguments needed to compressed textures. This puts the burden on the container
  14970. * generator to house the arcane code for determining these for current & future formats.
  14971. *
  14972. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14973. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14974. *
  14975. * Note: The result of this call is not taken into account when a texture is base64.
  14976. *
  14977. * @param formatsAvailable defines the list of those format families you have created
  14978. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14979. *
  14980. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14981. * @returns The extension selected.
  14982. */
  14983. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14984. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14985. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14986. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14987. return this._textureFormatInUse = this._texturesSupported[i];
  14988. }
  14989. }
  14990. }
  14991. // actively set format to nothing, to allow this to be called more than once
  14992. // and possibly fail the 2nd time
  14993. this._textureFormatInUse = null;
  14994. return null;
  14995. };
  14996. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14997. var gl = this._gl;
  14998. var magFilter = gl.NEAREST;
  14999. var minFilter = gl.NEAREST;
  15000. switch (samplingMode) {
  15001. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15002. magFilter = gl.LINEAR;
  15003. if (generateMipMaps) {
  15004. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15005. }
  15006. else {
  15007. minFilter = gl.LINEAR;
  15008. }
  15009. break;
  15010. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15011. magFilter = gl.LINEAR;
  15012. if (generateMipMaps) {
  15013. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15014. }
  15015. else {
  15016. minFilter = gl.LINEAR;
  15017. }
  15018. break;
  15019. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15020. magFilter = gl.NEAREST;
  15021. if (generateMipMaps) {
  15022. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15023. }
  15024. else {
  15025. minFilter = gl.NEAREST;
  15026. }
  15027. break;
  15028. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15029. magFilter = gl.NEAREST;
  15030. if (generateMipMaps) {
  15031. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15032. }
  15033. else {
  15034. minFilter = gl.NEAREST;
  15035. }
  15036. break;
  15037. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15038. magFilter = gl.NEAREST;
  15039. if (generateMipMaps) {
  15040. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15041. }
  15042. else {
  15043. minFilter = gl.LINEAR;
  15044. }
  15045. break;
  15046. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15047. magFilter = gl.NEAREST;
  15048. if (generateMipMaps) {
  15049. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15050. }
  15051. else {
  15052. minFilter = gl.LINEAR;
  15053. }
  15054. break;
  15055. case Engine.TEXTURE_NEAREST_LINEAR:
  15056. magFilter = gl.NEAREST;
  15057. minFilter = gl.LINEAR;
  15058. break;
  15059. case Engine.TEXTURE_NEAREST_NEAREST:
  15060. magFilter = gl.NEAREST;
  15061. minFilter = gl.NEAREST;
  15062. break;
  15063. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15064. magFilter = gl.LINEAR;
  15065. if (generateMipMaps) {
  15066. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15067. }
  15068. else {
  15069. minFilter = gl.NEAREST;
  15070. }
  15071. break;
  15072. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15073. magFilter = gl.LINEAR;
  15074. if (generateMipMaps) {
  15075. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15076. }
  15077. else {
  15078. minFilter = gl.NEAREST;
  15079. }
  15080. break;
  15081. case Engine.TEXTURE_LINEAR_LINEAR:
  15082. magFilter = gl.LINEAR;
  15083. minFilter = gl.LINEAR;
  15084. break;
  15085. case Engine.TEXTURE_LINEAR_NEAREST:
  15086. magFilter = gl.LINEAR;
  15087. minFilter = gl.NEAREST;
  15088. break;
  15089. }
  15090. return {
  15091. min: minFilter,
  15092. mag: magFilter
  15093. };
  15094. };
  15095. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15096. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15097. var img;
  15098. var onload = function () {
  15099. loadedImages[index] = img;
  15100. loadedImages._internalCount++;
  15101. if (scene) {
  15102. scene._removePendingData(img);
  15103. }
  15104. if (loadedImages._internalCount === 6) {
  15105. onfinish(loadedImages);
  15106. }
  15107. };
  15108. var onerror = function (message, exception) {
  15109. if (scene) {
  15110. scene._removePendingData(img);
  15111. }
  15112. if (onErrorCallBack) {
  15113. onErrorCallBack(message, exception);
  15114. }
  15115. };
  15116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15117. if (scene) {
  15118. scene._addPendingData(img);
  15119. }
  15120. };
  15121. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15122. if (onError === void 0) { onError = null; }
  15123. var loadedImages = [];
  15124. loadedImages._internalCount = 0;
  15125. for (var index = 0; index < 6; index++) {
  15126. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15127. }
  15128. };
  15129. ;
  15130. /** @hidden */
  15131. Engine.prototype._createTexture = function () {
  15132. var texture = this._gl.createTexture();
  15133. if (!texture) {
  15134. throw new Error("Unable to create texture");
  15135. }
  15136. return texture;
  15137. };
  15138. /**
  15139. * Usually called from BABYLON.Texture.ts.
  15140. * Passed information to create a WebGLTexture
  15141. * @param urlArg defines a value which contains one of the following:
  15142. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15143. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15144. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15145. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15146. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15147. * @param scene needed for loading to the correct scene
  15148. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15149. * @param onLoad optional callback to be called upon successful completion
  15150. * @param onError optional callback to be called upon failure
  15151. * @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
  15152. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15153. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15154. * @param forcedExtension defines the extension to use to pick the right loader
  15155. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15156. */
  15157. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15158. var _this = this;
  15159. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15160. if (onLoad === void 0) { onLoad = null; }
  15161. if (onError === void 0) { onError = null; }
  15162. if (buffer === void 0) { buffer = null; }
  15163. if (fallback === void 0) { fallback = null; }
  15164. if (format === void 0) { format = null; }
  15165. if (forcedExtension === void 0) { forcedExtension = null; }
  15166. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15167. var fromData = url.substr(0, 5) === "data:";
  15168. var fromBlob = url.substr(0, 5) === "blob:";
  15169. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15170. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15171. // establish the file extension, if possible
  15172. var lastDot = url.lastIndexOf('.');
  15173. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15174. var loader = null;
  15175. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15176. var availableLoader = _a[_i];
  15177. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15178. loader = availableLoader;
  15179. break;
  15180. }
  15181. }
  15182. if (loader) {
  15183. url = loader.transformUrl(url, this._textureFormatInUse);
  15184. }
  15185. if (scene) {
  15186. scene._addPendingData(texture);
  15187. }
  15188. texture.url = url;
  15189. texture.generateMipMaps = !noMipmap;
  15190. texture.samplingMode = samplingMode;
  15191. texture.invertY = invertY;
  15192. if (!this._doNotHandleContextLost) {
  15193. // Keep a link to the buffer only if we plan to handle context lost
  15194. texture._buffer = buffer;
  15195. }
  15196. var onLoadObserver = null;
  15197. if (onLoad && !fallback) {
  15198. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15199. }
  15200. if (!fallback)
  15201. this._internalTexturesCache.push(texture);
  15202. var onInternalError = function (message, exception) {
  15203. if (scene) {
  15204. scene._removePendingData(texture);
  15205. }
  15206. var customFallback = false;
  15207. if (loader) {
  15208. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15209. if (fallbackUrl) {
  15210. // Add Back
  15211. customFallback = true;
  15212. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15213. }
  15214. }
  15215. if (!customFallback) {
  15216. if (onLoadObserver) {
  15217. texture.onLoadedObservable.remove(onLoadObserver);
  15218. }
  15219. if (BABYLON.Tools.UseFallbackTexture) {
  15220. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15221. }
  15222. }
  15223. if (onError) {
  15224. onError(message || "Unknown error", exception);
  15225. }
  15226. };
  15227. // processing for non-image formats
  15228. if (loader) {
  15229. var callback = function (data) {
  15230. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15231. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15232. done();
  15233. return false;
  15234. }, samplingMode);
  15235. });
  15236. };
  15237. if (!buffer) {
  15238. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15239. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15240. });
  15241. }
  15242. else {
  15243. callback(buffer);
  15244. }
  15245. }
  15246. else {
  15247. var onload = function (img) {
  15248. if (fromBlob && !_this._doNotHandleContextLost) {
  15249. // We need to store the image if we need to rebuild the texture
  15250. // in case of a webgl context lost
  15251. texture._buffer = img;
  15252. }
  15253. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15254. var gl = _this._gl;
  15255. var isPot = (img.width === potWidth && img.height === potHeight);
  15256. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15257. if (isPot) {
  15258. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15259. return false;
  15260. }
  15261. var maxTextureSize = _this._caps.maxTextureSize;
  15262. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15263. _this._prepareWorkingCanvas();
  15264. if (!_this._workingCanvas || !_this._workingContext) {
  15265. return false;
  15266. }
  15267. _this._workingCanvas.width = potWidth;
  15268. _this._workingCanvas.height = potHeight;
  15269. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15271. texture.width = potWidth;
  15272. texture.height = potHeight;
  15273. return false;
  15274. }
  15275. else {
  15276. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15277. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15278. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15279. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15284. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15285. _this._releaseTexture(source_1);
  15286. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15287. continuationCallback();
  15288. });
  15289. }
  15290. return true;
  15291. }, samplingMode);
  15292. };
  15293. if (!fromData || isBase64) {
  15294. if (buffer instanceof HTMLImageElement) {
  15295. onload(buffer);
  15296. }
  15297. else {
  15298. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15299. }
  15300. }
  15301. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15302. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15303. }
  15304. else {
  15305. onload(buffer);
  15306. }
  15307. }
  15308. return texture;
  15309. };
  15310. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15311. var _this = this;
  15312. var rtt = this.createRenderTargetTexture({
  15313. width: destination.width,
  15314. height: destination.height,
  15315. }, {
  15316. generateMipMaps: false,
  15317. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15318. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15319. generateDepthBuffer: false,
  15320. generateStencilBuffer: false
  15321. });
  15322. if (!this._rescalePostProcess) {
  15323. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15324. }
  15325. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15326. _this._rescalePostProcess.onApply = function (effect) {
  15327. effect._bindTexture("textureSampler", source);
  15328. };
  15329. var hostingScene = scene;
  15330. if (!hostingScene) {
  15331. hostingScene = _this.scenes[_this.scenes.length - 1];
  15332. }
  15333. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15334. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15335. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15336. _this.unBindFramebuffer(rtt);
  15337. _this._releaseTexture(rtt);
  15338. if (onComplete) {
  15339. onComplete();
  15340. }
  15341. });
  15342. };
  15343. /**
  15344. * Update a raw texture
  15345. * @param texture defines the texture to update
  15346. * @param data defines the data to store in the texture
  15347. * @param format defines the format of the data
  15348. * @param invertY defines if data must be stored with Y axis inverted
  15349. * @param compression defines the compression used (null by default)
  15350. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15351. */
  15352. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15353. if (compression === void 0) { compression = null; }
  15354. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15355. if (!texture) {
  15356. return;
  15357. }
  15358. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15359. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15360. // babylon's internalFormat but gl's texImage2D format
  15361. var internalFormat = this._getInternalFormat(format);
  15362. var textureType = this._getWebGLTextureType(type);
  15363. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15364. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15365. if (!this._doNotHandleContextLost) {
  15366. texture._bufferView = data;
  15367. texture.format = format;
  15368. texture.type = type;
  15369. texture.invertY = invertY;
  15370. texture._compression = compression;
  15371. }
  15372. if (texture.width % 4 !== 0) {
  15373. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15374. }
  15375. if (compression && data) {
  15376. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15377. }
  15378. else {
  15379. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15380. }
  15381. if (texture.generateMipMaps) {
  15382. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15383. }
  15384. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15385. // this.resetTextureCache();
  15386. texture.isReady = true;
  15387. };
  15388. /**
  15389. * Creates a raw texture
  15390. * @param data defines the data to store in the texture
  15391. * @param width defines the width of the texture
  15392. * @param height defines the height of the texture
  15393. * @param format defines the format of the data
  15394. * @param generateMipMaps defines if the engine should generate the mip levels
  15395. * @param invertY defines if data must be stored with Y axis inverted
  15396. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15397. * @param compression defines the compression used (null by default)
  15398. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15399. * @returns the raw texture inside an InternalTexture
  15400. */
  15401. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15402. if (compression === void 0) { compression = null; }
  15403. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15404. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15405. texture.baseWidth = width;
  15406. texture.baseHeight = height;
  15407. texture.width = width;
  15408. texture.height = height;
  15409. texture.format = format;
  15410. texture.generateMipMaps = generateMipMaps;
  15411. texture.samplingMode = samplingMode;
  15412. texture.invertY = invertY;
  15413. texture._compression = compression;
  15414. texture.type = type;
  15415. if (!this._doNotHandleContextLost) {
  15416. texture._bufferView = data;
  15417. }
  15418. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15419. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15420. // Filters
  15421. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15422. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15424. if (generateMipMaps) {
  15425. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15426. }
  15427. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15428. this._internalTexturesCache.push(texture);
  15429. return texture;
  15430. };
  15431. /** @hidden */
  15432. Engine.prototype._unpackFlipY = function (value) {
  15433. if (this._unpackFlipYCached !== value) {
  15434. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15435. if (this.enableUnpackFlipYCached) {
  15436. this._unpackFlipYCached = value;
  15437. }
  15438. }
  15439. };
  15440. /** @hidden */
  15441. Engine.prototype._getUnpackAlignement = function () {
  15442. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15443. };
  15444. /**
  15445. * Creates a dynamic texture
  15446. * @param width defines the width of the texture
  15447. * @param height defines the height of the texture
  15448. * @param generateMipMaps defines if the engine should generate the mip levels
  15449. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15450. * @returns the dynamic texture inside an InternalTexture
  15451. */
  15452. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15453. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15454. texture.baseWidth = width;
  15455. texture.baseHeight = height;
  15456. if (generateMipMaps) {
  15457. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15458. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15459. }
  15460. // this.resetTextureCache();
  15461. texture.width = width;
  15462. texture.height = height;
  15463. texture.isReady = false;
  15464. texture.generateMipMaps = generateMipMaps;
  15465. texture.samplingMode = samplingMode;
  15466. this.updateTextureSamplingMode(samplingMode, texture);
  15467. this._internalTexturesCache.push(texture);
  15468. return texture;
  15469. };
  15470. /**
  15471. * Update the sampling mode of a given texture
  15472. * @param samplingMode defines the required sampling mode
  15473. * @param texture defines the texture to update
  15474. */
  15475. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15476. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15477. if (texture.isCube) {
  15478. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15479. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15480. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15481. }
  15482. else if (texture.is3D) {
  15483. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15484. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15485. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15486. }
  15487. else {
  15488. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15489. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15490. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15491. }
  15492. texture.samplingMode = samplingMode;
  15493. };
  15494. /**
  15495. * Update the content of a dynamic texture
  15496. * @param texture defines the texture to update
  15497. * @param canvas defines the canvas containing the source
  15498. * @param invertY defines if data must be stored with Y axis inverted
  15499. * @param premulAlpha defines if alpha is stored as premultiplied
  15500. * @param format defines the format of the data
  15501. */
  15502. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15503. if (premulAlpha === void 0) { premulAlpha = false; }
  15504. if (!texture) {
  15505. return;
  15506. }
  15507. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15508. this._unpackFlipY(invertY);
  15509. if (premulAlpha) {
  15510. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15511. }
  15512. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15513. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15514. if (texture.generateMipMaps) {
  15515. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15516. }
  15517. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15518. if (premulAlpha) {
  15519. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15520. }
  15521. texture.isReady = true;
  15522. };
  15523. /**
  15524. * Update a video texture
  15525. * @param texture defines the texture to update
  15526. * @param video defines the video element to use
  15527. * @param invertY defines if data must be stored with Y axis inverted
  15528. */
  15529. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15530. if (!texture || texture._isDisabled) {
  15531. return;
  15532. }
  15533. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15534. this._unpackFlipY(!invertY); // Video are upside down by default
  15535. try {
  15536. // Testing video texture support
  15537. if (this._videoTextureSupported === undefined) {
  15538. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15539. if (this._gl.getError() !== 0) {
  15540. this._videoTextureSupported = false;
  15541. }
  15542. else {
  15543. this._videoTextureSupported = true;
  15544. }
  15545. }
  15546. // Copy video through the current working canvas if video texture is not supported
  15547. if (!this._videoTextureSupported) {
  15548. if (!texture._workingCanvas) {
  15549. texture._workingCanvas = document.createElement("canvas");
  15550. var context = texture._workingCanvas.getContext("2d");
  15551. if (!context) {
  15552. throw new Error("Unable to get 2d context");
  15553. }
  15554. texture._workingContext = context;
  15555. texture._workingCanvas.width = texture.width;
  15556. texture._workingCanvas.height = texture.height;
  15557. }
  15558. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15559. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15560. }
  15561. else {
  15562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15563. }
  15564. if (texture.generateMipMaps) {
  15565. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15566. }
  15567. if (!wasPreviouslyBound) {
  15568. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15569. }
  15570. // this.resetTextureCache();
  15571. texture.isReady = true;
  15572. }
  15573. catch (ex) {
  15574. // Something unexpected
  15575. // Let's disable the texture
  15576. texture._isDisabled = true;
  15577. }
  15578. };
  15579. /**
  15580. * Updates a depth texture Comparison Mode and Function.
  15581. * If the comparison Function is equal to 0, the mode will be set to none.
  15582. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15583. * @param texture The texture to set the comparison function for
  15584. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15585. */
  15586. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15587. if (this.webGLVersion === 1) {
  15588. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15589. return;
  15590. }
  15591. var gl = this._gl;
  15592. if (texture.isCube) {
  15593. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15594. if (comparisonFunction === 0) {
  15595. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15597. }
  15598. else {
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15601. }
  15602. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15603. }
  15604. else {
  15605. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15606. if (comparisonFunction === 0) {
  15607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15609. }
  15610. else {
  15611. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15613. }
  15614. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15615. }
  15616. texture._comparisonFunction = comparisonFunction;
  15617. };
  15618. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15619. var width = size.width || size;
  15620. var height = size.height || size;
  15621. internalTexture.baseWidth = width;
  15622. internalTexture.baseHeight = height;
  15623. internalTexture.width = width;
  15624. internalTexture.height = height;
  15625. internalTexture.isReady = true;
  15626. internalTexture.samples = 1;
  15627. internalTexture.generateMipMaps = false;
  15628. internalTexture._generateDepthBuffer = true;
  15629. internalTexture._generateStencilBuffer = generateStencil;
  15630. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15631. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15632. internalTexture._comparisonFunction = comparisonFunction;
  15633. var gl = this._gl;
  15634. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15635. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15636. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15637. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15638. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15639. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15640. if (comparisonFunction === 0) {
  15641. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15642. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15643. }
  15644. else {
  15645. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15646. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15647. }
  15648. };
  15649. /**
  15650. * Creates a depth stencil texture.
  15651. * This is only available in WebGL 2 or with the depth texture extension available.
  15652. * @param size The size of face edge in the texture.
  15653. * @param options The options defining the texture.
  15654. * @returns The texture
  15655. */
  15656. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15657. if (options.isCube) {
  15658. var width = size.width || size;
  15659. return this._createDepthStencilCubeTexture(width, options);
  15660. }
  15661. else {
  15662. return this._createDepthStencilTexture(size, options);
  15663. }
  15664. };
  15665. /**
  15666. * Creates a depth stencil texture.
  15667. * This is only available in WebGL 2 or with the depth texture extension available.
  15668. * @param size The size of face edge in the texture.
  15669. * @param options The options defining the texture.
  15670. * @returns The texture
  15671. */
  15672. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15673. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15674. if (!this._caps.depthTextureExtension) {
  15675. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15676. return internalTexture;
  15677. }
  15678. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15679. var gl = this._gl;
  15680. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15681. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15682. if (this.webGLVersion > 1) {
  15683. if (internalOptions.generateStencil) {
  15684. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15685. }
  15686. else {
  15687. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15688. }
  15689. }
  15690. else {
  15691. if (internalOptions.generateStencil) {
  15692. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15693. }
  15694. else {
  15695. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15696. }
  15697. }
  15698. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15699. return internalTexture;
  15700. };
  15701. /**
  15702. * Creates a depth stencil cube texture.
  15703. * This is only available in WebGL 2.
  15704. * @param size The size of face edge in the cube texture.
  15705. * @param options The options defining the cube texture.
  15706. * @returns The cube texture
  15707. */
  15708. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15709. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15710. internalTexture.isCube = true;
  15711. if (this.webGLVersion === 1) {
  15712. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15713. return internalTexture;
  15714. }
  15715. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15716. var gl = this._gl;
  15717. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15718. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15719. // Create the depth/stencil buffer
  15720. for (var face = 0; face < 6; face++) {
  15721. if (internalOptions.generateStencil) {
  15722. 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);
  15723. }
  15724. else {
  15725. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15726. }
  15727. }
  15728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15729. return internalTexture;
  15730. };
  15731. /**
  15732. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15733. * @param renderTarget The render target to set the frame buffer for
  15734. */
  15735. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15736. // Create the framebuffer
  15737. var internalTexture = renderTarget.getInternalTexture();
  15738. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15739. return;
  15740. }
  15741. var gl = this._gl;
  15742. var depthStencilTexture = renderTarget.depthStencilTexture;
  15743. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15744. if (depthStencilTexture.isCube) {
  15745. if (depthStencilTexture._generateStencilBuffer) {
  15746. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15747. }
  15748. else {
  15749. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15750. }
  15751. }
  15752. else {
  15753. if (depthStencilTexture._generateStencilBuffer) {
  15754. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15755. }
  15756. else {
  15757. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15758. }
  15759. }
  15760. this.bindUnboundFramebuffer(null);
  15761. };
  15762. /**
  15763. * Creates a new render target texture
  15764. * @param size defines the size of the texture
  15765. * @param options defines the options used to create the texture
  15766. * @returns a new render target texture stored in an InternalTexture
  15767. */
  15768. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15769. var fullOptions = new RenderTargetCreationOptions();
  15770. if (options !== undefined && typeof options === "object") {
  15771. fullOptions.generateMipMaps = options.generateMipMaps;
  15772. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15773. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15774. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15775. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15776. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15777. }
  15778. else {
  15779. fullOptions.generateMipMaps = options;
  15780. fullOptions.generateDepthBuffer = true;
  15781. fullOptions.generateStencilBuffer = false;
  15782. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15783. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15784. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15785. }
  15786. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15787. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15788. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15789. }
  15790. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15791. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15792. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15793. }
  15794. var gl = this._gl;
  15795. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15796. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15797. var width = size.width || size;
  15798. var height = size.height || size;
  15799. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15800. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15801. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15802. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15803. }
  15804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15806. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15807. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15808. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15809. // Create the framebuffer
  15810. var currentFrameBuffer = this._currentFramebuffer;
  15811. var framebuffer = gl.createFramebuffer();
  15812. this.bindUnboundFramebuffer(framebuffer);
  15813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15814. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15815. if (fullOptions.generateMipMaps) {
  15816. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15817. }
  15818. // Unbind
  15819. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15820. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15821. this.bindUnboundFramebuffer(currentFrameBuffer);
  15822. texture._framebuffer = framebuffer;
  15823. texture.baseWidth = width;
  15824. texture.baseHeight = height;
  15825. texture.width = width;
  15826. texture.height = height;
  15827. texture.isReady = true;
  15828. texture.samples = 1;
  15829. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15830. texture.samplingMode = fullOptions.samplingMode;
  15831. texture.type = fullOptions.type;
  15832. texture.format = fullOptions.format;
  15833. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15834. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15835. // this.resetTextureCache();
  15836. this._internalTexturesCache.push(texture);
  15837. return texture;
  15838. };
  15839. /**
  15840. * Create a multi render target texture
  15841. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15842. * @param size defines the size of the texture
  15843. * @param options defines the creation options
  15844. * @returns the cube texture as an InternalTexture
  15845. */
  15846. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15847. var generateMipMaps = false;
  15848. var generateDepthBuffer = true;
  15849. var generateStencilBuffer = false;
  15850. var generateDepthTexture = false;
  15851. var textureCount = 1;
  15852. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15853. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15854. var types = new Array();
  15855. var samplingModes = new Array();
  15856. if (options !== undefined) {
  15857. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15858. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15859. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15860. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15861. textureCount = options.textureCount || 1;
  15862. if (options.types) {
  15863. types = options.types;
  15864. }
  15865. if (options.samplingModes) {
  15866. samplingModes = options.samplingModes;
  15867. }
  15868. }
  15869. var gl = this._gl;
  15870. // Create the framebuffer
  15871. var framebuffer = gl.createFramebuffer();
  15872. this.bindUnboundFramebuffer(framebuffer);
  15873. var width = size.width || size;
  15874. var height = size.height || size;
  15875. var textures = [];
  15876. var attachments = [];
  15877. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15878. for (var i = 0; i < textureCount; i++) {
  15879. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15880. var type = types[i] || defaultType;
  15881. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15882. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15883. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15884. }
  15885. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15886. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15887. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15888. }
  15889. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15890. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15891. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15892. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15893. }
  15894. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15895. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15896. textures.push(texture);
  15897. attachments.push(attachment);
  15898. gl.activeTexture(gl["TEXTURE" + i]);
  15899. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15904. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15905. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15906. if (generateMipMaps) {
  15907. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15908. }
  15909. // Unbind
  15910. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15911. texture._framebuffer = framebuffer;
  15912. texture._depthStencilBuffer = depthStencilBuffer;
  15913. texture.baseWidth = width;
  15914. texture.baseHeight = height;
  15915. texture.width = width;
  15916. texture.height = height;
  15917. texture.isReady = true;
  15918. texture.samples = 1;
  15919. texture.generateMipMaps = generateMipMaps;
  15920. texture.samplingMode = samplingMode;
  15921. texture.type = type;
  15922. texture._generateDepthBuffer = generateDepthBuffer;
  15923. texture._generateStencilBuffer = generateStencilBuffer;
  15924. texture._attachments = attachments;
  15925. this._internalTexturesCache.push(texture);
  15926. }
  15927. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15928. // Depth texture
  15929. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15930. gl.activeTexture(gl.TEXTURE0);
  15931. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15936. 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);
  15937. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15938. depthTexture._framebuffer = framebuffer;
  15939. depthTexture.baseWidth = width;
  15940. depthTexture.baseHeight = height;
  15941. depthTexture.width = width;
  15942. depthTexture.height = height;
  15943. depthTexture.isReady = true;
  15944. depthTexture.samples = 1;
  15945. depthTexture.generateMipMaps = generateMipMaps;
  15946. depthTexture.samplingMode = gl.NEAREST;
  15947. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15948. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15949. textures.push(depthTexture);
  15950. this._internalTexturesCache.push(depthTexture);
  15951. }
  15952. gl.drawBuffers(attachments);
  15953. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15954. this.bindUnboundFramebuffer(null);
  15955. this.resetTextureCache();
  15956. return textures;
  15957. };
  15958. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15959. if (samples === void 0) { samples = 1; }
  15960. var depthStencilBuffer = null;
  15961. var gl = this._gl;
  15962. // Create the depth/stencil buffer
  15963. if (generateStencilBuffer) {
  15964. depthStencilBuffer = gl.createRenderbuffer();
  15965. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15966. if (samples > 1) {
  15967. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15968. }
  15969. else {
  15970. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15971. }
  15972. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15973. }
  15974. else if (generateDepthBuffer) {
  15975. depthStencilBuffer = gl.createRenderbuffer();
  15976. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15977. if (samples > 1) {
  15978. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15979. }
  15980. else {
  15981. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15982. }
  15983. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15984. }
  15985. return depthStencilBuffer;
  15986. };
  15987. /**
  15988. * Updates the sample count of a render target texture
  15989. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15990. * @param texture defines the texture to update
  15991. * @param samples defines the sample count to set
  15992. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15993. */
  15994. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15995. if (this.webGLVersion < 2 || !texture) {
  15996. return 1;
  15997. }
  15998. if (texture.samples === samples) {
  15999. return samples;
  16000. }
  16001. var gl = this._gl;
  16002. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16003. // Dispose previous render buffers
  16004. if (texture._depthStencilBuffer) {
  16005. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16006. texture._depthStencilBuffer = null;
  16007. }
  16008. if (texture._MSAAFramebuffer) {
  16009. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16010. texture._MSAAFramebuffer = null;
  16011. }
  16012. if (texture._MSAARenderBuffer) {
  16013. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16014. texture._MSAARenderBuffer = null;
  16015. }
  16016. if (samples > 1) {
  16017. var framebuffer = gl.createFramebuffer();
  16018. if (!framebuffer) {
  16019. throw new Error("Unable to create multi sampled framebuffer");
  16020. }
  16021. texture._MSAAFramebuffer = framebuffer;
  16022. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16023. var colorRenderbuffer = gl.createRenderbuffer();
  16024. if (!colorRenderbuffer) {
  16025. throw new Error("Unable to create multi sampled framebuffer");
  16026. }
  16027. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16028. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16029. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16030. texture._MSAARenderBuffer = colorRenderbuffer;
  16031. }
  16032. else {
  16033. this.bindUnboundFramebuffer(texture._framebuffer);
  16034. }
  16035. texture.samples = samples;
  16036. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16037. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16038. this.bindUnboundFramebuffer(null);
  16039. return samples;
  16040. };
  16041. /**
  16042. * Update the sample count for a given multiple render target texture
  16043. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16044. * @param textures defines the textures to update
  16045. * @param samples defines the sample count to set
  16046. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16047. */
  16048. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16049. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16050. return 1;
  16051. }
  16052. if (textures[0].samples === samples) {
  16053. return samples;
  16054. }
  16055. var gl = this._gl;
  16056. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16057. // Dispose previous render buffers
  16058. if (textures[0]._depthStencilBuffer) {
  16059. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16060. textures[0]._depthStencilBuffer = null;
  16061. }
  16062. if (textures[0]._MSAAFramebuffer) {
  16063. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16064. textures[0]._MSAAFramebuffer = null;
  16065. }
  16066. for (var i = 0; i < textures.length; i++) {
  16067. if (textures[i]._MSAARenderBuffer) {
  16068. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16069. textures[i]._MSAARenderBuffer = null;
  16070. }
  16071. }
  16072. if (samples > 1) {
  16073. var framebuffer = gl.createFramebuffer();
  16074. if (!framebuffer) {
  16075. throw new Error("Unable to create multi sampled framebuffer");
  16076. }
  16077. this.bindUnboundFramebuffer(framebuffer);
  16078. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16079. var attachments = [];
  16080. for (var i = 0; i < textures.length; i++) {
  16081. var texture = textures[i];
  16082. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16083. var colorRenderbuffer = gl.createRenderbuffer();
  16084. if (!colorRenderbuffer) {
  16085. throw new Error("Unable to create multi sampled framebuffer");
  16086. }
  16087. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16088. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16089. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16090. texture._MSAAFramebuffer = framebuffer;
  16091. texture._MSAARenderBuffer = colorRenderbuffer;
  16092. texture.samples = samples;
  16093. texture._depthStencilBuffer = depthStencilBuffer;
  16094. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16095. attachments.push(attachment);
  16096. }
  16097. gl.drawBuffers(attachments);
  16098. }
  16099. else {
  16100. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16101. }
  16102. this.bindUnboundFramebuffer(null);
  16103. return samples;
  16104. };
  16105. /** @hidden */
  16106. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16107. if (faceIndex === void 0) { faceIndex = 0; }
  16108. if (lod === void 0) { lod = 0; }
  16109. var gl = this._gl;
  16110. var target = gl.TEXTURE_2D;
  16111. if (texture.isCube) {
  16112. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16113. }
  16114. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16115. };
  16116. /** @hidden */
  16117. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16118. if (faceIndex === void 0) { faceIndex = 0; }
  16119. if (lod === void 0) { lod = 0; }
  16120. var gl = this._gl;
  16121. var textureType = this._getWebGLTextureType(texture.type);
  16122. var format = this._getInternalFormat(texture.format);
  16123. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16124. this._unpackFlipY(texture.invertY);
  16125. var target = gl.TEXTURE_2D;
  16126. if (texture.isCube) {
  16127. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16128. }
  16129. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16130. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16131. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16132. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16133. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16134. };
  16135. /** @hidden */
  16136. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16137. if (faceIndex === void 0) { faceIndex = 0; }
  16138. if (lod === void 0) { lod = 0; }
  16139. var gl = this._gl;
  16140. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16141. this._bindTextureDirectly(bindTarget, texture, true);
  16142. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16143. this._bindTextureDirectly(bindTarget, null, true);
  16144. };
  16145. /** @hidden */
  16146. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16147. if (faceIndex === void 0) { faceIndex = 0; }
  16148. if (lod === void 0) { lod = 0; }
  16149. var gl = this._gl;
  16150. var textureType = this._getWebGLTextureType(texture.type);
  16151. var format = this._getInternalFormat(texture.format);
  16152. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16153. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16154. this._bindTextureDirectly(bindTarget, texture, true);
  16155. this._unpackFlipY(texture.invertY);
  16156. var target = gl.TEXTURE_2D;
  16157. if (texture.isCube) {
  16158. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16159. }
  16160. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16161. this._bindTextureDirectly(bindTarget, null, true);
  16162. };
  16163. /**
  16164. * Creates a new render target cube texture
  16165. * @param size defines the size of the texture
  16166. * @param options defines the options used to create the texture
  16167. * @returns a new render target cube texture stored in an InternalTexture
  16168. */
  16169. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16170. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16171. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16172. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16173. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16174. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16175. }
  16176. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16177. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16178. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16179. }
  16180. var gl = this._gl;
  16181. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16182. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16183. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16184. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16185. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16186. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16187. }
  16188. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16192. for (var face = 0; face < 6; face++) {
  16193. 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);
  16194. }
  16195. // Create the framebuffer
  16196. var framebuffer = gl.createFramebuffer();
  16197. this.bindUnboundFramebuffer(framebuffer);
  16198. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16199. // MipMaps
  16200. if (fullOptions.generateMipMaps) {
  16201. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16202. }
  16203. // Unbind
  16204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16205. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16206. this.bindUnboundFramebuffer(null);
  16207. texture._framebuffer = framebuffer;
  16208. texture.width = size;
  16209. texture.height = size;
  16210. texture.isReady = true;
  16211. texture.isCube = true;
  16212. texture.samples = 1;
  16213. texture.generateMipMaps = fullOptions.generateMipMaps;
  16214. texture.samplingMode = fullOptions.samplingMode;
  16215. texture.type = fullOptions.type;
  16216. texture.format = fullOptions.format;
  16217. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16218. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16219. this._internalTexturesCache.push(texture);
  16220. return texture;
  16221. };
  16222. /**
  16223. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16224. * @param rootUrl defines the url where the file to load is located
  16225. * @param scene defines the current scene
  16226. * @param lodScale defines scale to apply to the mip map selection
  16227. * @param lodOffset defines offset to apply to the mip map selection
  16228. * @param onLoad defines an optional callback raised when the texture is loaded
  16229. * @param onError defines an optional callback raised if there is an issue to load the texture
  16230. * @param format defines the format of the data
  16231. * @param forcedExtension defines the extension to use to pick the right loader
  16232. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16233. * @returns the cube texture as an InternalTexture
  16234. */
  16235. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16236. var _this = this;
  16237. if (onLoad === void 0) { onLoad = null; }
  16238. if (onError === void 0) { onError = null; }
  16239. if (forcedExtension === void 0) { forcedExtension = null; }
  16240. if (createPolynomials === void 0) { createPolynomials = true; }
  16241. var callback = function (loadData) {
  16242. if (!loadData) {
  16243. if (onLoad) {
  16244. onLoad(null);
  16245. }
  16246. return;
  16247. }
  16248. var texture = loadData.texture;
  16249. if (!createPolynomials) {
  16250. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16251. }
  16252. else if (loadData.info.sphericalPolynomial) {
  16253. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16254. }
  16255. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16256. if (_this._caps.textureLOD) {
  16257. // Do not add extra process if texture lod is supported.
  16258. if (onLoad) {
  16259. onLoad(texture);
  16260. }
  16261. return;
  16262. }
  16263. var mipSlices = 3;
  16264. var gl = _this._gl;
  16265. var width = loadData.width;
  16266. if (!width) {
  16267. return;
  16268. }
  16269. var textures = [];
  16270. for (var i = 0; i < mipSlices; i++) {
  16271. //compute LOD from even spacing in smoothness (matching shader calculation)
  16272. var smoothness = i / (mipSlices - 1);
  16273. var roughness = 1 - smoothness;
  16274. var minLODIndex = lodOffset; // roughness = 0
  16275. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16276. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16277. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16278. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16279. glTextureFromLod.type = texture.type;
  16280. glTextureFromLod.format = texture.format;
  16281. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16282. glTextureFromLod.height = glTextureFromLod.width;
  16283. glTextureFromLod.isCube = true;
  16284. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16289. if (loadData.isDDS) {
  16290. var info = loadData.info;
  16291. var data = loadData.data;
  16292. _this._unpackFlipY(info.isCompressed);
  16293. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16294. }
  16295. else {
  16296. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16297. }
  16298. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16299. // Wrap in a base texture for easy binding.
  16300. var lodTexture = new BABYLON.BaseTexture(scene);
  16301. lodTexture.isCube = true;
  16302. lodTexture._texture = glTextureFromLod;
  16303. glTextureFromLod.isReady = true;
  16304. textures.push(lodTexture);
  16305. }
  16306. texture._lodTextureHigh = textures[2];
  16307. texture._lodTextureMid = textures[1];
  16308. texture._lodTextureLow = textures[0];
  16309. if (onLoad) {
  16310. onLoad(texture);
  16311. }
  16312. };
  16313. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16314. };
  16315. /**
  16316. * Creates a cube texture
  16317. * @param rootUrl defines the url where the files to load is located
  16318. * @param scene defines the current scene
  16319. * @param files defines the list of files to load (1 per face)
  16320. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16321. * @param onLoad defines an optional callback raised when the texture is loaded
  16322. * @param onError defines an optional callback raised if there is an issue to load the texture
  16323. * @param format defines the format of the data
  16324. * @param forcedExtension defines the extension to use to pick the right loader
  16325. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16326. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16327. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16328. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16329. * @returns the cube texture as an InternalTexture
  16330. */
  16331. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16332. var _this = this;
  16333. if (onLoad === void 0) { onLoad = null; }
  16334. if (onError === void 0) { onError = null; }
  16335. if (forcedExtension === void 0) { forcedExtension = null; }
  16336. if (createPolynomials === void 0) { createPolynomials = false; }
  16337. if (lodScale === void 0) { lodScale = 0; }
  16338. if (lodOffset === void 0) { lodOffset = 0; }
  16339. if (fallback === void 0) { fallback = null; }
  16340. var gl = this._gl;
  16341. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16342. texture.isCube = true;
  16343. texture.url = rootUrl;
  16344. texture.generateMipMaps = !noMipmap;
  16345. texture._lodGenerationScale = lodScale;
  16346. texture._lodGenerationOffset = lodOffset;
  16347. if (!this._doNotHandleContextLost) {
  16348. texture._extension = forcedExtension;
  16349. texture._files = files;
  16350. }
  16351. var lastDot = rootUrl.lastIndexOf('.');
  16352. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16353. var loader = null;
  16354. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16355. var availableLoader = _a[_i];
  16356. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16357. loader = availableLoader;
  16358. break;
  16359. }
  16360. }
  16361. var onInternalError = function (request, exception) {
  16362. if (loader) {
  16363. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16364. if (fallbackUrl) {
  16365. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16366. }
  16367. }
  16368. if (onError && request) {
  16369. onError(request.status + " " + request.statusText, exception);
  16370. }
  16371. };
  16372. if (loader) {
  16373. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16374. var onloaddata = function (data) {
  16375. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16376. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16377. };
  16378. if (files && files.length === 6) {
  16379. if (loader.supportCascades) {
  16380. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16381. }
  16382. else if (onError) {
  16383. onError("Textures type does not support cascades.");
  16384. }
  16385. }
  16386. else {
  16387. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16388. }
  16389. }
  16390. else {
  16391. if (!files) {
  16392. throw new Error("Cannot load cubemap because files were not defined");
  16393. }
  16394. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16395. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16396. var height = width;
  16397. _this._prepareWorkingCanvas();
  16398. if (!_this._workingCanvas || !_this._workingContext) {
  16399. return;
  16400. }
  16401. _this._workingCanvas.width = width;
  16402. _this._workingCanvas.height = height;
  16403. var faces = [
  16404. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16405. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16406. ];
  16407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16408. _this._unpackFlipY(false);
  16409. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16410. for (var index = 0; index < faces.length; index++) {
  16411. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16412. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16413. }
  16414. if (!noMipmap) {
  16415. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16416. }
  16417. _this._setCubeMapTextureParams(!noMipmap);
  16418. texture.width = width;
  16419. texture.height = height;
  16420. texture.isReady = true;
  16421. if (format) {
  16422. texture.format = format;
  16423. }
  16424. texture.onLoadedObservable.notifyObservers(texture);
  16425. texture.onLoadedObservable.clear();
  16426. if (onLoad) {
  16427. onLoad();
  16428. }
  16429. }, files, onError);
  16430. }
  16431. this._internalTexturesCache.push(texture);
  16432. return texture;
  16433. };
  16434. /**
  16435. * @hidden
  16436. */
  16437. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16438. var gl = this._gl;
  16439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16442. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16443. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16444. // this.resetTextureCache();
  16445. };
  16446. /**
  16447. * Update a raw cube texture
  16448. * @param texture defines the texture to udpdate
  16449. * @param data defines the data to store
  16450. * @param format defines the data format
  16451. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16452. * @param invertY defines if data must be stored with Y axis inverted
  16453. * @param compression defines the compression used (null by default)
  16454. * @param level defines which level of the texture to update
  16455. */
  16456. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16457. if (compression === void 0) { compression = null; }
  16458. if (level === void 0) { level = 0; }
  16459. texture._bufferViewArray = data;
  16460. texture.format = format;
  16461. texture.type = type;
  16462. texture.invertY = invertY;
  16463. texture._compression = compression;
  16464. var gl = this._gl;
  16465. var textureType = this._getWebGLTextureType(type);
  16466. var internalFormat = this._getInternalFormat(format);
  16467. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16468. var needConversion = false;
  16469. if (internalFormat === gl.RGB) {
  16470. internalFormat = gl.RGBA;
  16471. needConversion = true;
  16472. }
  16473. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16474. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16475. if (texture.width % 4 !== 0) {
  16476. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16477. }
  16478. // Data are known to be in +X +Y +Z -X -Y -Z
  16479. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16480. var faceData = data[faceIndex];
  16481. if (compression) {
  16482. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16483. }
  16484. else {
  16485. if (needConversion) {
  16486. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16487. }
  16488. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16489. }
  16490. }
  16491. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16492. if (isPot && texture.generateMipMaps && level === 0) {
  16493. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16494. }
  16495. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16496. // this.resetTextureCache();
  16497. texture.isReady = true;
  16498. };
  16499. /**
  16500. * Creates a new raw cube texture
  16501. * @param data defines the array of data to use to create each face
  16502. * @param size defines the size of the textures
  16503. * @param format defines the format of the data
  16504. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16505. * @param generateMipMaps defines if the engine should generate the mip levels
  16506. * @param invertY defines if data must be stored with Y axis inverted
  16507. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16508. * @param compression defines the compression used (null by default)
  16509. * @returns the cube texture as an InternalTexture
  16510. */
  16511. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16512. if (compression === void 0) { compression = null; }
  16513. var gl = this._gl;
  16514. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16515. texture.isCube = true;
  16516. texture.format = format;
  16517. texture.type = type;
  16518. if (!this._doNotHandleContextLost) {
  16519. texture._bufferViewArray = data;
  16520. }
  16521. var textureType = this._getWebGLTextureType(type);
  16522. var internalFormat = this._getInternalFormat(format);
  16523. if (internalFormat === gl.RGB) {
  16524. internalFormat = gl.RGBA;
  16525. }
  16526. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16527. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16528. generateMipMaps = false;
  16529. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16530. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16531. }
  16532. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16533. generateMipMaps = false;
  16534. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16535. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16536. }
  16537. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16538. generateMipMaps = false;
  16539. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16540. }
  16541. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16542. generateMipMaps = false;
  16543. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16544. }
  16545. var width = size;
  16546. var height = width;
  16547. texture.width = width;
  16548. texture.height = height;
  16549. // Double check on POT to generate Mips.
  16550. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16551. if (!isPot) {
  16552. generateMipMaps = false;
  16553. }
  16554. // Upload data if needed. The texture won't be ready until then.
  16555. if (data) {
  16556. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16557. }
  16558. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16559. // Filters
  16560. if (data && generateMipMaps) {
  16561. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16562. }
  16563. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16568. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16569. texture.generateMipMaps = generateMipMaps;
  16570. return texture;
  16571. };
  16572. /**
  16573. * Creates a new raw cube texture from a specified url
  16574. * @param url defines the url where the data is located
  16575. * @param scene defines the current scene
  16576. * @param size defines the size of the textures
  16577. * @param format defines the format of the data
  16578. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16579. * @param noMipmap defines if the engine should avoid generating the mip levels
  16580. * @param callback defines a callback used to extract texture data from loaded data
  16581. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16582. * @param onLoad defines a callback called when texture is loaded
  16583. * @param onError defines a callback called if there is an error
  16584. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16585. * @param invertY defines if data must be stored with Y axis inverted
  16586. * @returns the cube texture as an InternalTexture
  16587. */
  16588. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16589. var _this = this;
  16590. if (onLoad === void 0) { onLoad = null; }
  16591. if (onError === void 0) { onError = null; }
  16592. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16593. if (invertY === void 0) { invertY = false; }
  16594. var gl = this._gl;
  16595. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16596. scene._addPendingData(texture);
  16597. texture.url = url;
  16598. this._internalTexturesCache.push(texture);
  16599. var onerror = function (request, exception) {
  16600. scene._removePendingData(texture);
  16601. if (onError && request) {
  16602. onError(request.status + " " + request.statusText, exception);
  16603. }
  16604. };
  16605. var internalCallback = function (data) {
  16606. var width = texture.width;
  16607. var faceDataArrays = callback(data);
  16608. if (!faceDataArrays) {
  16609. return;
  16610. }
  16611. if (mipmapGenerator) {
  16612. var textureType = _this._getWebGLTextureType(type);
  16613. var internalFormat = _this._getInternalFormat(format);
  16614. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16615. var needConversion = false;
  16616. if (internalFormat === gl.RGB) {
  16617. internalFormat = gl.RGBA;
  16618. needConversion = true;
  16619. }
  16620. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16621. _this._unpackFlipY(false);
  16622. var mipData = mipmapGenerator(faceDataArrays);
  16623. for (var level = 0; level < mipData.length; level++) {
  16624. var mipSize = width >> level;
  16625. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16626. var mipFaceData = mipData[level][faceIndex];
  16627. if (needConversion) {
  16628. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16629. }
  16630. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16631. }
  16632. }
  16633. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16634. }
  16635. else {
  16636. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16637. }
  16638. texture.isReady = true;
  16639. // this.resetTextureCache();
  16640. scene._removePendingData(texture);
  16641. if (onLoad) {
  16642. onLoad();
  16643. }
  16644. };
  16645. this._loadFile(url, function (data) {
  16646. internalCallback(data);
  16647. }, undefined, scene.database, true, onerror);
  16648. return texture;
  16649. };
  16650. ;
  16651. /**
  16652. * Update a raw 3D texture
  16653. * @param texture defines the texture to update
  16654. * @param data defines the data to store
  16655. * @param format defines the data format
  16656. * @param invertY defines if data must be stored with Y axis inverted
  16657. * @param compression defines the used compression (can be null)
  16658. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16659. */
  16660. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16661. if (compression === void 0) { compression = null; }
  16662. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16663. var internalType = this._getWebGLTextureType(textureType);
  16664. var internalFormat = this._getInternalFormat(format);
  16665. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16666. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16667. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16668. if (!this._doNotHandleContextLost) {
  16669. texture._bufferView = data;
  16670. texture.format = format;
  16671. texture.invertY = invertY;
  16672. texture._compression = compression;
  16673. }
  16674. if (texture.width % 4 !== 0) {
  16675. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16676. }
  16677. if (compression && data) {
  16678. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16679. }
  16680. else {
  16681. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16682. }
  16683. if (texture.generateMipMaps) {
  16684. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16685. }
  16686. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16687. // this.resetTextureCache();
  16688. texture.isReady = true;
  16689. };
  16690. /**
  16691. * Creates a new raw 3D texture
  16692. * @param data defines the data used to create the texture
  16693. * @param width defines the width of the texture
  16694. * @param height defines the height of the texture
  16695. * @param depth defines the depth of the texture
  16696. * @param format defines the format of the texture
  16697. * @param generateMipMaps defines if the engine must generate mip levels
  16698. * @param invertY defines if data must be stored with Y axis inverted
  16699. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16700. * @param compression defines the compressed used (can be null)
  16701. * @param textureType defines the compressed used (can be null)
  16702. * @returns a new raw 3D texture (stored in an InternalTexture)
  16703. */
  16704. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16705. if (compression === void 0) { compression = null; }
  16706. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16707. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16708. texture.baseWidth = width;
  16709. texture.baseHeight = height;
  16710. texture.baseDepth = depth;
  16711. texture.width = width;
  16712. texture.height = height;
  16713. texture.depth = depth;
  16714. texture.format = format;
  16715. texture.type = textureType;
  16716. texture.generateMipMaps = generateMipMaps;
  16717. texture.samplingMode = samplingMode;
  16718. texture.is3D = true;
  16719. if (!this._doNotHandleContextLost) {
  16720. texture._bufferView = data;
  16721. }
  16722. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16723. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16724. // Filters
  16725. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16726. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16727. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16728. if (generateMipMaps) {
  16729. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16730. }
  16731. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16732. this._internalTexturesCache.push(texture);
  16733. return texture;
  16734. };
  16735. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16736. var gl = this._gl;
  16737. if (!gl) {
  16738. return;
  16739. }
  16740. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16743. if (!noMipmap && !isCompressed) {
  16744. gl.generateMipmap(gl.TEXTURE_2D);
  16745. }
  16746. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16747. // this.resetTextureCache();
  16748. if (scene) {
  16749. scene._removePendingData(texture);
  16750. }
  16751. texture.onLoadedObservable.notifyObservers(texture);
  16752. texture.onLoadedObservable.clear();
  16753. };
  16754. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16755. var _this = this;
  16756. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16757. var maxTextureSize = this.getCaps().maxTextureSize;
  16758. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16759. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16760. var gl = this._gl;
  16761. if (!gl) {
  16762. return;
  16763. }
  16764. if (!texture._webGLTexture) {
  16765. // this.resetTextureCache();
  16766. if (scene) {
  16767. scene._removePendingData(texture);
  16768. }
  16769. return;
  16770. }
  16771. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16772. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16773. texture.baseWidth = width;
  16774. texture.baseHeight = height;
  16775. texture.width = potWidth;
  16776. texture.height = potHeight;
  16777. texture.isReady = true;
  16778. if (processFunction(potWidth, potHeight, function () {
  16779. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16780. })) {
  16781. // Returning as texture needs extra async steps
  16782. return;
  16783. }
  16784. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16785. };
  16786. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16787. // Create new RGBA data container.
  16788. var rgbaData;
  16789. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16790. rgbaData = new Float32Array(width * height * 4);
  16791. }
  16792. else {
  16793. rgbaData = new Uint32Array(width * height * 4);
  16794. }
  16795. // Convert each pixel.
  16796. for (var x = 0; x < width; x++) {
  16797. for (var y = 0; y < height; y++) {
  16798. var index = (y * width + x) * 3;
  16799. var newIndex = (y * width + x) * 4;
  16800. // Map Old Value to new value.
  16801. rgbaData[newIndex + 0] = rgbData[index + 0];
  16802. rgbaData[newIndex + 1] = rgbData[index + 1];
  16803. rgbaData[newIndex + 2] = rgbData[index + 2];
  16804. // Add fully opaque alpha channel.
  16805. rgbaData[newIndex + 3] = 1;
  16806. }
  16807. }
  16808. return rgbaData;
  16809. };
  16810. /** @hidden */
  16811. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16812. var gl = this._gl;
  16813. if (texture._framebuffer) {
  16814. gl.deleteFramebuffer(texture._framebuffer);
  16815. texture._framebuffer = null;
  16816. }
  16817. if (texture._depthStencilBuffer) {
  16818. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16819. texture._depthStencilBuffer = null;
  16820. }
  16821. if (texture._MSAAFramebuffer) {
  16822. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16823. texture._MSAAFramebuffer = null;
  16824. }
  16825. if (texture._MSAARenderBuffer) {
  16826. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16827. texture._MSAARenderBuffer = null;
  16828. }
  16829. };
  16830. /** @hidden */
  16831. Engine.prototype._releaseTexture = function (texture) {
  16832. var gl = this._gl;
  16833. this._releaseFramebufferObjects(texture);
  16834. gl.deleteTexture(texture._webGLTexture);
  16835. // Unbind channels
  16836. this.unbindAllTextures();
  16837. var index = this._internalTexturesCache.indexOf(texture);
  16838. if (index !== -1) {
  16839. this._internalTexturesCache.splice(index, 1);
  16840. }
  16841. // Integrated fixed lod samplers.
  16842. if (texture._lodTextureHigh) {
  16843. texture._lodTextureHigh.dispose();
  16844. }
  16845. if (texture._lodTextureMid) {
  16846. texture._lodTextureMid.dispose();
  16847. }
  16848. if (texture._lodTextureLow) {
  16849. texture._lodTextureLow.dispose();
  16850. }
  16851. // Set output texture of post process to null if the texture has been released/disposed
  16852. this.scenes.forEach(function (scene) {
  16853. scene.postProcesses.forEach(function (postProcess) {
  16854. if (postProcess._outputTexture == texture) {
  16855. postProcess._outputTexture = null;
  16856. }
  16857. });
  16858. scene.cameras.forEach(function (camera) {
  16859. camera._postProcesses.forEach(function (postProcess) {
  16860. if (postProcess) {
  16861. if (postProcess._outputTexture == texture) {
  16862. postProcess._outputTexture = null;
  16863. }
  16864. }
  16865. });
  16866. });
  16867. });
  16868. };
  16869. Engine.prototype.setProgram = function (program) {
  16870. if (this._currentProgram !== program) {
  16871. this._gl.useProgram(program);
  16872. this._currentProgram = program;
  16873. }
  16874. };
  16875. /**
  16876. * Binds an effect to the webGL context
  16877. * @param effect defines the effect to bind
  16878. */
  16879. Engine.prototype.bindSamplers = function (effect) {
  16880. this.setProgram(effect.getProgram());
  16881. var samplers = effect.getSamplers();
  16882. for (var index = 0; index < samplers.length; index++) {
  16883. var uniform = effect.getUniform(samplers[index]);
  16884. if (uniform) {
  16885. this._boundUniforms[index] = uniform;
  16886. }
  16887. }
  16888. this._currentEffect = null;
  16889. };
  16890. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16891. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16892. return;
  16893. }
  16894. // Remove
  16895. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16896. // Bind last to it
  16897. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16898. // Bind to dummy
  16899. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16900. };
  16901. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16902. if (!internalTexture) {
  16903. return -1;
  16904. }
  16905. internalTexture._initialSlot = channel;
  16906. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16907. if (channel !== internalTexture._designatedSlot) {
  16908. this._textureCollisions.addCount(1, false);
  16909. }
  16910. }
  16911. else {
  16912. if (channel !== internalTexture._designatedSlot) {
  16913. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16914. return internalTexture._designatedSlot;
  16915. }
  16916. else {
  16917. // No slot for this texture, let's pick a new one (if we find a free slot)
  16918. if (this._nextFreeTextureSlots.length) {
  16919. return this._nextFreeTextureSlots[0];
  16920. }
  16921. // We need to recycle the oldest bound texture, sorry.
  16922. this._textureCollisions.addCount(1, false);
  16923. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16924. }
  16925. }
  16926. }
  16927. return channel;
  16928. };
  16929. Engine.prototype._linkTrackers = function (previous, next) {
  16930. previous.next = next;
  16931. next.previous = previous;
  16932. };
  16933. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16934. var currentSlot = internalTexture._designatedSlot;
  16935. if (currentSlot === -1) {
  16936. return -1;
  16937. }
  16938. internalTexture._designatedSlot = -1;
  16939. if (this.disableTextureBindingOptimization) {
  16940. return -1;
  16941. }
  16942. // Remove from bound list
  16943. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16944. // Free the slot
  16945. this._boundTexturesCache[currentSlot] = null;
  16946. this._nextFreeTextureSlots.push(currentSlot);
  16947. return currentSlot;
  16948. };
  16949. Engine.prototype._activateCurrentTexture = function () {
  16950. if (this._currentTextureChannel !== this._activeChannel) {
  16951. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16952. this._currentTextureChannel = this._activeChannel;
  16953. }
  16954. };
  16955. /** @hidden */
  16956. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16957. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16958. if (force === void 0) { force = false; }
  16959. var wasPreviouslyBound = false;
  16960. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16961. this._activeChannel = texture._designatedSlot;
  16962. }
  16963. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16964. var isTextureForRendering = texture && texture._initialSlot > -1;
  16965. if (currentTextureBound !== texture || force) {
  16966. if (currentTextureBound) {
  16967. this._removeDesignatedSlot(currentTextureBound);
  16968. }
  16969. this._activateCurrentTexture();
  16970. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16971. this._boundTexturesCache[this._activeChannel] = texture;
  16972. if (texture) {
  16973. if (!this.disableTextureBindingOptimization) {
  16974. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16975. if (slotIndex > -1) {
  16976. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16977. }
  16978. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16979. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16980. }
  16981. texture._designatedSlot = this._activeChannel;
  16982. }
  16983. }
  16984. else if (forTextureDataUpdate) {
  16985. wasPreviouslyBound = true;
  16986. this._activateCurrentTexture();
  16987. }
  16988. if (isTextureForRendering && !forTextureDataUpdate) {
  16989. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16990. }
  16991. return wasPreviouslyBound;
  16992. };
  16993. /** @hidden */
  16994. Engine.prototype._bindTexture = function (channel, texture) {
  16995. if (channel < 0) {
  16996. return;
  16997. }
  16998. if (texture) {
  16999. channel = this._getCorrectTextureChannel(channel, texture);
  17000. }
  17001. this._activeChannel = channel;
  17002. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17003. };
  17004. /**
  17005. * Sets a texture to the webGL context from a postprocess
  17006. * @param channel defines the channel to use
  17007. * @param postProcess defines the source postprocess
  17008. */
  17009. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17010. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17011. };
  17012. /**
  17013. * Binds the output of the passed in post process to the texture channel specified
  17014. * @param channel The channel the texture should be bound to
  17015. * @param postProcess The post process which's output should be bound
  17016. */
  17017. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17018. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17019. };
  17020. /**
  17021. * Unbind all textures from the webGL context
  17022. */
  17023. Engine.prototype.unbindAllTextures = function () {
  17024. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17025. this._activeChannel = channel;
  17026. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17027. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17028. if (this.webGLVersion > 1) {
  17029. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17030. }
  17031. }
  17032. };
  17033. /**
  17034. * Sets a texture to the according uniform.
  17035. * @param channel The texture channel
  17036. * @param uniform The uniform to set
  17037. * @param texture The texture to apply
  17038. */
  17039. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17040. if (channel < 0) {
  17041. return;
  17042. }
  17043. if (uniform) {
  17044. this._boundUniforms[channel] = uniform;
  17045. }
  17046. this._setTexture(channel, texture);
  17047. };
  17048. /**
  17049. * Sets a depth stencil texture from a render target to the according uniform.
  17050. * @param channel The texture channel
  17051. * @param uniform The uniform to set
  17052. * @param texture The render target texture containing the depth stencil texture to apply
  17053. */
  17054. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17055. if (channel < 0) {
  17056. return;
  17057. }
  17058. if (uniform) {
  17059. this._boundUniforms[channel] = uniform;
  17060. }
  17061. if (!texture || !texture.depthStencilTexture) {
  17062. this._setTexture(channel, null);
  17063. }
  17064. else {
  17065. this._setTexture(channel, texture, false, true);
  17066. }
  17067. };
  17068. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17069. var uniform = this._boundUniforms[sourceSlot];
  17070. if (uniform._currentState === destination) {
  17071. return;
  17072. }
  17073. this._gl.uniform1i(uniform, destination);
  17074. uniform._currentState = destination;
  17075. };
  17076. Engine.prototype._getTextureWrapMode = function (mode) {
  17077. switch (mode) {
  17078. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17079. return this._gl.REPEAT;
  17080. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17081. return this._gl.CLAMP_TO_EDGE;
  17082. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17083. return this._gl.MIRRORED_REPEAT;
  17084. }
  17085. return this._gl.REPEAT;
  17086. };
  17087. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17088. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17089. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17090. // Not ready?
  17091. if (!texture) {
  17092. if (this._boundTexturesCache[channel] != null) {
  17093. this._activeChannel = channel;
  17094. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17095. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17096. if (this.webGLVersion > 1) {
  17097. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17098. }
  17099. }
  17100. return false;
  17101. }
  17102. // Video
  17103. if (texture.video) {
  17104. this._activeChannel = channel;
  17105. texture.update();
  17106. }
  17107. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17108. texture.delayLoad();
  17109. return false;
  17110. }
  17111. var internalTexture;
  17112. if (depthStencilTexture) {
  17113. internalTexture = texture.depthStencilTexture;
  17114. }
  17115. else if (texture.isReady()) {
  17116. internalTexture = texture.getInternalTexture();
  17117. }
  17118. else if (texture.isCube) {
  17119. internalTexture = this.emptyCubeTexture;
  17120. }
  17121. else if (texture.is3D) {
  17122. internalTexture = this.emptyTexture3D;
  17123. }
  17124. else {
  17125. internalTexture = this.emptyTexture;
  17126. }
  17127. if (!isPartOfTextureArray) {
  17128. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17129. }
  17130. var needToBind = true;
  17131. if (this._boundTexturesCache[channel] === internalTexture) {
  17132. this._moveBoundTextureOnTop(internalTexture);
  17133. if (!isPartOfTextureArray) {
  17134. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17135. }
  17136. needToBind = false;
  17137. }
  17138. this._activeChannel = channel;
  17139. if (internalTexture && internalTexture.is3D) {
  17140. if (needToBind) {
  17141. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17142. }
  17143. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17144. internalTexture._cachedWrapU = texture.wrapU;
  17145. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17146. }
  17147. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17148. internalTexture._cachedWrapV = texture.wrapV;
  17149. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17150. }
  17151. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17152. internalTexture._cachedWrapR = texture.wrapR;
  17153. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17154. }
  17155. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17156. }
  17157. else if (internalTexture && internalTexture.isCube) {
  17158. if (needToBind) {
  17159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17160. }
  17161. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17162. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17163. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17164. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17165. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17166. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17167. }
  17168. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17169. }
  17170. else {
  17171. if (needToBind) {
  17172. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17173. }
  17174. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17175. internalTexture._cachedWrapU = texture.wrapU;
  17176. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17177. }
  17178. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17179. internalTexture._cachedWrapV = texture.wrapV;
  17180. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17181. }
  17182. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17183. }
  17184. return true;
  17185. };
  17186. /**
  17187. * Sets an array of texture to the webGL context
  17188. * @param channel defines the channel where the texture array must be set
  17189. * @param uniform defines the associated uniform location
  17190. * @param textures defines the array of textures to bind
  17191. */
  17192. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17193. if (channel < 0 || !uniform) {
  17194. return;
  17195. }
  17196. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17197. this._textureUnits = new Int32Array(textures.length);
  17198. }
  17199. for (var i = 0; i < textures.length; i++) {
  17200. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17201. }
  17202. this._gl.uniform1iv(uniform, this._textureUnits);
  17203. for (var index = 0; index < textures.length; index++) {
  17204. this._setTexture(this._textureUnits[index], textures[index], true);
  17205. }
  17206. };
  17207. /** @hidden */
  17208. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17209. var internalTexture = texture.getInternalTexture();
  17210. if (!internalTexture) {
  17211. return;
  17212. }
  17213. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17214. var value = texture.anisotropicFilteringLevel;
  17215. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17216. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17217. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17218. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17219. }
  17220. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17221. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17222. internalTexture._cachedAnisotropicFilteringLevel = value;
  17223. }
  17224. };
  17225. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17226. this._bindTextureDirectly(target, texture, true, true);
  17227. this._gl.texParameterf(target, parameter, value);
  17228. };
  17229. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17230. if (texture) {
  17231. this._bindTextureDirectly(target, texture, true, true);
  17232. }
  17233. this._gl.texParameteri(target, parameter, value);
  17234. };
  17235. /**
  17236. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17237. * @param x defines the x coordinate of the rectangle where pixels must be read
  17238. * @param y defines the y coordinate of the rectangle where pixels must be read
  17239. * @param width defines the width of the rectangle where pixels must be read
  17240. * @param height defines the height of the rectangle where pixels must be read
  17241. * @returns a Uint8Array containing RGBA colors
  17242. */
  17243. Engine.prototype.readPixels = function (x, y, width, height) {
  17244. var data = new Uint8Array(height * width * 4);
  17245. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17246. return data;
  17247. };
  17248. /**
  17249. * Add an externaly attached data from its key.
  17250. * This method call will fail and return false, if such key already exists.
  17251. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17252. * @param key the unique key that identifies the data
  17253. * @param data the data object to associate to the key for this Engine instance
  17254. * @return true if no such key were already present and the data was added successfully, false otherwise
  17255. */
  17256. Engine.prototype.addExternalData = function (key, data) {
  17257. if (!this._externalData) {
  17258. this._externalData = new BABYLON.StringDictionary();
  17259. }
  17260. return this._externalData.add(key, data);
  17261. };
  17262. /**
  17263. * Get an externaly attached data from its key
  17264. * @param key the unique key that identifies the data
  17265. * @return the associated data, if present (can be null), or undefined if not present
  17266. */
  17267. Engine.prototype.getExternalData = function (key) {
  17268. if (!this._externalData) {
  17269. this._externalData = new BABYLON.StringDictionary();
  17270. }
  17271. return this._externalData.get(key);
  17272. };
  17273. /**
  17274. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17275. * @param key the unique key that identifies the data
  17276. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17277. * @return the associated data, can be null if the factory returned null.
  17278. */
  17279. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17280. if (!this._externalData) {
  17281. this._externalData = new BABYLON.StringDictionary();
  17282. }
  17283. return this._externalData.getOrAddWithFactory(key, factory);
  17284. };
  17285. /**
  17286. * Remove an externaly attached data from the Engine instance
  17287. * @param key the unique key that identifies the data
  17288. * @return true if the data was successfully removed, false if it doesn't exist
  17289. */
  17290. Engine.prototype.removeExternalData = function (key) {
  17291. if (!this._externalData) {
  17292. this._externalData = new BABYLON.StringDictionary();
  17293. }
  17294. return this._externalData.remove(key);
  17295. };
  17296. /**
  17297. * Unbind all vertex attributes from the webGL context
  17298. */
  17299. Engine.prototype.unbindAllAttributes = function () {
  17300. if (this._mustWipeVertexAttributes) {
  17301. this._mustWipeVertexAttributes = false;
  17302. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17303. this._gl.disableVertexAttribArray(i);
  17304. this._vertexAttribArraysEnabled[i] = false;
  17305. this._currentBufferPointers[i].active = false;
  17306. }
  17307. return;
  17308. }
  17309. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17310. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17311. continue;
  17312. }
  17313. this._gl.disableVertexAttribArray(i);
  17314. this._vertexAttribArraysEnabled[i] = false;
  17315. this._currentBufferPointers[i].active = false;
  17316. }
  17317. };
  17318. /**
  17319. * 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
  17320. */
  17321. Engine.prototype.releaseEffects = function () {
  17322. for (var name in this._compiledEffects) {
  17323. this._deleteProgram(this._compiledEffects[name]._program);
  17324. }
  17325. this._compiledEffects = {};
  17326. };
  17327. /**
  17328. * Dispose and release all associated resources
  17329. */
  17330. Engine.prototype.dispose = function () {
  17331. this.hideLoadingUI();
  17332. this.stopRenderLoop();
  17333. // Release postProcesses
  17334. while (this.postProcesses.length) {
  17335. this.postProcesses[0].dispose();
  17336. }
  17337. // Empty texture
  17338. if (this._emptyTexture) {
  17339. this._releaseTexture(this._emptyTexture);
  17340. this._emptyTexture = null;
  17341. }
  17342. if (this._emptyCubeTexture) {
  17343. this._releaseTexture(this._emptyCubeTexture);
  17344. this._emptyCubeTexture = null;
  17345. }
  17346. // Rescale PP
  17347. if (this._rescalePostProcess) {
  17348. this._rescalePostProcess.dispose();
  17349. }
  17350. // Release scenes
  17351. while (this.scenes.length) {
  17352. this.scenes[0].dispose();
  17353. }
  17354. // Release audio engine
  17355. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17356. Engine.audioEngine.dispose();
  17357. }
  17358. // Release effects
  17359. this.releaseEffects();
  17360. // Unbind
  17361. this.unbindAllAttributes();
  17362. this._boundUniforms = [];
  17363. if (this._dummyFramebuffer) {
  17364. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17365. }
  17366. //WebVR
  17367. this.disableVR();
  17368. // Events
  17369. if (BABYLON.Tools.IsWindowObjectExist()) {
  17370. window.removeEventListener("blur", this._onBlur);
  17371. window.removeEventListener("focus", this._onFocus);
  17372. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17373. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17374. if (this._renderingCanvas) {
  17375. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17376. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17377. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17378. if (!this._doNotHandleContextLost) {
  17379. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17380. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17381. }
  17382. }
  17383. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17384. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17385. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17386. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17387. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17388. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17389. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17390. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17391. if (this._onVrDisplayConnect) {
  17392. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17393. if (this._onVrDisplayDisconnect) {
  17394. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17395. }
  17396. if (this._onVrDisplayPresentChange) {
  17397. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17398. }
  17399. this._onVrDisplayConnect = null;
  17400. this._onVrDisplayDisconnect = null;
  17401. }
  17402. }
  17403. // Remove from Instances
  17404. var index = Engine.Instances.indexOf(this);
  17405. if (index >= 0) {
  17406. Engine.Instances.splice(index, 1);
  17407. }
  17408. this._workingCanvas = null;
  17409. this._workingContext = null;
  17410. this._currentBufferPointers = [];
  17411. this._renderingCanvas = null;
  17412. this._currentProgram = null;
  17413. this._bindedRenderFunction = null;
  17414. this.onResizeObservable.clear();
  17415. this.onCanvasBlurObservable.clear();
  17416. this.onCanvasFocusObservable.clear();
  17417. this.onCanvasPointerOutObservable.clear();
  17418. this.onBeginFrameObservable.clear();
  17419. this.onEndFrameObservable.clear();
  17420. BABYLON.Effect.ResetCache();
  17421. // Abort active requests
  17422. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17423. var request = _a[_i];
  17424. request.abort();
  17425. }
  17426. };
  17427. // Loading screen
  17428. /**
  17429. * Display the loading screen
  17430. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17431. */
  17432. Engine.prototype.displayLoadingUI = function () {
  17433. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17434. return;
  17435. }
  17436. var loadingScreen = this.loadingScreen;
  17437. if (loadingScreen) {
  17438. loadingScreen.displayLoadingUI();
  17439. }
  17440. };
  17441. /**
  17442. * Hide the loading screen
  17443. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17444. */
  17445. Engine.prototype.hideLoadingUI = function () {
  17446. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17447. return;
  17448. }
  17449. var loadingScreen = this.loadingScreen;
  17450. if (loadingScreen) {
  17451. loadingScreen.hideLoadingUI();
  17452. }
  17453. };
  17454. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17455. /**
  17456. * Gets the current loading screen object
  17457. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17458. */
  17459. get: function () {
  17460. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17461. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17462. return this._loadingScreen;
  17463. },
  17464. /**
  17465. * Sets the current loading screen object
  17466. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17467. */
  17468. set: function (loadingScreen) {
  17469. this._loadingScreen = loadingScreen;
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17475. /**
  17476. * Sets the current loading screen text
  17477. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17478. */
  17479. set: function (text) {
  17480. this.loadingScreen.loadingUIText = text;
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17486. /**
  17487. * Sets the current loading screen background color
  17488. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17489. */
  17490. set: function (color) {
  17491. this.loadingScreen.loadingUIBackgroundColor = color;
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. /**
  17497. * Attach a new callback raised when context lost event is fired
  17498. * @param callback defines the callback to call
  17499. */
  17500. Engine.prototype.attachContextLostEvent = function (callback) {
  17501. if (this._renderingCanvas) {
  17502. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17503. }
  17504. };
  17505. /**
  17506. * Attach a new callback raised when context restored event is fired
  17507. * @param callback defines the callback to call
  17508. */
  17509. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17510. if (this._renderingCanvas) {
  17511. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17512. }
  17513. };
  17514. /**
  17515. * Gets the source code of the vertex shader associated with a specific webGL program
  17516. * @param program defines the program to use
  17517. * @returns a string containing the source code of the vertex shader associated with the program
  17518. */
  17519. Engine.prototype.getVertexShaderSource = function (program) {
  17520. var shaders = this._gl.getAttachedShaders(program);
  17521. if (!shaders) {
  17522. return null;
  17523. }
  17524. return this._gl.getShaderSource(shaders[0]);
  17525. };
  17526. /**
  17527. * Gets the source code of the fragment shader associated with a specific webGL program
  17528. * @param program defines the program to use
  17529. * @returns a string containing the source code of the fragment shader associated with the program
  17530. */
  17531. Engine.prototype.getFragmentShaderSource = function (program) {
  17532. var shaders = this._gl.getAttachedShaders(program);
  17533. if (!shaders) {
  17534. return null;
  17535. }
  17536. return this._gl.getShaderSource(shaders[1]);
  17537. };
  17538. /**
  17539. * Get the current error code of the webGL context
  17540. * @returns the error code
  17541. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17542. */
  17543. Engine.prototype.getError = function () {
  17544. return this._gl.getError();
  17545. };
  17546. // FPS
  17547. /**
  17548. * Gets the current framerate
  17549. * @returns a number representing the framerate
  17550. */
  17551. Engine.prototype.getFps = function () {
  17552. return this._fps;
  17553. };
  17554. /**
  17555. * Gets the time spent between current and previous frame
  17556. * @returns a number representing the delta time in ms
  17557. */
  17558. Engine.prototype.getDeltaTime = function () {
  17559. return this._deltaTime;
  17560. };
  17561. Engine.prototype._measureFps = function () {
  17562. this._performanceMonitor.sampleFrame();
  17563. this._fps = this._performanceMonitor.averageFPS;
  17564. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17565. };
  17566. /** @hidden */
  17567. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17568. if (faceIndex === void 0) { faceIndex = -1; }
  17569. if (level === void 0) { level = 0; }
  17570. if (buffer === void 0) { buffer = null; }
  17571. var gl = this._gl;
  17572. if (!this._dummyFramebuffer) {
  17573. var dummy = gl.createFramebuffer();
  17574. if (!dummy) {
  17575. throw new Error("Unable to create dummy framebuffer");
  17576. }
  17577. this._dummyFramebuffer = dummy;
  17578. }
  17579. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17580. if (faceIndex > -1) {
  17581. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17582. }
  17583. else {
  17584. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17585. }
  17586. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17587. switch (readType) {
  17588. case gl.UNSIGNED_BYTE:
  17589. if (!buffer) {
  17590. buffer = new Uint8Array(4 * width * height);
  17591. }
  17592. readType = gl.UNSIGNED_BYTE;
  17593. break;
  17594. default:
  17595. if (!buffer) {
  17596. buffer = new Float32Array(4 * width * height);
  17597. }
  17598. readType = gl.FLOAT;
  17599. break;
  17600. }
  17601. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17602. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17603. return buffer;
  17604. };
  17605. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17606. if (this._webGLVersion > 1) {
  17607. return this._caps.colorBufferFloat;
  17608. }
  17609. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17610. };
  17611. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17612. if (this._webGLVersion > 1) {
  17613. return this._caps.colorBufferFloat;
  17614. }
  17615. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17616. };
  17617. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17618. Engine.prototype._canRenderToFramebuffer = function (type) {
  17619. var gl = this._gl;
  17620. //clear existing errors
  17621. while (gl.getError() !== gl.NO_ERROR) { }
  17622. var successful = true;
  17623. var texture = gl.createTexture();
  17624. gl.bindTexture(gl.TEXTURE_2D, texture);
  17625. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17628. var fb = gl.createFramebuffer();
  17629. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17630. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17631. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17632. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17633. successful = successful && (gl.getError() === gl.NO_ERROR);
  17634. //try render by clearing frame buffer's color buffer
  17635. if (successful) {
  17636. gl.clear(gl.COLOR_BUFFER_BIT);
  17637. successful = successful && (gl.getError() === gl.NO_ERROR);
  17638. }
  17639. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17640. if (successful) {
  17641. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17642. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17643. var readFormat = gl.RGBA;
  17644. var readType = gl.UNSIGNED_BYTE;
  17645. var buffer = new Uint8Array(4);
  17646. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17647. successful = successful && (gl.getError() === gl.NO_ERROR);
  17648. }
  17649. //clean up
  17650. gl.deleteTexture(texture);
  17651. gl.deleteFramebuffer(fb);
  17652. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17653. //clear accumulated errors
  17654. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17655. return successful;
  17656. };
  17657. /** @hidden */
  17658. Engine.prototype._getWebGLTextureType = function (type) {
  17659. if (this._webGLVersion === 1) {
  17660. switch (type) {
  17661. case Engine.TEXTURETYPE_FLOAT:
  17662. return this._gl.FLOAT;
  17663. case Engine.TEXTURETYPE_HALF_FLOAT:
  17664. return this._gl.HALF_FLOAT_OES;
  17665. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17666. return this._gl.UNSIGNED_BYTE;
  17667. }
  17668. return this._gl.UNSIGNED_BYTE;
  17669. }
  17670. switch (type) {
  17671. case Engine.TEXTURETYPE_BYTE:
  17672. return this._gl.BYTE;
  17673. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17674. return this._gl.UNSIGNED_BYTE;
  17675. case Engine.TEXTURETYPE_SHORT:
  17676. return this._gl.SHORT;
  17677. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17678. return this._gl.UNSIGNED_SHORT;
  17679. case Engine.TEXTURETYPE_INT:
  17680. return this._gl.INT;
  17681. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17682. return this._gl.UNSIGNED_INT;
  17683. case Engine.TEXTURETYPE_FLOAT:
  17684. return this._gl.FLOAT;
  17685. case Engine.TEXTURETYPE_HALF_FLOAT:
  17686. return this._gl.HALF_FLOAT;
  17687. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17688. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17689. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17690. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17691. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17692. return this._gl.UNSIGNED_SHORT_5_6_5;
  17693. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17694. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17695. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17696. return this._gl.UNSIGNED_INT_24_8;
  17697. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17698. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17699. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17700. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17701. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17702. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17703. }
  17704. return this._gl.UNSIGNED_BYTE;
  17705. };
  17706. ;
  17707. Engine.prototype._getInternalFormat = function (format) {
  17708. var internalFormat = this._gl.RGBA;
  17709. switch (format) {
  17710. case Engine.TEXTUREFORMAT_ALPHA:
  17711. internalFormat = this._gl.ALPHA;
  17712. break;
  17713. case Engine.TEXTUREFORMAT_LUMINANCE:
  17714. internalFormat = this._gl.LUMINANCE;
  17715. break;
  17716. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17717. internalFormat = this._gl.LUMINANCE_ALPHA;
  17718. break;
  17719. case Engine.TEXTUREFORMAT_RED:
  17720. internalFormat = this._gl.RED;
  17721. break;
  17722. case Engine.TEXTUREFORMAT_RG:
  17723. internalFormat = this._gl.RG;
  17724. break;
  17725. case Engine.TEXTUREFORMAT_RGB:
  17726. internalFormat = this._gl.RGB;
  17727. break;
  17728. case Engine.TEXTUREFORMAT_RGBA:
  17729. internalFormat = this._gl.RGBA;
  17730. break;
  17731. }
  17732. if (this._webGLVersion > 1) {
  17733. switch (format) {
  17734. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17735. internalFormat = this._gl.RED_INTEGER;
  17736. break;
  17737. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17738. internalFormat = this._gl.RG_INTEGER;
  17739. break;
  17740. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17741. internalFormat = this._gl.RGB_INTEGER;
  17742. break;
  17743. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17744. internalFormat = this._gl.RGBA_INTEGER;
  17745. break;
  17746. }
  17747. }
  17748. return internalFormat;
  17749. };
  17750. /** @hidden */
  17751. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17752. if (this._webGLVersion === 1) {
  17753. if (format !== undefined) {
  17754. switch (format) {
  17755. case Engine.TEXTUREFORMAT_ALPHA:
  17756. return this._gl.ALPHA;
  17757. case Engine.TEXTUREFORMAT_LUMINANCE:
  17758. return this._gl.LUMINANCE;
  17759. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17760. return this._gl.LUMINANCE_ALPHA;
  17761. }
  17762. }
  17763. return this._gl.RGBA;
  17764. }
  17765. switch (type) {
  17766. case Engine.TEXTURETYPE_BYTE:
  17767. switch (format) {
  17768. case Engine.TEXTUREFORMAT_RED:
  17769. return this._gl.R8_SNORM;
  17770. case Engine.TEXTUREFORMAT_RG:
  17771. return this._gl.RG8_SNORM;
  17772. case Engine.TEXTUREFORMAT_RGB:
  17773. return this._gl.RGB8_SNORM;
  17774. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17775. return this._gl.R8I;
  17776. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17777. return this._gl.RG8I;
  17778. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17779. return this._gl.RGB8I;
  17780. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17781. return this._gl.RGBA8I;
  17782. default:
  17783. return this._gl.RGBA8_SNORM;
  17784. }
  17785. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17786. switch (format) {
  17787. case Engine.TEXTUREFORMAT_RED:
  17788. return this._gl.R8;
  17789. case Engine.TEXTUREFORMAT_RG:
  17790. return this._gl.RG8;
  17791. case Engine.TEXTUREFORMAT_RGB:
  17792. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17793. case Engine.TEXTUREFORMAT_RGBA:
  17794. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17795. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17796. return this._gl.R8UI;
  17797. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17798. return this._gl.RG8UI;
  17799. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17800. return this._gl.RGB8UI;
  17801. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17802. return this._gl.RGBA8UI;
  17803. default:
  17804. return this._gl.RGBA8;
  17805. }
  17806. case Engine.TEXTURETYPE_SHORT:
  17807. switch (format) {
  17808. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17809. return this._gl.R16I;
  17810. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17811. return this._gl.RG16I;
  17812. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17813. return this._gl.RGB16I;
  17814. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17815. return this._gl.RGBA16I;
  17816. default:
  17817. return this._gl.RGBA16I;
  17818. }
  17819. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17820. switch (format) {
  17821. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17822. return this._gl.R16UI;
  17823. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17824. return this._gl.RG16UI;
  17825. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17826. return this._gl.RGB16UI;
  17827. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17828. return this._gl.RGBA16UI;
  17829. default:
  17830. return this._gl.RGBA16UI;
  17831. }
  17832. case Engine.TEXTURETYPE_INT:
  17833. switch (format) {
  17834. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17835. return this._gl.R32I;
  17836. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17837. return this._gl.RG32I;
  17838. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17839. return this._gl.RGB32I;
  17840. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17841. return this._gl.RGBA32I;
  17842. default:
  17843. return this._gl.RGBA32I;
  17844. }
  17845. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17846. switch (format) {
  17847. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17848. return this._gl.R32UI;
  17849. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17850. return this._gl.RG32UI;
  17851. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17852. return this._gl.RGB32UI;
  17853. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17854. return this._gl.RGBA32UI;
  17855. default:
  17856. return this._gl.RGBA32UI;
  17857. }
  17858. case Engine.TEXTURETYPE_FLOAT:
  17859. switch (format) {
  17860. case Engine.TEXTUREFORMAT_RED:
  17861. return this._gl.R32F; // By default. Other possibility is R16F.
  17862. case Engine.TEXTUREFORMAT_RG:
  17863. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17864. case Engine.TEXTUREFORMAT_RGB:
  17865. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17866. case Engine.TEXTUREFORMAT_RGBA:
  17867. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17868. default:
  17869. return this._gl.RGBA32F;
  17870. }
  17871. case Engine.TEXTURETYPE_HALF_FLOAT:
  17872. switch (format) {
  17873. case Engine.TEXTUREFORMAT_RED:
  17874. return this._gl.R16F;
  17875. case Engine.TEXTUREFORMAT_RG:
  17876. return this._gl.RG16F;
  17877. case Engine.TEXTUREFORMAT_RGB:
  17878. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17879. case Engine.TEXTUREFORMAT_RGBA:
  17880. return this._gl.RGBA16F;
  17881. default:
  17882. return this._gl.RGBA16F;
  17883. }
  17884. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17885. return this._gl.RGB565;
  17886. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17887. return this._gl.R11F_G11F_B10F;
  17888. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17889. return this._gl.RGB9_E5;
  17890. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17891. return this._gl.RGBA4;
  17892. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17893. return this._gl.RGB5_A1;
  17894. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17895. switch (format) {
  17896. case Engine.TEXTUREFORMAT_RGBA:
  17897. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17898. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17899. return this._gl.RGB10_A2UI;
  17900. default:
  17901. return this._gl.RGB10_A2;
  17902. }
  17903. }
  17904. return this._gl.RGBA8;
  17905. };
  17906. ;
  17907. /** @hidden */
  17908. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17909. if (type === Engine.TEXTURETYPE_FLOAT) {
  17910. return this._gl.RGBA32F;
  17911. }
  17912. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17913. return this._gl.RGBA16F;
  17914. }
  17915. return this._gl.RGBA8;
  17916. };
  17917. ;
  17918. /** @hidden */
  17919. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17920. var _this = this;
  17921. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17922. this._activeRequests.push(request);
  17923. request.onCompleteObservable.add(function (request) {
  17924. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17925. });
  17926. return request;
  17927. };
  17928. /** @hidden */
  17929. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17930. var _this = this;
  17931. return new Promise(function (resolve, reject) {
  17932. _this._loadFile(url, function (data) {
  17933. resolve(data);
  17934. }, undefined, database, useArrayBuffer, function (request, exception) {
  17935. reject(exception);
  17936. });
  17937. });
  17938. };
  17939. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17940. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17941. var onload = function (data) {
  17942. loadedFiles[index] = data;
  17943. loadedFiles._internalCount++;
  17944. if (loadedFiles._internalCount === 6) {
  17945. onfinish(loadedFiles);
  17946. }
  17947. };
  17948. var onerror = function (request, exception) {
  17949. if (onErrorCallBack && request) {
  17950. onErrorCallBack(request.status + " " + request.statusText, exception);
  17951. }
  17952. };
  17953. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17954. };
  17955. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17956. if (onError === void 0) { onError = null; }
  17957. var loadedFiles = [];
  17958. loadedFiles._internalCount = 0;
  17959. for (var index = 0; index < 6; index++) {
  17960. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17961. }
  17962. };
  17963. // Statics
  17964. /**
  17965. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17966. * @returns true if the engine can be created
  17967. * @ignorenaming
  17968. */
  17969. Engine.isSupported = function () {
  17970. try {
  17971. var tempcanvas = document.createElement("canvas");
  17972. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17973. return gl != null && !!window.WebGLRenderingContext;
  17974. }
  17975. catch (e) {
  17976. return false;
  17977. }
  17978. };
  17979. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17980. Engine.ExceptionList = [
  17981. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17982. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17983. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17984. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17985. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17986. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17987. ];
  17988. /** Gets the list of created engines */
  17989. Engine.Instances = new Array();
  17990. /**
  17991. * Hidden
  17992. */
  17993. Engine._TextureLoaders = [];
  17994. // Const statics
  17995. /** Defines that alpha blending is disabled */
  17996. Engine.ALPHA_DISABLE = 0;
  17997. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17998. Engine.ALPHA_ADD = 1;
  17999. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18000. Engine.ALPHA_COMBINE = 2;
  18001. /** Defines that alpha blending to DEST - SRC * DEST */
  18002. Engine.ALPHA_SUBTRACT = 3;
  18003. /** Defines that alpha blending to SRC * DEST */
  18004. Engine.ALPHA_MULTIPLY = 4;
  18005. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18006. Engine.ALPHA_MAXIMIZED = 5;
  18007. /** Defines that alpha blending to SRC + DEST */
  18008. Engine.ALPHA_ONEONE = 6;
  18009. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18010. Engine.ALPHA_PREMULTIPLIED = 7;
  18011. /**
  18012. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18013. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18014. */
  18015. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18016. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18017. Engine.ALPHA_INTERPOLATE = 9;
  18018. /**
  18019. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18020. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18021. */
  18022. Engine.ALPHA_SCREENMODE = 10;
  18023. /** Defines that the ressource is not delayed*/
  18024. Engine.DELAYLOADSTATE_NONE = 0;
  18025. /** Defines that the ressource was successfully delay loaded */
  18026. Engine.DELAYLOADSTATE_LOADED = 1;
  18027. /** Defines that the ressource is currently delay loading */
  18028. Engine.DELAYLOADSTATE_LOADING = 2;
  18029. /** Defines that the ressource is delayed and has not started loading */
  18030. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18031. // Depht or Stencil test Constants.
  18032. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18033. Engine.NEVER = 0x0200;
  18034. /** 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 */
  18035. Engine.ALWAYS = 0x0207;
  18036. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18037. Engine.LESS = 0x0201;
  18038. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18039. Engine.EQUAL = 0x0202;
  18040. /** 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 */
  18041. Engine.LEQUAL = 0x0203;
  18042. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18043. Engine.GREATER = 0x0204;
  18044. /** 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 */
  18045. Engine.GEQUAL = 0x0206;
  18046. /** 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 */
  18047. Engine.NOTEQUAL = 0x0205;
  18048. // Stencil Actions Constants.
  18049. /** Passed to stencilOperation to specify that stencil value must be kept */
  18050. Engine.KEEP = 0x1E00;
  18051. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18052. Engine.REPLACE = 0x1E01;
  18053. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18054. Engine.INCR = 0x1E02;
  18055. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18056. Engine.DECR = 0x1E03;
  18057. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18058. Engine.INVERT = 0x150A;
  18059. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18060. Engine.INCR_WRAP = 0x8507;
  18061. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18062. Engine.DECR_WRAP = 0x8508;
  18063. /** Texture is not repeating outside of 0..1 UVs */
  18064. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18065. /** Texture is repeating outside of 0..1 UVs */
  18066. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18067. /** Texture is repeating and mirrored */
  18068. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18069. /** ALPHA */
  18070. Engine.TEXTUREFORMAT_ALPHA = 0;
  18071. /** LUMINANCE */
  18072. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18073. /** LUMINANCE_ALPHA */
  18074. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18075. /** RGB */
  18076. Engine.TEXTUREFORMAT_RGB = 4;
  18077. /** RGBA */
  18078. Engine.TEXTUREFORMAT_RGBA = 5;
  18079. /** RED */
  18080. Engine.TEXTUREFORMAT_RED = 6;
  18081. /** RED (2nd reference) */
  18082. Engine.TEXTUREFORMAT_R = 6;
  18083. /** RG */
  18084. Engine.TEXTUREFORMAT_RG = 7;
  18085. /** RED_INTEGER */
  18086. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18087. /** RED_INTEGER (2nd reference) */
  18088. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18089. /** RG_INTEGER */
  18090. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18091. /** RGB_INTEGER */
  18092. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18093. /** RGBA_INTEGER */
  18094. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18095. /** UNSIGNED_BYTE */
  18096. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18097. /** UNSIGNED_BYTE (2nd reference) */
  18098. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18099. /** FLOAT */
  18100. Engine.TEXTURETYPE_FLOAT = 1;
  18101. /** HALF_FLOAT */
  18102. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18103. /** BYTE */
  18104. Engine.TEXTURETYPE_BYTE = 3;
  18105. /** SHORT */
  18106. Engine.TEXTURETYPE_SHORT = 4;
  18107. /** UNSIGNED_SHORT */
  18108. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18109. /** INT */
  18110. Engine.TEXTURETYPE_INT = 6;
  18111. /** UNSIGNED_INT */
  18112. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18113. /** UNSIGNED_SHORT_4_4_4_4 */
  18114. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18115. /** UNSIGNED_SHORT_5_5_5_1 */
  18116. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18117. /** UNSIGNED_SHORT_5_6_5 */
  18118. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18119. /** UNSIGNED_INT_2_10_10_10_REV */
  18120. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18121. /** UNSIGNED_INT_24_8 */
  18122. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18123. /** UNSIGNED_INT_10F_11F_11F_REV */
  18124. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18125. /** UNSIGNED_INT_5_9_9_9_REV */
  18126. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18127. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18128. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18129. /** nearest is mag = nearest and min = nearest and mip = linear */
  18130. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18131. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18132. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18133. /** Trilinear is mag = linear and min = linear and mip = linear */
  18134. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18135. /** nearest is mag = nearest and min = nearest and mip = linear */
  18136. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18137. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18138. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18139. /** Trilinear is mag = linear and min = linear and mip = linear */
  18140. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18141. /** mag = nearest and min = nearest and mip = nearest */
  18142. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18143. /** mag = nearest and min = linear and mip = nearest */
  18144. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18145. /** mag = nearest and min = linear and mip = linear */
  18146. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18147. /** mag = nearest and min = linear and mip = none */
  18148. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18149. /** mag = nearest and min = nearest and mip = none */
  18150. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18151. /** mag = linear and min = nearest and mip = nearest */
  18152. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18153. /** mag = linear and min = nearest and mip = linear */
  18154. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18155. /** mag = linear and min = linear and mip = none */
  18156. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18157. /** mag = linear and min = nearest and mip = none */
  18158. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18159. /** Explicit coordinates mode */
  18160. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18161. /** Spherical coordinates mode */
  18162. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18163. /** Planar coordinates mode */
  18164. Engine.TEXTURE_PLANAR_MODE = 2;
  18165. /** Cubic coordinates mode */
  18166. Engine.TEXTURE_CUBIC_MODE = 3;
  18167. /** Projection coordinates mode */
  18168. Engine.TEXTURE_PROJECTION_MODE = 4;
  18169. /** Skybox coordinates mode */
  18170. Engine.TEXTURE_SKYBOX_MODE = 5;
  18171. /** Inverse Cubic coordinates mode */
  18172. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18173. /** Equirectangular coordinates mode */
  18174. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18175. /** Equirectangular Fixed coordinates mode */
  18176. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18177. /** Equirectangular Fixed Mirrored coordinates mode */
  18178. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18179. // Texture rescaling mode
  18180. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18181. Engine.SCALEMODE_FLOOR = 1;
  18182. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18183. Engine.SCALEMODE_NEAREST = 2;
  18184. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18185. Engine.SCALEMODE_CEILING = 3;
  18186. // Updatable statics so stick with vars here
  18187. /**
  18188. * Gets or sets the epsilon value used by collision engine
  18189. */
  18190. Engine.CollisionsEpsilon = 0.001;
  18191. /**
  18192. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18193. */
  18194. Engine.CodeRepository = "src/";
  18195. /**
  18196. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18197. */
  18198. Engine.ShadersRepository = "src/Shaders/";
  18199. return Engine;
  18200. }());
  18201. BABYLON.Engine = Engine;
  18202. })(BABYLON || (BABYLON = {}));
  18203. //# sourceMappingURL=babylon.engine.js.map
  18204. var BABYLON;
  18205. (function (BABYLON) {
  18206. /**
  18207. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18208. */
  18209. var Node = /** @class */ (function () {
  18210. /**
  18211. * Creates a new Node
  18212. * @param {string} name - the name and id to be given to this node
  18213. * @param {BABYLON.Scene} the scene this node will be added to
  18214. */
  18215. function Node(name, scene) {
  18216. if (scene === void 0) { scene = null; }
  18217. /**
  18218. * Gets or sets a string used to store user defined state for the node
  18219. */
  18220. this.state = "";
  18221. /**
  18222. * Gets or sets an object used to store user defined information for the node
  18223. */
  18224. this.metadata = null;
  18225. /**
  18226. * Gets or sets a boolean used to define if the node must be serialized
  18227. */
  18228. this.doNotSerialize = false;
  18229. /** @hidden */
  18230. this._isDisposed = false;
  18231. /**
  18232. * Gets a list of Animations associated with the node
  18233. */
  18234. this.animations = new Array();
  18235. this._ranges = {};
  18236. this._isEnabled = true;
  18237. this._isParentEnabled = true;
  18238. this._isReady = true;
  18239. /** @hidden */
  18240. this._currentRenderId = -1;
  18241. this._parentRenderId = -1;
  18242. this._childRenderId = -1;
  18243. /** @hidden */
  18244. this._worldMatrix = BABYLON.Matrix.Identity();
  18245. /** @hidden */
  18246. this._worldMatrixDeterminant = 0;
  18247. this._animationPropertiesOverride = null;
  18248. /**
  18249. * An event triggered when the mesh is disposed
  18250. */
  18251. this.onDisposeObservable = new BABYLON.Observable();
  18252. // Behaviors
  18253. this._behaviors = new Array();
  18254. this.name = name;
  18255. this.id = name;
  18256. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18257. this.uniqueId = this._scene.getUniqueId();
  18258. this._initCache();
  18259. this._scene.rootNodes.push(this);
  18260. }
  18261. /**
  18262. * Add a new node constructor
  18263. * @param type defines the type name of the node to construct
  18264. * @param constructorFunc defines the constructor function
  18265. */
  18266. Node.AddNodeConstructor = function (type, constructorFunc) {
  18267. this._NodeConstructors[type] = constructorFunc;
  18268. };
  18269. /**
  18270. * Returns a node constructor based on type name
  18271. * @param type defines the type name
  18272. * @param name defines the new node name
  18273. * @param scene defines the hosting scene
  18274. * @param options defines optional options to transmit to constructors
  18275. * @returns the new constructor or null
  18276. */
  18277. Node.Construct = function (type, name, scene, options) {
  18278. var constructorFunc = this._NodeConstructors[type];
  18279. if (!constructorFunc) {
  18280. return null;
  18281. }
  18282. return constructorFunc(name, scene, options);
  18283. };
  18284. /**
  18285. * Gets a boolean indicating if the node has been disposed
  18286. * @returns true if the node was disposed
  18287. */
  18288. Node.prototype.isDisposed = function () {
  18289. return this._isDisposed;
  18290. };
  18291. Object.defineProperty(Node.prototype, "parent", {
  18292. get: function () {
  18293. return this._parentNode;
  18294. },
  18295. /**
  18296. * Gets or sets the parent of the node
  18297. */
  18298. set: function (parent) {
  18299. if (this._parentNode === parent) {
  18300. return;
  18301. }
  18302. var previousParentNode = this._parentNode;
  18303. // Remove self from list of children of parent
  18304. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18305. var index = this._parentNode._children.indexOf(this);
  18306. if (index !== -1) {
  18307. this._parentNode._children.splice(index, 1);
  18308. }
  18309. if (!parent) {
  18310. // Need to add this node to the rootNodes
  18311. this._scene.rootNodes.push(this);
  18312. }
  18313. }
  18314. // Store new parent
  18315. this._parentNode = parent;
  18316. // Add as child to new parent
  18317. if (this._parentNode) {
  18318. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18319. this._parentNode._children = new Array();
  18320. }
  18321. this._parentNode._children.push(this);
  18322. if (!previousParentNode) {
  18323. // Need to remove from rootNodes
  18324. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18325. if (rootNodeIndex > -1) {
  18326. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18327. }
  18328. }
  18329. }
  18330. // Enabled state
  18331. this._syncParentEnabledState();
  18332. },
  18333. enumerable: true,
  18334. configurable: true
  18335. });
  18336. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18337. /**
  18338. * Gets or sets the animation properties override
  18339. */
  18340. get: function () {
  18341. if (!this._animationPropertiesOverride) {
  18342. return this._scene.animationPropertiesOverride;
  18343. }
  18344. return this._animationPropertiesOverride;
  18345. },
  18346. set: function (value) {
  18347. this._animationPropertiesOverride = value;
  18348. },
  18349. enumerable: true,
  18350. configurable: true
  18351. });
  18352. /**
  18353. * Gets a string idenfifying the name of the class
  18354. * @returns "Node" string
  18355. */
  18356. Node.prototype.getClassName = function () {
  18357. return "Node";
  18358. };
  18359. Object.defineProperty(Node.prototype, "onDispose", {
  18360. /**
  18361. * Sets a callback that will be raised when the node will be disposed
  18362. */
  18363. set: function (callback) {
  18364. if (this._onDisposeObserver) {
  18365. this.onDisposeObservable.remove(this._onDisposeObserver);
  18366. }
  18367. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18368. },
  18369. enumerable: true,
  18370. configurable: true
  18371. });
  18372. /**
  18373. * Gets the scene of the node
  18374. * @returns a {BABYLON.Scene}
  18375. */
  18376. Node.prototype.getScene = function () {
  18377. return this._scene;
  18378. };
  18379. /**
  18380. * Gets the engine of the node
  18381. * @returns a {BABYLON.Engine}
  18382. */
  18383. Node.prototype.getEngine = function () {
  18384. return this._scene.getEngine();
  18385. };
  18386. /**
  18387. * Attach a behavior to the node
  18388. * @see http://doc.babylonjs.com/features/behaviour
  18389. * @param behavior defines the behavior to attach
  18390. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18391. * @returns the current Node
  18392. */
  18393. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18394. var _this = this;
  18395. if (attachImmediately === void 0) { attachImmediately = false; }
  18396. var index = this._behaviors.indexOf(behavior);
  18397. if (index !== -1) {
  18398. return this;
  18399. }
  18400. behavior.init();
  18401. if (this._scene.isLoading && !attachImmediately) {
  18402. // We defer the attach when the scene will be loaded
  18403. this._scene.onDataLoadedObservable.addOnce(function () {
  18404. behavior.attach(_this);
  18405. });
  18406. }
  18407. else {
  18408. behavior.attach(this);
  18409. }
  18410. this._behaviors.push(behavior);
  18411. return this;
  18412. };
  18413. /**
  18414. * Remove an attached behavior
  18415. * @see http://doc.babylonjs.com/features/behaviour
  18416. * @param behavior defines the behavior to attach
  18417. * @returns the current Node
  18418. */
  18419. Node.prototype.removeBehavior = function (behavior) {
  18420. var index = this._behaviors.indexOf(behavior);
  18421. if (index === -1) {
  18422. return this;
  18423. }
  18424. this._behaviors[index].detach();
  18425. this._behaviors.splice(index, 1);
  18426. return this;
  18427. };
  18428. Object.defineProperty(Node.prototype, "behaviors", {
  18429. /**
  18430. * Gets the list of attached behaviors
  18431. * @see http://doc.babylonjs.com/features/behaviour
  18432. */
  18433. get: function () {
  18434. return this._behaviors;
  18435. },
  18436. enumerable: true,
  18437. configurable: true
  18438. });
  18439. /**
  18440. * Gets an attached behavior by name
  18441. * @param name defines the name of the behavior to look for
  18442. * @see http://doc.babylonjs.com/features/behaviour
  18443. * @returns null if behavior was not found else the requested behavior
  18444. */
  18445. Node.prototype.getBehaviorByName = function (name) {
  18446. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18447. var behavior = _a[_i];
  18448. if (behavior.name === name) {
  18449. return behavior;
  18450. }
  18451. }
  18452. return null;
  18453. };
  18454. /**
  18455. * Returns the latest update of the World matrix
  18456. * @returns a Matrix
  18457. */
  18458. Node.prototype.getWorldMatrix = function () {
  18459. if (this._currentRenderId !== this._scene.getRenderId()) {
  18460. this.computeWorldMatrix();
  18461. }
  18462. return this._worldMatrix;
  18463. };
  18464. /** @hidden */
  18465. Node.prototype._getWorldMatrixDeterminant = function () {
  18466. return this._worldMatrixDeterminant;
  18467. };
  18468. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18469. /**
  18470. * Returns directly the latest state of the mesh World matrix.
  18471. * A Matrix is returned.
  18472. */
  18473. get: function () {
  18474. return this._worldMatrix;
  18475. },
  18476. enumerable: true,
  18477. configurable: true
  18478. });
  18479. // override it in derived class if you add new variables to the cache
  18480. // and call the parent class method
  18481. /** @hidden */
  18482. Node.prototype._initCache = function () {
  18483. this._cache = {};
  18484. this._cache.parent = undefined;
  18485. };
  18486. /** @hidden */
  18487. Node.prototype.updateCache = function (force) {
  18488. if (!force && this.isSynchronized())
  18489. return;
  18490. this._cache.parent = this.parent;
  18491. this._updateCache();
  18492. };
  18493. // override it in derived class if you add new variables to the cache
  18494. // and call the parent class method if !ignoreParentClass
  18495. /** @hidden */
  18496. Node.prototype._updateCache = function (ignoreParentClass) {
  18497. };
  18498. // override it in derived class if you add new variables to the cache
  18499. /** @hidden */
  18500. Node.prototype._isSynchronized = function () {
  18501. return true;
  18502. };
  18503. /** @hidden */
  18504. Node.prototype._markSyncedWithParent = function () {
  18505. if (this._parentNode) {
  18506. this._parentRenderId = this._parentNode._childRenderId;
  18507. }
  18508. };
  18509. /** @hidden */
  18510. Node.prototype.isSynchronizedWithParent = function () {
  18511. if (!this._parentNode) {
  18512. return true;
  18513. }
  18514. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18515. return false;
  18516. }
  18517. return this._parentNode.isSynchronized();
  18518. };
  18519. /** @hidden */
  18520. Node.prototype.isSynchronized = function () {
  18521. if (this._cache.parent != this._parentNode) {
  18522. this._cache.parent = this._parentNode;
  18523. return false;
  18524. }
  18525. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18526. return false;
  18527. }
  18528. return this._isSynchronized();
  18529. };
  18530. /**
  18531. * Is this node ready to be used/rendered
  18532. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18533. * @return true if the node is ready
  18534. */
  18535. Node.prototype.isReady = function (completeCheck) {
  18536. if (completeCheck === void 0) { completeCheck = false; }
  18537. return this._isReady;
  18538. };
  18539. /**
  18540. * Is this node enabled?
  18541. * 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
  18542. * @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
  18543. * @return whether this node (and its parent) is enabled
  18544. */
  18545. Node.prototype.isEnabled = function (checkAncestors) {
  18546. if (checkAncestors === void 0) { checkAncestors = true; }
  18547. if (checkAncestors === false) {
  18548. return this._isEnabled;
  18549. }
  18550. if (!this._isEnabled) {
  18551. return false;
  18552. }
  18553. return this._isParentEnabled;
  18554. };
  18555. /** @hidden */
  18556. Node.prototype._syncParentEnabledState = function () {
  18557. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18558. if (this._children) {
  18559. this._children.forEach(function (c) {
  18560. c._syncParentEnabledState(); // Force children to update accordingly
  18561. });
  18562. }
  18563. };
  18564. /**
  18565. * Set the enabled state of this node
  18566. * @param value defines the new enabled state
  18567. */
  18568. Node.prototype.setEnabled = function (value) {
  18569. this._isEnabled = value;
  18570. this._syncParentEnabledState();
  18571. };
  18572. /**
  18573. * Is this node a descendant of the given node?
  18574. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18575. * @param ancestor defines the parent node to inspect
  18576. * @returns a boolean indicating if this node is a descendant of the given node
  18577. */
  18578. Node.prototype.isDescendantOf = function (ancestor) {
  18579. if (this.parent) {
  18580. if (this.parent === ancestor) {
  18581. return true;
  18582. }
  18583. return this.parent.isDescendantOf(ancestor);
  18584. }
  18585. return false;
  18586. };
  18587. /** @hidden */
  18588. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18589. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18590. if (!this._children) {
  18591. return;
  18592. }
  18593. for (var index = 0; index < this._children.length; index++) {
  18594. var item = this._children[index];
  18595. if (!predicate || predicate(item)) {
  18596. results.push(item);
  18597. }
  18598. if (!directDescendantsOnly) {
  18599. item._getDescendants(results, false, predicate);
  18600. }
  18601. }
  18602. };
  18603. /**
  18604. * Will return all nodes that have this node as ascendant
  18605. * @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
  18606. * @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
  18607. * @return all children nodes of all types
  18608. */
  18609. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18610. var results = new Array();
  18611. this._getDescendants(results, directDescendantsOnly, predicate);
  18612. return results;
  18613. };
  18614. /**
  18615. * Get all child-meshes of this node
  18616. * @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
  18617. * @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
  18618. * @returns an array of {BABYLON.AbstractMesh}
  18619. */
  18620. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18621. var results = [];
  18622. this._getDescendants(results, directDescendantsOnly, function (node) {
  18623. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18624. });
  18625. return results;
  18626. };
  18627. /**
  18628. * Get all child-transformNodes of this node
  18629. * @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
  18630. * @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
  18631. * @returns an array of {BABYLON.TransformNode}
  18632. */
  18633. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18634. var results = [];
  18635. this._getDescendants(results, directDescendantsOnly, function (node) {
  18636. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18637. });
  18638. return results;
  18639. };
  18640. /**
  18641. * Get all direct children of this node
  18642. * @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
  18643. * @returns an array of {BABYLON.Node}
  18644. */
  18645. Node.prototype.getChildren = function (predicate) {
  18646. return this.getDescendants(true, predicate);
  18647. };
  18648. /** @hidden */
  18649. Node.prototype._setReady = function (state) {
  18650. if (state === this._isReady) {
  18651. return;
  18652. }
  18653. if (!state) {
  18654. this._isReady = false;
  18655. return;
  18656. }
  18657. if (this.onReady) {
  18658. this.onReady(this);
  18659. }
  18660. this._isReady = true;
  18661. };
  18662. /**
  18663. * Get an animation by name
  18664. * @param name defines the name of the animation to look for
  18665. * @returns null if not found else the requested animation
  18666. */
  18667. Node.prototype.getAnimationByName = function (name) {
  18668. for (var i = 0; i < this.animations.length; i++) {
  18669. var animation = this.animations[i];
  18670. if (animation.name === name) {
  18671. return animation;
  18672. }
  18673. }
  18674. return null;
  18675. };
  18676. /**
  18677. * Creates an animation range for this node
  18678. * @param name defines the name of the range
  18679. * @param from defines the starting key
  18680. * @param to defines the end key
  18681. */
  18682. Node.prototype.createAnimationRange = function (name, from, to) {
  18683. // check name not already in use
  18684. if (!this._ranges[name]) {
  18685. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18686. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18687. if (this.animations[i]) {
  18688. this.animations[i].createRange(name, from, to);
  18689. }
  18690. }
  18691. }
  18692. };
  18693. /**
  18694. * Delete a specific animation range
  18695. * @param name defines the name of the range to delete
  18696. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18697. */
  18698. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18699. if (deleteFrames === void 0) { deleteFrames = true; }
  18700. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18701. if (this.animations[i]) {
  18702. this.animations[i].deleteRange(name, deleteFrames);
  18703. }
  18704. }
  18705. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18706. };
  18707. /**
  18708. * Get an animation range by name
  18709. * @param name defines the name of the animation range to look for
  18710. * @returns null if not found else the requested animation range
  18711. */
  18712. Node.prototype.getAnimationRange = function (name) {
  18713. return this._ranges[name];
  18714. };
  18715. /**
  18716. * Will start the animation sequence
  18717. * @param name defines the range frames for animation sequence
  18718. * @param loop defines if the animation should loop (false by default)
  18719. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18720. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18721. * @returns the object created for this animation. If range does not exist, it will return null
  18722. */
  18723. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18724. var range = this.getAnimationRange(name);
  18725. if (!range) {
  18726. return null;
  18727. }
  18728. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18729. };
  18730. /**
  18731. * Serialize animation ranges into a JSON compatible object
  18732. * @returns serialization object
  18733. */
  18734. Node.prototype.serializeAnimationRanges = function () {
  18735. var serializationRanges = [];
  18736. for (var name in this._ranges) {
  18737. var localRange = this._ranges[name];
  18738. if (!localRange) {
  18739. continue;
  18740. }
  18741. var range = {};
  18742. range.name = name;
  18743. range.from = localRange.from;
  18744. range.to = localRange.to;
  18745. serializationRanges.push(range);
  18746. }
  18747. return serializationRanges;
  18748. };
  18749. /**
  18750. * Computes the world matrix of the node
  18751. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18752. * @returns the world matrix
  18753. */
  18754. Node.prototype.computeWorldMatrix = function (force) {
  18755. if (!this._worldMatrix) {
  18756. this._worldMatrix = BABYLON.Matrix.Identity();
  18757. }
  18758. return this._worldMatrix;
  18759. };
  18760. /**
  18761. * Releases resources associated with this node.
  18762. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18763. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18764. */
  18765. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18766. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18767. if (!doNotRecurse) {
  18768. var nodes = this.getDescendants(true);
  18769. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18770. var node = nodes_1[_i];
  18771. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18772. }
  18773. }
  18774. else {
  18775. var transformNodes = this.getChildTransformNodes(true);
  18776. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18777. var transformNode = transformNodes_1[_a];
  18778. transformNode.parent = null;
  18779. transformNode.computeWorldMatrix(true);
  18780. }
  18781. }
  18782. if (!this.parent) {
  18783. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18784. if (rootNodeIndex > -1) {
  18785. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18786. }
  18787. }
  18788. else {
  18789. this.parent = null;
  18790. }
  18791. // Callback
  18792. this.onDisposeObservable.notifyObservers(this);
  18793. this.onDisposeObservable.clear();
  18794. // Behaviors
  18795. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18796. var behavior = _c[_b];
  18797. behavior.detach();
  18798. }
  18799. this._behaviors = [];
  18800. this._isDisposed = true;
  18801. };
  18802. /**
  18803. * Parse animation range data from a serialization object and store them into a given node
  18804. * @param node defines where to store the animation ranges
  18805. * @param parsedNode defines the serialization object to read data from
  18806. * @param scene defines the hosting scene
  18807. */
  18808. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18809. if (parsedNode.ranges) {
  18810. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18811. var data = parsedNode.ranges[index];
  18812. node.createAnimationRange(data.name, data.from, data.to);
  18813. }
  18814. }
  18815. };
  18816. Node._NodeConstructors = {};
  18817. __decorate([
  18818. BABYLON.serialize()
  18819. ], Node.prototype, "name", void 0);
  18820. __decorate([
  18821. BABYLON.serialize()
  18822. ], Node.prototype, "id", void 0);
  18823. __decorate([
  18824. BABYLON.serialize()
  18825. ], Node.prototype, "uniqueId", void 0);
  18826. __decorate([
  18827. BABYLON.serialize()
  18828. ], Node.prototype, "state", void 0);
  18829. __decorate([
  18830. BABYLON.serialize()
  18831. ], Node.prototype, "metadata", void 0);
  18832. return Node;
  18833. }());
  18834. BABYLON.Node = Node;
  18835. })(BABYLON || (BABYLON = {}));
  18836. //# sourceMappingURL=babylon.node.js.map
  18837. var BABYLON;
  18838. (function (BABYLON) {
  18839. // This matrix is used as a value to reset the bounding box.
  18840. var _identityMatrix = BABYLON.Matrix.Identity();
  18841. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18842. /**
  18843. * Class used to store bounding sphere information
  18844. */
  18845. var BoundingSphere = /** @class */ (function () {
  18846. /**
  18847. * Creates a new bounding sphere
  18848. * @param min defines the minimum vector (in local space)
  18849. * @param max defines the maximum vector (in local space)
  18850. */
  18851. function BoundingSphere(min, max) {
  18852. this.center = BABYLON.Vector3.Zero();
  18853. this.centerWorld = BABYLON.Vector3.Zero();
  18854. this.reConstruct(min, max);
  18855. }
  18856. /**
  18857. * Recreates the entire bounding sphere from scratch
  18858. * @param min defines the new minimum vector (in local space)
  18859. * @param max defines the new maximum vector (in local space)
  18860. */
  18861. BoundingSphere.prototype.reConstruct = function (min, max) {
  18862. this.minimum = min.clone();
  18863. this.maximum = max.clone();
  18864. var distance = BABYLON.Vector3.Distance(min, max);
  18865. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18866. this.radius = distance * 0.5;
  18867. this.centerWorld.set(0, 0, 0);
  18868. this._update(_identityMatrix);
  18869. };
  18870. /**
  18871. * Scale the current bounding sphere by applying a scale factor
  18872. * @param factor defines the scale factor to apply
  18873. * @returns the current bounding box
  18874. */
  18875. BoundingSphere.prototype.scale = function (factor) {
  18876. var newRadius = this.radius * factor;
  18877. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18878. var min = this.center.subtract(_tempRadiusVector);
  18879. var max = this.center.add(_tempRadiusVector);
  18880. this.reConstruct(min, max);
  18881. return this;
  18882. };
  18883. // Methods
  18884. /** @hidden */
  18885. BoundingSphere.prototype._update = function (world) {
  18886. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18887. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18888. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18889. };
  18890. /**
  18891. * Tests if the bounding sphere is intersecting the frustum planes
  18892. * @param frustumPlanes defines the frustum planes to test
  18893. * @returns true if there is an intersection
  18894. */
  18895. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18896. for (var i = 0; i < 6; i++) {
  18897. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18898. return false;
  18899. }
  18900. return true;
  18901. };
  18902. /**
  18903. * Tests if a point is inside the bounding sphere
  18904. * @param point defines the point to test
  18905. * @returns true if the point is inside the bounding sphere
  18906. */
  18907. BoundingSphere.prototype.intersectsPoint = function (point) {
  18908. var x = this.centerWorld.x - point.x;
  18909. var y = this.centerWorld.y - point.y;
  18910. var z = this.centerWorld.z - point.z;
  18911. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18912. if (this.radiusWorld < distance)
  18913. return false;
  18914. return true;
  18915. };
  18916. // Statics
  18917. /**
  18918. * Checks if two sphere intersct
  18919. * @param sphere0 sphere 0
  18920. * @param sphere1 sphere 1
  18921. * @returns true if the speres intersect
  18922. */
  18923. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18924. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18925. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18926. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18927. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18928. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18929. return false;
  18930. return true;
  18931. };
  18932. return BoundingSphere;
  18933. }());
  18934. BABYLON.BoundingSphere = BoundingSphere;
  18935. })(BABYLON || (BABYLON = {}));
  18936. //# sourceMappingURL=babylon.boundingSphere.js.map
  18937. var BABYLON;
  18938. (function (BABYLON) {
  18939. /**
  18940. * Class used to store bounding box information
  18941. */
  18942. var BoundingBox = /** @class */ (function () {
  18943. /**
  18944. * Creates a new bounding box
  18945. * @param min defines the minimum vector (in local space)
  18946. * @param max defines the maximum vector (in local space)
  18947. */
  18948. function BoundingBox(min, max) {
  18949. /**
  18950. * Gets the 8 vectors representing the bounding box in world space
  18951. */
  18952. this.vectorsWorld = new Array();
  18953. this.reConstruct(min, max);
  18954. }
  18955. // Methods
  18956. /**
  18957. * Recreates the entire bounding box from scratch
  18958. * @param min defines the new minimum vector (in local space)
  18959. * @param max defines the new maximum vector (in local space)
  18960. */
  18961. BoundingBox.prototype.reConstruct = function (min, max) {
  18962. this.minimum = min.clone();
  18963. this.maximum = max.clone();
  18964. // Bounding vectors
  18965. this.vectors = [
  18966. this.minimum.clone(),
  18967. this.maximum.clone(),
  18968. this.minimum.clone(),
  18969. this.minimum.clone(),
  18970. this.minimum.clone(),
  18971. this.maximum.clone(),
  18972. this.maximum.clone(),
  18973. this.maximum.clone()
  18974. ];
  18975. this.vectors[2].x = this.maximum.x;
  18976. this.vectors[3].y = this.maximum.y;
  18977. this.vectors[4].z = this.maximum.z;
  18978. this.vectors[5].z = this.minimum.z;
  18979. this.vectors[6].x = this.minimum.x;
  18980. this.vectors[7].y = this.minimum.y;
  18981. // OBB
  18982. this.center = this.maximum.add(this.minimum).scale(0.5);
  18983. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18984. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18985. // World
  18986. for (var index = 0; index < this.vectors.length; index++) {
  18987. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18988. }
  18989. this.minimumWorld = BABYLON.Vector3.Zero();
  18990. this.maximumWorld = BABYLON.Vector3.Zero();
  18991. this.centerWorld = BABYLON.Vector3.Zero();
  18992. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18993. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18994. };
  18995. /**
  18996. * Scale the current bounding box by applying a scale factor
  18997. * @param factor defines the scale factor to apply
  18998. * @returns the current bounding box
  18999. */
  19000. BoundingBox.prototype.scale = function (factor) {
  19001. var diff = this.maximum.subtract(this.minimum);
  19002. var distance = diff.length() * factor;
  19003. diff.normalize();
  19004. var newRadius = diff.scale(distance / 2);
  19005. var min = this.center.subtract(newRadius);
  19006. var max = this.center.add(newRadius);
  19007. this.reConstruct(min, max);
  19008. return this;
  19009. };
  19010. /**
  19011. * Gets the world matrix of the bounding box
  19012. * @returns a matrix
  19013. */
  19014. BoundingBox.prototype.getWorldMatrix = function () {
  19015. return this._worldMatrix;
  19016. };
  19017. /**
  19018. * Sets the world matrix stored in the bounding box
  19019. * @param matrix defines the matrix to store
  19020. * @returns current bounding box
  19021. */
  19022. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19023. this._worldMatrix.copyFrom(matrix);
  19024. return this;
  19025. };
  19026. /** @hidden */
  19027. BoundingBox.prototype._update = function (world) {
  19028. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19029. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19030. for (var index = 0; index < this.vectors.length; index++) {
  19031. var v = this.vectorsWorld[index];
  19032. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19033. if (v.x < this.minimumWorld.x)
  19034. this.minimumWorld.x = v.x;
  19035. if (v.y < this.minimumWorld.y)
  19036. this.minimumWorld.y = v.y;
  19037. if (v.z < this.minimumWorld.z)
  19038. this.minimumWorld.z = v.z;
  19039. if (v.x > this.maximumWorld.x)
  19040. this.maximumWorld.x = v.x;
  19041. if (v.y > this.maximumWorld.y)
  19042. this.maximumWorld.y = v.y;
  19043. if (v.z > this.maximumWorld.z)
  19044. this.maximumWorld.z = v.z;
  19045. }
  19046. // Extend
  19047. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19048. this.extendSizeWorld.scaleInPlace(0.5);
  19049. // OBB
  19050. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19051. this.centerWorld.scaleInPlace(0.5);
  19052. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19053. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19054. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19055. this._worldMatrix = world;
  19056. };
  19057. /**
  19058. * Tests if the bounding box is intersecting the frustum planes
  19059. * @param frustumPlanes defines the frustum planes to test
  19060. * @returns true if there is an intersection
  19061. */
  19062. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19063. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19064. };
  19065. /**
  19066. * Tests if the bounding box is entirely inside the frustum planes
  19067. * @param frustumPlanes defines the frustum planes to test
  19068. * @returns true if there is an inclusion
  19069. */
  19070. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19071. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19072. };
  19073. /**
  19074. * Tests if a point is inside the bounding box
  19075. * @param point defines the point to test
  19076. * @returns true if the point is inside the bounding box
  19077. */
  19078. BoundingBox.prototype.intersectsPoint = function (point) {
  19079. var delta = -BABYLON.Epsilon;
  19080. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19081. return false;
  19082. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19083. return false;
  19084. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19085. return false;
  19086. return true;
  19087. };
  19088. /**
  19089. * Tests if the bounding box intersects with a bounding sphere
  19090. * @param sphere defines the sphere to test
  19091. * @returns true if there is an intersection
  19092. */
  19093. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19094. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19095. };
  19096. /**
  19097. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19098. * @param min defines the min vector to use
  19099. * @param max defines the max vector to use
  19100. * @returns true if there is an intersection
  19101. */
  19102. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19103. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19104. return false;
  19105. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19106. return false;
  19107. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19108. return false;
  19109. return true;
  19110. };
  19111. // Statics
  19112. /**
  19113. * Tests if two bounding boxes are intersections
  19114. * @param box0 defines the first box to test
  19115. * @param box1 defines the second box to test
  19116. * @returns true if there is an intersection
  19117. */
  19118. BoundingBox.Intersects = function (box0, box1) {
  19119. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19120. return false;
  19121. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19122. return false;
  19123. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19124. return false;
  19125. return true;
  19126. };
  19127. /**
  19128. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19129. * @param minPoint defines the minimum vector of the bounding box
  19130. * @param maxPoint defines the maximum vector of the bounding box
  19131. * @param sphereCenter defines the sphere center
  19132. * @param sphereRadius defines the sphere radius
  19133. * @returns true if there is an intersection
  19134. */
  19135. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19136. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19137. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19138. return (num <= (sphereRadius * sphereRadius));
  19139. };
  19140. /**
  19141. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19142. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19143. * @param frustumPlanes defines the frustum planes to test
  19144. * @return true if there is an inclusion
  19145. */
  19146. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19147. for (var p = 0; p < 6; p++) {
  19148. for (var i = 0; i < 8; i++) {
  19149. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19150. return false;
  19151. }
  19152. }
  19153. }
  19154. return true;
  19155. };
  19156. /**
  19157. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19158. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19159. * @param frustumPlanes defines the frustum planes to test
  19160. * @return true if there is an intersection
  19161. */
  19162. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19163. for (var p = 0; p < 6; p++) {
  19164. var inCount = 8;
  19165. for (var i = 0; i < 8; i++) {
  19166. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19167. --inCount;
  19168. }
  19169. else {
  19170. break;
  19171. }
  19172. }
  19173. if (inCount === 0)
  19174. return false;
  19175. }
  19176. return true;
  19177. };
  19178. return BoundingBox;
  19179. }());
  19180. BABYLON.BoundingBox = BoundingBox;
  19181. })(BABYLON || (BABYLON = {}));
  19182. //# sourceMappingURL=babylon.boundingBox.js.map
  19183. var BABYLON;
  19184. (function (BABYLON) {
  19185. var computeBoxExtents = function (axis, box) {
  19186. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19187. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19188. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19189. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19190. var r = r0 + r1 + r2;
  19191. return {
  19192. min: p - r,
  19193. max: p + r
  19194. };
  19195. };
  19196. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19197. var axisOverlap = function (axis, box0, box1) {
  19198. var result0 = computeBoxExtents(axis, box0);
  19199. var result1 = computeBoxExtents(axis, box1);
  19200. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19201. };
  19202. /**
  19203. * Info for a bounding data of a mesh
  19204. */
  19205. var BoundingInfo = /** @class */ (function () {
  19206. /**
  19207. * Constructs bounding info
  19208. * @param minimum min vector of the bounding box/sphere
  19209. * @param maximum max vector of the bounding box/sphere
  19210. */
  19211. function BoundingInfo(
  19212. /**
  19213. * min vector of the bounding box/sphere
  19214. */
  19215. minimum,
  19216. /**
  19217. * max vector of the bounding box/sphere
  19218. */
  19219. maximum) {
  19220. this.minimum = minimum;
  19221. this.maximum = maximum;
  19222. this._isLocked = false;
  19223. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19224. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19225. }
  19226. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19227. /**
  19228. * If the info is locked and won't be updated to avoid perf overhead
  19229. */
  19230. get: function () {
  19231. return this._isLocked;
  19232. },
  19233. set: function (value) {
  19234. this._isLocked = value;
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. // Methods
  19240. /**
  19241. * Updates the boudning sphere and box
  19242. * @param world world matrix to be used to update
  19243. */
  19244. BoundingInfo.prototype.update = function (world) {
  19245. if (this._isLocked) {
  19246. return;
  19247. }
  19248. this.boundingBox._update(world);
  19249. this.boundingSphere._update(world);
  19250. };
  19251. /**
  19252. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19253. * @param center New center of the bounding info
  19254. * @param extend New extend of the bounding info
  19255. * @returns the current bounding info
  19256. */
  19257. BoundingInfo.prototype.centerOn = function (center, extend) {
  19258. this.minimum = center.subtract(extend);
  19259. this.maximum = center.add(extend);
  19260. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  19261. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  19262. return this;
  19263. };
  19264. /**
  19265. * Scale the current bounding info by applying a scale factor
  19266. * @param factor defines the scale factor to apply
  19267. * @returns the current bounding info
  19268. */
  19269. BoundingInfo.prototype.scale = function (factor) {
  19270. this.boundingBox.scale(factor);
  19271. this.boundingSphere.scale(factor);
  19272. return this;
  19273. };
  19274. /**
  19275. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19276. * @param frustumPlanes defines the frustum to test
  19277. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19278. * @returns true if the bounding info is in the frustum planes
  19279. */
  19280. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19281. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19282. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19283. return false;
  19284. }
  19285. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19286. return true;
  19287. }
  19288. return this.boundingBox.isInFrustum(frustumPlanes);
  19289. };
  19290. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19291. /**
  19292. * Gets the world distance between the min and max points of the bounding box
  19293. */
  19294. get: function () {
  19295. var boundingBox = this.boundingBox;
  19296. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19297. return size.length();
  19298. },
  19299. enumerable: true,
  19300. configurable: true
  19301. });
  19302. /**
  19303. * Checks if a cullable object (mesh...) is in the camera frustum
  19304. * Unlike isInFrustum this cheks the full bounding box
  19305. * @param frustumPlanes Camera near/planes
  19306. * @returns true if the object is in frustum otherwise false
  19307. */
  19308. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19309. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19310. };
  19311. /** @hidden */
  19312. BoundingInfo.prototype._checkCollision = function (collider) {
  19313. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19314. };
  19315. /**
  19316. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19317. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19318. * @param point the point to check intersection with
  19319. * @returns if the point intersects
  19320. */
  19321. BoundingInfo.prototype.intersectsPoint = function (point) {
  19322. if (!this.boundingSphere.centerWorld) {
  19323. return false;
  19324. }
  19325. if (!this.boundingSphere.intersectsPoint(point)) {
  19326. return false;
  19327. }
  19328. if (!this.boundingBox.intersectsPoint(point)) {
  19329. return false;
  19330. }
  19331. return true;
  19332. };
  19333. /**
  19334. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19335. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19336. * @param boundingInfo the bounding info to check intersection with
  19337. * @param precise if the intersection should be done using OBB
  19338. * @returns if the bounding info intersects
  19339. */
  19340. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19341. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19342. return false;
  19343. }
  19344. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19345. return false;
  19346. }
  19347. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19348. return false;
  19349. }
  19350. if (!precise) {
  19351. return true;
  19352. }
  19353. var box0 = this.boundingBox;
  19354. var box1 = boundingInfo.boundingBox;
  19355. if (!axisOverlap(box0.directions[0], box0, box1))
  19356. return false;
  19357. if (!axisOverlap(box0.directions[1], box0, box1))
  19358. return false;
  19359. if (!axisOverlap(box0.directions[2], box0, box1))
  19360. return false;
  19361. if (!axisOverlap(box1.directions[0], box0, box1))
  19362. return false;
  19363. if (!axisOverlap(box1.directions[1], box0, box1))
  19364. return false;
  19365. if (!axisOverlap(box1.directions[2], box0, box1))
  19366. return false;
  19367. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19368. return false;
  19369. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19370. return false;
  19371. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19372. return false;
  19373. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19374. return false;
  19375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19376. return false;
  19377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19378. return false;
  19379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19380. return false;
  19381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19382. return false;
  19383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19384. return false;
  19385. return true;
  19386. };
  19387. return BoundingInfo;
  19388. }());
  19389. BABYLON.BoundingInfo = BoundingInfo;
  19390. })(BABYLON || (BABYLON = {}));
  19391. //# sourceMappingURL=babylon.boundingInfo.js.map
  19392. var BABYLON;
  19393. (function (BABYLON) {
  19394. var TransformNode = /** @class */ (function (_super) {
  19395. __extends(TransformNode, _super);
  19396. function TransformNode(name, scene, isPure) {
  19397. if (scene === void 0) { scene = null; }
  19398. if (isPure === void 0) { isPure = true; }
  19399. var _this = _super.call(this, name, scene) || this;
  19400. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19401. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19402. _this._up = new BABYLON.Vector3(0, 1, 0);
  19403. _this._right = new BABYLON.Vector3(1, 0, 0);
  19404. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19405. // Properties
  19406. _this._position = BABYLON.Vector3.Zero();
  19407. _this._rotation = BABYLON.Vector3.Zero();
  19408. _this._scaling = BABYLON.Vector3.One();
  19409. _this._isDirty = false;
  19410. /**
  19411. * Set the billboard mode. Default is 0.
  19412. *
  19413. * | Value | Type | Description |
  19414. * | --- | --- | --- |
  19415. * | 0 | BILLBOARDMODE_NONE | |
  19416. * | 1 | BILLBOARDMODE_X | |
  19417. * | 2 | BILLBOARDMODE_Y | |
  19418. * | 4 | BILLBOARDMODE_Z | |
  19419. * | 7 | BILLBOARDMODE_ALL | |
  19420. *
  19421. */
  19422. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19423. _this.scalingDeterminant = 1;
  19424. _this.infiniteDistance = false;
  19425. /**
  19426. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19427. * By default the system will update normals to compensate
  19428. */
  19429. _this.ignoreNonUniformScaling = false;
  19430. _this._localWorld = BABYLON.Matrix.Zero();
  19431. _this._absolutePosition = BABYLON.Vector3.Zero();
  19432. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19433. _this._postMultiplyPivotMatrix = false;
  19434. _this._isWorldMatrixFrozen = false;
  19435. /**
  19436. * An event triggered after the world matrix is updated
  19437. */
  19438. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19439. _this._nonUniformScaling = false;
  19440. if (isPure) {
  19441. _this.getScene().addTransformNode(_this);
  19442. }
  19443. return _this;
  19444. }
  19445. /**
  19446. * Gets a string identifying the name of the class
  19447. * @returns "TransformNode" string
  19448. */
  19449. TransformNode.prototype.getClassName = function () {
  19450. return "TransformNode";
  19451. };
  19452. Object.defineProperty(TransformNode.prototype, "position", {
  19453. /**
  19454. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19455. */
  19456. get: function () {
  19457. return this._position;
  19458. },
  19459. set: function (newPosition) {
  19460. this._position = newPosition;
  19461. this._isDirty = true;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(TransformNode.prototype, "rotation", {
  19467. /**
  19468. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19469. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19470. */
  19471. get: function () {
  19472. return this._rotation;
  19473. },
  19474. set: function (newRotation) {
  19475. this._rotation = newRotation;
  19476. this._isDirty = true;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(TransformNode.prototype, "scaling", {
  19482. /**
  19483. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  19484. */
  19485. get: function () {
  19486. return this._scaling;
  19487. },
  19488. set: function (newScaling) {
  19489. this._scaling = newScaling;
  19490. this._isDirty = true;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19496. /**
  19497. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19498. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19499. */
  19500. get: function () {
  19501. return this._rotationQuaternion;
  19502. },
  19503. set: function (quaternion) {
  19504. this._rotationQuaternion = quaternion;
  19505. //reset the rotation vector.
  19506. if (quaternion && this.rotation.length()) {
  19507. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19508. }
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(TransformNode.prototype, "forward", {
  19514. /**
  19515. * The forward direction of that transform in world space.
  19516. */
  19517. get: function () {
  19518. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(TransformNode.prototype, "up", {
  19524. /**
  19525. * The up direction of that transform in world space.
  19526. */
  19527. get: function () {
  19528. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(TransformNode.prototype, "right", {
  19534. /**
  19535. * The right direction of that transform in world space.
  19536. */
  19537. get: function () {
  19538. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. /**
  19544. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19545. * Returns the TransformNode.
  19546. */
  19547. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19548. this._poseMatrix.copyFrom(matrix);
  19549. return this;
  19550. };
  19551. /**
  19552. * Returns the mesh Pose matrix.
  19553. * Returned object : Matrix
  19554. */
  19555. TransformNode.prototype.getPoseMatrix = function () {
  19556. return this._poseMatrix;
  19557. };
  19558. /** @hidden */
  19559. TransformNode.prototype._isSynchronized = function () {
  19560. if (this._isDirty) {
  19561. return false;
  19562. }
  19563. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19564. return false;
  19565. if (this._cache.pivotMatrixUpdated) {
  19566. return false;
  19567. }
  19568. if (this.infiniteDistance) {
  19569. return false;
  19570. }
  19571. if (!this._cache.position.equals(this._position))
  19572. return false;
  19573. if (this._rotationQuaternion) {
  19574. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19575. return false;
  19576. }
  19577. if (!this._cache.rotation.equals(this._rotation))
  19578. return false;
  19579. if (!this._cache.scaling.equals(this._scaling))
  19580. return false;
  19581. return true;
  19582. };
  19583. /** @hidden */
  19584. TransformNode.prototype._initCache = function () {
  19585. _super.prototype._initCache.call(this);
  19586. this._cache.localMatrixUpdated = false;
  19587. this._cache.position = BABYLON.Vector3.Zero();
  19588. this._cache.scaling = BABYLON.Vector3.Zero();
  19589. this._cache.rotation = BABYLON.Vector3.Zero();
  19590. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19591. this._cache.billboardMode = -1;
  19592. };
  19593. TransformNode.prototype.markAsDirty = function (property) {
  19594. if (property === "rotation") {
  19595. this.rotationQuaternion = null;
  19596. }
  19597. this._currentRenderId = Number.MAX_VALUE;
  19598. this._isDirty = true;
  19599. return this;
  19600. };
  19601. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19602. /**
  19603. * Returns the current mesh absolute position.
  19604. * Returns a Vector3.
  19605. */
  19606. get: function () {
  19607. return this._absolutePosition;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. /**
  19613. * Sets a new matrix to apply before all other transformation
  19614. * @param matrix defines the transform matrix
  19615. * @returns the current TransformNode
  19616. */
  19617. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19618. return this.setPivotMatrix(matrix, false);
  19619. };
  19620. /**
  19621. * Sets a new pivot matrix to the current node
  19622. * @param matrix defines the new pivot matrix to use
  19623. * @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
  19624. * @returns the current TransformNode
  19625. */
  19626. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19627. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19628. this._pivotMatrix = matrix.clone();
  19629. this._cache.pivotMatrixUpdated = true;
  19630. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19631. if (this._postMultiplyPivotMatrix) {
  19632. if (!this._pivotMatrixInverse) {
  19633. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19634. }
  19635. else {
  19636. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19637. }
  19638. }
  19639. return this;
  19640. };
  19641. /**
  19642. * Returns the mesh pivot matrix.
  19643. * Default : Identity.
  19644. * A Matrix is returned.
  19645. */
  19646. TransformNode.prototype.getPivotMatrix = function () {
  19647. return this._pivotMatrix;
  19648. };
  19649. /**
  19650. * Prevents the World matrix to be computed any longer.
  19651. * Returns the TransformNode.
  19652. */
  19653. TransformNode.prototype.freezeWorldMatrix = function () {
  19654. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19655. this.computeWorldMatrix(true);
  19656. this._isWorldMatrixFrozen = true;
  19657. return this;
  19658. };
  19659. /**
  19660. * Allows back the World matrix computation.
  19661. * Returns the TransformNode.
  19662. */
  19663. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19664. this._isWorldMatrixFrozen = false;
  19665. this.computeWorldMatrix(true);
  19666. return this;
  19667. };
  19668. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19669. /**
  19670. * True if the World matrix has been frozen.
  19671. * Returns a boolean.
  19672. */
  19673. get: function () {
  19674. return this._isWorldMatrixFrozen;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. /**
  19680. * Retuns the mesh absolute position in the World.
  19681. * Returns a Vector3.
  19682. */
  19683. TransformNode.prototype.getAbsolutePosition = function () {
  19684. this.computeWorldMatrix();
  19685. return this._absolutePosition;
  19686. };
  19687. /**
  19688. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19689. * Returns the TransformNode.
  19690. */
  19691. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19692. if (!absolutePosition) {
  19693. return this;
  19694. }
  19695. var absolutePositionX;
  19696. var absolutePositionY;
  19697. var absolutePositionZ;
  19698. if (absolutePosition.x === undefined) {
  19699. if (arguments.length < 3) {
  19700. return this;
  19701. }
  19702. absolutePositionX = arguments[0];
  19703. absolutePositionY = arguments[1];
  19704. absolutePositionZ = arguments[2];
  19705. }
  19706. else {
  19707. absolutePositionX = absolutePosition.x;
  19708. absolutePositionY = absolutePosition.y;
  19709. absolutePositionZ = absolutePosition.z;
  19710. }
  19711. if (this.parent) {
  19712. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19713. invertParentWorldMatrix.invert();
  19714. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19715. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19716. }
  19717. else {
  19718. this.position.x = absolutePositionX;
  19719. this.position.y = absolutePositionY;
  19720. this.position.z = absolutePositionZ;
  19721. }
  19722. return this;
  19723. };
  19724. /**
  19725. * Sets the mesh position in its local space.
  19726. * Returns the TransformNode.
  19727. */
  19728. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19729. this.computeWorldMatrix();
  19730. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19731. return this;
  19732. };
  19733. /**
  19734. * Returns the mesh position in the local space from the current World matrix values.
  19735. * Returns a new Vector3.
  19736. */
  19737. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19738. this.computeWorldMatrix();
  19739. var invLocalWorldMatrix = this._localWorld.clone();
  19740. invLocalWorldMatrix.invert();
  19741. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19742. };
  19743. /**
  19744. * Translates the mesh along the passed Vector3 in its local space.
  19745. * Returns the TransformNode.
  19746. */
  19747. TransformNode.prototype.locallyTranslate = function (vector3) {
  19748. this.computeWorldMatrix(true);
  19749. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19750. return this;
  19751. };
  19752. /**
  19753. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19754. * @param targetPoint the position (must be in same space as current mesh) to look at
  19755. * @param yawCor optional yaw (y-axis) correction in radians
  19756. * @param pitchCor optional pitch (x-axis) correction in radians
  19757. * @param rollCor optional roll (z-axis) correction in radians
  19758. * @param space the choosen space of the target
  19759. * @returns the TransformNode.
  19760. */
  19761. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19762. if (yawCor === void 0) { yawCor = 0; }
  19763. if (pitchCor === void 0) { pitchCor = 0; }
  19764. if (rollCor === void 0) { rollCor = 0; }
  19765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19766. var dv = TransformNode._lookAtVectorCache;
  19767. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19768. targetPoint.subtractToRef(pos, dv);
  19769. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19770. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19771. var pitch = Math.atan2(dv.y, len);
  19772. if (this.rotationQuaternion) {
  19773. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19774. }
  19775. else {
  19776. this.rotation.x = pitch + pitchCor;
  19777. this.rotation.y = yaw + yawCor;
  19778. this.rotation.z = rollCor;
  19779. }
  19780. return this;
  19781. };
  19782. /**
  19783. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19784. * This Vector3 is expressed in the World space.
  19785. */
  19786. TransformNode.prototype.getDirection = function (localAxis) {
  19787. var result = BABYLON.Vector3.Zero();
  19788. this.getDirectionToRef(localAxis, result);
  19789. return result;
  19790. };
  19791. /**
  19792. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19793. * localAxis is expressed in the mesh local space.
  19794. * result is computed in the Wordl space from the mesh World matrix.
  19795. * Returns the TransformNode.
  19796. */
  19797. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19798. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19799. return this;
  19800. };
  19801. /**
  19802. * Sets a new pivot point to the current node
  19803. * @param point defines the new pivot point to use
  19804. * @param space defines if the point is in world or local space (local by default)
  19805. * @returns the current TransformNode
  19806. */
  19807. TransformNode.prototype.setPivotPoint = function (point, space) {
  19808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19809. if (this.getScene().getRenderId() == 0) {
  19810. this.computeWorldMatrix(true);
  19811. }
  19812. var wm = this.getWorldMatrix();
  19813. if (space == BABYLON.Space.WORLD) {
  19814. var tmat = BABYLON.Tmp.Matrix[0];
  19815. wm.invertToRef(tmat);
  19816. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19817. }
  19818. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19819. };
  19820. /**
  19821. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19822. */
  19823. TransformNode.prototype.getPivotPoint = function () {
  19824. var point = BABYLON.Vector3.Zero();
  19825. this.getPivotPointToRef(point);
  19826. return point;
  19827. };
  19828. /**
  19829. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19830. * Returns the TransformNode.
  19831. */
  19832. TransformNode.prototype.getPivotPointToRef = function (result) {
  19833. result.x = -this._pivotMatrix.m[12];
  19834. result.y = -this._pivotMatrix.m[13];
  19835. result.z = -this._pivotMatrix.m[14];
  19836. return this;
  19837. };
  19838. /**
  19839. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19840. */
  19841. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19842. var point = BABYLON.Vector3.Zero();
  19843. this.getAbsolutePivotPointToRef(point);
  19844. return point;
  19845. };
  19846. /**
  19847. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19848. * Returns the TransformNode.
  19849. */
  19850. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19851. result.x = this._pivotMatrix.m[12];
  19852. result.y = this._pivotMatrix.m[13];
  19853. result.z = this._pivotMatrix.m[14];
  19854. this.getPivotPointToRef(result);
  19855. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19856. return this;
  19857. };
  19858. /**
  19859. * Defines the passed node as the parent of the current node.
  19860. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19861. * Returns the TransformNode.
  19862. */
  19863. TransformNode.prototype.setParent = function (node) {
  19864. if (!node && !this.parent) {
  19865. return this;
  19866. }
  19867. if (!node) {
  19868. var rotation = BABYLON.Tmp.Quaternion[0];
  19869. var position = BABYLON.Tmp.Vector3[0];
  19870. var scale = BABYLON.Tmp.Vector3[1];
  19871. if (this.parent && this.parent.computeWorldMatrix) {
  19872. this.parent.computeWorldMatrix(true);
  19873. }
  19874. this.computeWorldMatrix(true);
  19875. this.getWorldMatrix().decompose(scale, rotation, position);
  19876. if (this.rotationQuaternion) {
  19877. this.rotationQuaternion.copyFrom(rotation);
  19878. }
  19879. else {
  19880. rotation.toEulerAnglesToRef(this.rotation);
  19881. }
  19882. this.scaling.x = scale.x;
  19883. this.scaling.y = scale.y;
  19884. this.scaling.z = scale.z;
  19885. this.position.x = position.x;
  19886. this.position.y = position.y;
  19887. this.position.z = position.z;
  19888. }
  19889. else {
  19890. var rotation = BABYLON.Tmp.Quaternion[0];
  19891. var position = BABYLON.Tmp.Vector3[0];
  19892. var scale = BABYLON.Tmp.Vector3[1];
  19893. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19894. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19895. this.computeWorldMatrix(true);
  19896. node.computeWorldMatrix(true);
  19897. node.getWorldMatrix().invertToRef(invParentMatrix);
  19898. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19899. diffMatrix.decompose(scale, rotation, position);
  19900. if (this.rotationQuaternion) {
  19901. this.rotationQuaternion.copyFrom(rotation);
  19902. }
  19903. else {
  19904. rotation.toEulerAnglesToRef(this.rotation);
  19905. }
  19906. this.position.x = position.x;
  19907. this.position.y = position.y;
  19908. this.position.z = position.z;
  19909. this.scaling.x = scale.x;
  19910. this.scaling.y = scale.y;
  19911. this.scaling.z = scale.z;
  19912. }
  19913. this.parent = node;
  19914. return this;
  19915. };
  19916. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19917. get: function () {
  19918. return this._nonUniformScaling;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. /** @hidden */
  19924. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19925. if (this._nonUniformScaling === value) {
  19926. return false;
  19927. }
  19928. this._nonUniformScaling = value;
  19929. return true;
  19930. };
  19931. /**
  19932. * Attach the current TransformNode to another TransformNode associated with a bone
  19933. * @param bone Bone affecting the TransformNode
  19934. * @param affectedTransformNode TransformNode associated with the bone
  19935. */
  19936. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19937. this._transformToBoneReferal = affectedTransformNode;
  19938. this.parent = bone;
  19939. if (bone.getWorldMatrix().determinant() < 0) {
  19940. this.scalingDeterminant *= -1;
  19941. }
  19942. return this;
  19943. };
  19944. TransformNode.prototype.detachFromBone = function () {
  19945. if (!this.parent) {
  19946. return this;
  19947. }
  19948. if (this.parent.getWorldMatrix().determinant() < 0) {
  19949. this.scalingDeterminant *= -1;
  19950. }
  19951. this._transformToBoneReferal = null;
  19952. this.parent = null;
  19953. return this;
  19954. };
  19955. /**
  19956. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19957. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19958. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19959. * The passed axis is also normalized.
  19960. * Returns the TransformNode.
  19961. */
  19962. TransformNode.prototype.rotate = function (axis, amount, space) {
  19963. axis.normalize();
  19964. if (!this.rotationQuaternion) {
  19965. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19966. this.rotation = BABYLON.Vector3.Zero();
  19967. }
  19968. var rotationQuaternion;
  19969. if (!space || space === BABYLON.Space.LOCAL) {
  19970. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19971. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19972. }
  19973. else {
  19974. if (this.parent) {
  19975. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19976. invertParentWorldMatrix.invert();
  19977. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19978. }
  19979. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19980. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19981. }
  19982. return this;
  19983. };
  19984. /**
  19985. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19986. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19987. * The passed axis is also normalized.
  19988. * Returns the TransformNode.
  19989. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19990. */
  19991. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19992. axis.normalize();
  19993. if (!this.rotationQuaternion) {
  19994. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19995. this.rotation.copyFromFloats(0, 0, 0);
  19996. }
  19997. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19998. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19999. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20000. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20001. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20002. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20003. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20004. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20005. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20006. return this;
  20007. };
  20008. /**
  20009. * Translates the mesh along the axis vector for the passed distance in the given space.
  20010. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20011. * Returns the TransformNode.
  20012. */
  20013. TransformNode.prototype.translate = function (axis, distance, space) {
  20014. var displacementVector = axis.scale(distance);
  20015. if (!space || space === BABYLON.Space.LOCAL) {
  20016. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20017. this.setPositionWithLocalVector(tempV3);
  20018. }
  20019. else {
  20020. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20021. }
  20022. return this;
  20023. };
  20024. /**
  20025. * Adds a rotation step to the mesh current rotation.
  20026. * x, y, z are Euler angles expressed in radians.
  20027. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20028. * This means this rotation is made in the mesh local space only.
  20029. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20030. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20031. * ```javascript
  20032. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20033. * ```
  20034. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20035. * 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.
  20036. * Returns the TransformNode.
  20037. */
  20038. TransformNode.prototype.addRotation = function (x, y, z) {
  20039. var rotationQuaternion;
  20040. if (this.rotationQuaternion) {
  20041. rotationQuaternion = this.rotationQuaternion;
  20042. }
  20043. else {
  20044. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20045. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20046. }
  20047. var accumulation = BABYLON.Tmp.Quaternion[0];
  20048. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20049. rotationQuaternion.multiplyInPlace(accumulation);
  20050. if (!this.rotationQuaternion) {
  20051. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20052. }
  20053. return this;
  20054. };
  20055. /**
  20056. * Computes the world matrix of the node
  20057. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20058. * @returns the world matrix
  20059. */
  20060. TransformNode.prototype.computeWorldMatrix = function (force) {
  20061. if (this._isWorldMatrixFrozen) {
  20062. return this._worldMatrix;
  20063. }
  20064. if (!force && this.isSynchronized()) {
  20065. this._currentRenderId = this.getScene().getRenderId();
  20066. return this._worldMatrix;
  20067. }
  20068. this._updateCache();
  20069. this._cache.position.copyFrom(this.position);
  20070. this._cache.scaling.copyFrom(this.scaling);
  20071. this._cache.pivotMatrixUpdated = false;
  20072. this._cache.billboardMode = this.billboardMode;
  20073. this._currentRenderId = this.getScene().getRenderId();
  20074. this._childRenderId = this.getScene().getRenderId();
  20075. this._isDirty = false;
  20076. // Scaling
  20077. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20078. // Rotation
  20079. //rotate, if quaternion is set and rotation was used
  20080. if (this.rotationQuaternion) {
  20081. var len = this.rotation.length();
  20082. if (len) {
  20083. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20084. this.rotation.copyFromFloats(0, 0, 0);
  20085. }
  20086. }
  20087. if (this.rotationQuaternion) {
  20088. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20089. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20090. }
  20091. else {
  20092. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20093. this._cache.rotation.copyFrom(this.rotation);
  20094. }
  20095. // Translation
  20096. var camera = this.getScene().activeCamera;
  20097. if (this.infiniteDistance && !this.parent && camera) {
  20098. var cameraWorldMatrix = camera.getWorldMatrix();
  20099. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20100. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20101. }
  20102. else {
  20103. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20104. }
  20105. // Composing transformations
  20106. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20107. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20108. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20109. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20110. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20111. // Need to decompose each rotation here
  20112. var currentPosition = BABYLON.Tmp.Vector3[3];
  20113. if (this.parent && this.parent.getWorldMatrix) {
  20114. if (this._transformToBoneReferal) {
  20115. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20116. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20117. }
  20118. else {
  20119. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20120. }
  20121. }
  20122. else {
  20123. currentPosition.copyFrom(this.position);
  20124. }
  20125. currentPosition.subtractInPlace(camera.globalPosition);
  20126. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20127. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20128. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20129. }
  20130. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20131. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20132. }
  20133. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20134. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20135. }
  20136. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20137. }
  20138. else {
  20139. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20140. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20141. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20142. }
  20143. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20144. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20145. }
  20146. // Post multiply inverse of pivotMatrix
  20147. if (this._postMultiplyPivotMatrix) {
  20148. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20149. }
  20150. // Local world
  20151. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20152. // Parent
  20153. if (this.parent && this.parent.getWorldMatrix) {
  20154. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20155. if (this._transformToBoneReferal) {
  20156. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20157. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20158. }
  20159. else {
  20160. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20161. }
  20162. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20163. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20164. this._worldMatrix.copyFrom(this._localWorld);
  20165. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20166. }
  20167. else {
  20168. if (this._transformToBoneReferal) {
  20169. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20170. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20171. }
  20172. else {
  20173. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20174. }
  20175. }
  20176. this._markSyncedWithParent();
  20177. }
  20178. else {
  20179. this._worldMatrix.copyFrom(this._localWorld);
  20180. }
  20181. // Normal matrix
  20182. if (!this.ignoreNonUniformScaling) {
  20183. if (this.scaling.isNonUniform) {
  20184. this._updateNonUniformScalingState(true);
  20185. }
  20186. else if (this.parent && this.parent._nonUniformScaling) {
  20187. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20188. }
  20189. else {
  20190. this._updateNonUniformScalingState(false);
  20191. }
  20192. }
  20193. else {
  20194. this._updateNonUniformScalingState(false);
  20195. }
  20196. this._afterComputeWorldMatrix();
  20197. // Absolute position
  20198. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20199. // Callbacks
  20200. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20201. if (!this._poseMatrix) {
  20202. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20203. }
  20204. // Cache the determinant
  20205. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20206. return this._worldMatrix;
  20207. };
  20208. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20209. };
  20210. /**
  20211. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20212. * @param func: callback function to add
  20213. *
  20214. * Returns the TransformNode.
  20215. */
  20216. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20217. this.onAfterWorldMatrixUpdateObservable.add(func);
  20218. return this;
  20219. };
  20220. /**
  20221. * Removes a registered callback function.
  20222. * Returns the TransformNode.
  20223. */
  20224. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20225. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20226. return this;
  20227. };
  20228. /**
  20229. * Clone the current transform node
  20230. * Returns the new transform node
  20231. * @param name Name of the new clone
  20232. * @param newParent New parent for the clone
  20233. * @param doNotCloneChildren Do not clone children hierarchy
  20234. */
  20235. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20236. var _this = this;
  20237. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20238. result.name = name;
  20239. result.id = name;
  20240. if (newParent) {
  20241. result.parent = newParent;
  20242. }
  20243. if (!doNotCloneChildren) {
  20244. // Children
  20245. var directDescendants = this.getDescendants(true);
  20246. for (var index = 0; index < directDescendants.length; index++) {
  20247. var child = directDescendants[index];
  20248. if (child.clone) {
  20249. child.clone(name + "." + child.name, result);
  20250. }
  20251. }
  20252. }
  20253. return result;
  20254. };
  20255. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20256. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20257. serializationObject.type = this.getClassName();
  20258. // Parent
  20259. if (this.parent) {
  20260. serializationObject.parentId = this.parent.id;
  20261. }
  20262. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20263. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20264. }
  20265. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20266. serializationObject.isEnabled = this.isEnabled();
  20267. // Parent
  20268. if (this.parent) {
  20269. serializationObject.parentId = this.parent.id;
  20270. }
  20271. return serializationObject;
  20272. };
  20273. // Statics
  20274. /**
  20275. * Returns a new TransformNode object parsed from the source provided.
  20276. * The parameter `parsedMesh` is the source.
  20277. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20278. */
  20279. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20280. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20281. if (BABYLON.Tags) {
  20282. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20283. }
  20284. if (parsedTransformNode.localMatrix) {
  20285. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20286. }
  20287. else if (parsedTransformNode.pivotMatrix) {
  20288. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20289. }
  20290. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20291. // Parent
  20292. if (parsedTransformNode.parentId) {
  20293. transformNode._waitingParentId = parsedTransformNode.parentId;
  20294. }
  20295. return transformNode;
  20296. };
  20297. /**
  20298. * Releases resources associated with this transform node.
  20299. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20300. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20301. */
  20302. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20303. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20304. // Animations
  20305. this.getScene().stopAnimation(this);
  20306. // Remove from scene
  20307. this.getScene().removeTransformNode(this);
  20308. this.onAfterWorldMatrixUpdateObservable.clear();
  20309. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20310. };
  20311. // Statics
  20312. TransformNode.BILLBOARDMODE_NONE = 0;
  20313. TransformNode.BILLBOARDMODE_X = 1;
  20314. TransformNode.BILLBOARDMODE_Y = 2;
  20315. TransformNode.BILLBOARDMODE_Z = 4;
  20316. TransformNode.BILLBOARDMODE_ALL = 7;
  20317. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20318. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20319. __decorate([
  20320. BABYLON.serializeAsVector3("position")
  20321. ], TransformNode.prototype, "_position", void 0);
  20322. __decorate([
  20323. BABYLON.serializeAsVector3("rotation")
  20324. ], TransformNode.prototype, "_rotation", void 0);
  20325. __decorate([
  20326. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20327. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20328. __decorate([
  20329. BABYLON.serializeAsVector3("scaling")
  20330. ], TransformNode.prototype, "_scaling", void 0);
  20331. __decorate([
  20332. BABYLON.serialize()
  20333. ], TransformNode.prototype, "billboardMode", void 0);
  20334. __decorate([
  20335. BABYLON.serialize()
  20336. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20337. __decorate([
  20338. BABYLON.serialize()
  20339. ], TransformNode.prototype, "infiniteDistance", void 0);
  20340. __decorate([
  20341. BABYLON.serialize()
  20342. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20343. return TransformNode;
  20344. }(BABYLON.Node));
  20345. BABYLON.TransformNode = TransformNode;
  20346. })(BABYLON || (BABYLON = {}));
  20347. //# sourceMappingURL=babylon.transformNode.js.map
  20348. var BABYLON;
  20349. (function (BABYLON) {
  20350. /** @hidden */
  20351. var _FacetDataStorage = /** @class */ (function () {
  20352. function _FacetDataStorage() {
  20353. this.facetNb = 0; // facet number
  20354. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20355. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20356. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20357. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20358. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20359. this.subDiv = {
  20360. max: 1,
  20361. X: 1,
  20362. Y: 1,
  20363. Z: 1
  20364. };
  20365. this.facetDepthSort = false; // is the facet depth sort to be computed
  20366. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20367. }
  20368. return _FacetDataStorage;
  20369. }());
  20370. /**
  20371. * Class used to store all common mesh properties
  20372. */
  20373. var AbstractMesh = /** @class */ (function (_super) {
  20374. __extends(AbstractMesh, _super);
  20375. // Constructor
  20376. /**
  20377. * Creates a new AbstractMesh
  20378. * @param name defines the name of the mesh
  20379. * @param scene defines the hosting scene
  20380. */
  20381. function AbstractMesh(name, scene) {
  20382. if (scene === void 0) { scene = null; }
  20383. var _this = _super.call(this, name, scene, false) || this;
  20384. _this._facetData = new _FacetDataStorage();
  20385. /** Gets ot sets the culling strategy to use to find visible meshes */
  20386. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20387. // Events
  20388. /**
  20389. * An event triggered when this mesh collides with another one
  20390. */
  20391. _this.onCollideObservable = new BABYLON.Observable();
  20392. /**
  20393. * An event triggered when the collision's position changes
  20394. */
  20395. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20396. /**
  20397. * An event triggered when material is changed
  20398. */
  20399. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20400. // Properties
  20401. /**
  20402. * Gets or sets the orientation for POV movement & rotation
  20403. */
  20404. _this.definedFacingForward = true;
  20405. _this._visibility = 1.0;
  20406. /** Gets or sets the alpha index used to sort transparent meshes
  20407. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20408. */
  20409. _this.alphaIndex = Number.MAX_VALUE;
  20410. /**
  20411. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20412. */
  20413. _this.isVisible = true;
  20414. /**
  20415. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20416. */
  20417. _this.isPickable = true;
  20418. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20419. _this.showSubMeshesBoundingBox = false;
  20420. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20421. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20422. */
  20423. _this.isBlocker = false;
  20424. /**
  20425. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20426. */
  20427. _this.enablePointerMoveEvents = false;
  20428. /**
  20429. * Specifies the rendering group id for this mesh (0 by default)
  20430. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20431. */
  20432. _this.renderingGroupId = 0;
  20433. _this._receiveShadows = false;
  20434. /** Defines color to use when rendering outline */
  20435. _this.outlineColor = BABYLON.Color3.Red();
  20436. /** Define width to use when rendering outline */
  20437. _this.outlineWidth = 0.02;
  20438. /** Defines color to use when rendering overlay */
  20439. _this.overlayColor = BABYLON.Color3.Red();
  20440. /** Defines alpha to use when rendering overlay */
  20441. _this.overlayAlpha = 0.5;
  20442. _this._hasVertexAlpha = false;
  20443. _this._useVertexColors = true;
  20444. _this._computeBonesUsingShaders = true;
  20445. _this._numBoneInfluencers = 4;
  20446. _this._applyFog = true;
  20447. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20448. _this.useOctreeForRenderingSelection = true;
  20449. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20450. _this.useOctreeForPicking = true;
  20451. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20452. _this.useOctreeForCollisions = true;
  20453. _this._layerMask = 0x0FFFFFFF;
  20454. /**
  20455. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20456. */
  20457. _this.alwaysSelectAsActiveMesh = false;
  20458. /**
  20459. * Gets or sets the current action manager
  20460. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20461. */
  20462. _this.actionManager = null;
  20463. // Collisions
  20464. _this._checkCollisions = false;
  20465. _this._collisionMask = -1;
  20466. _this._collisionGroup = -1;
  20467. /**
  20468. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20469. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20470. */
  20471. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20472. /**
  20473. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20474. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20475. */
  20476. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20477. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20478. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20479. // Edges
  20480. /**
  20481. * Defines edge width used when edgesRenderer is enabled
  20482. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20483. */
  20484. _this.edgesWidth = 1;
  20485. /**
  20486. * Defines edge color used when edgesRenderer is enabled
  20487. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20488. */
  20489. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20490. // Cache
  20491. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20492. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20493. /** @hidden */
  20494. _this._renderId = 0;
  20495. /** @hidden */
  20496. _this._intersectionsInProgress = new Array();
  20497. /** @hidden */
  20498. _this._unIndexed = false;
  20499. /** @hidden */
  20500. _this._lightSources = new Array();
  20501. /**
  20502. * An event triggered when the mesh is rebuilt.
  20503. */
  20504. _this.onRebuildObservable = new BABYLON.Observable();
  20505. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20506. if (collidedMesh === void 0) { collidedMesh = null; }
  20507. //TODO move this to the collision coordinator!
  20508. if (_this.getScene().workerCollisions)
  20509. newPosition.multiplyInPlace(_this._collider._radius);
  20510. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20511. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20512. _this.position.addInPlace(_this._diffPositionForCollisions);
  20513. }
  20514. if (collidedMesh) {
  20515. _this.onCollideObservable.notifyObservers(collidedMesh);
  20516. }
  20517. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20518. };
  20519. _this.getScene().addMesh(_this);
  20520. _this._resyncLightSources();
  20521. return _this;
  20522. }
  20523. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20524. /**
  20525. * No billboard
  20526. */
  20527. get: function () {
  20528. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20529. },
  20530. enumerable: true,
  20531. configurable: true
  20532. });
  20533. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20534. /** Billboard on X axis */
  20535. get: function () {
  20536. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20537. },
  20538. enumerable: true,
  20539. configurable: true
  20540. });
  20541. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20542. /** Billboard on Y axis */
  20543. get: function () {
  20544. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20550. /** Billboard on Z axis */
  20551. get: function () {
  20552. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20553. },
  20554. enumerable: true,
  20555. configurable: true
  20556. });
  20557. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20558. /** Billboard on all axes */
  20559. get: function () {
  20560. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20561. },
  20562. enumerable: true,
  20563. configurable: true
  20564. });
  20565. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20566. /**
  20567. * Gets the number of facets in the mesh
  20568. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20569. */
  20570. get: function () {
  20571. return this._facetData.facetNb;
  20572. },
  20573. enumerable: true,
  20574. configurable: true
  20575. });
  20576. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20577. /**
  20578. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20579. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20580. */
  20581. get: function () {
  20582. return this._facetData.partitioningSubdivisions;
  20583. },
  20584. set: function (nb) {
  20585. this._facetData.partitioningSubdivisions = nb;
  20586. },
  20587. enumerable: true,
  20588. configurable: true
  20589. });
  20590. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20591. /**
  20592. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20593. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20594. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20595. */
  20596. get: function () {
  20597. return this._facetData.partitioningBBoxRatio;
  20598. },
  20599. set: function (ratio) {
  20600. this._facetData.partitioningBBoxRatio = ratio;
  20601. },
  20602. enumerable: true,
  20603. configurable: true
  20604. });
  20605. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20606. /**
  20607. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20608. * Works only for updatable meshes.
  20609. * Doesn't work with multi-materials
  20610. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20611. */
  20612. get: function () {
  20613. return this._facetData.facetDepthSort;
  20614. },
  20615. set: function (sort) {
  20616. this._facetData.facetDepthSort = sort;
  20617. },
  20618. enumerable: true,
  20619. configurable: true
  20620. });
  20621. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20622. /**
  20623. * The location (Vector3) where the facet depth sort must be computed from.
  20624. * By default, the active camera position.
  20625. * Used only when facet depth sort is enabled
  20626. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20627. */
  20628. get: function () {
  20629. return this._facetData.facetDepthSortFrom;
  20630. },
  20631. set: function (location) {
  20632. this._facetData.facetDepthSortFrom = location;
  20633. },
  20634. enumerable: true,
  20635. configurable: true
  20636. });
  20637. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20638. /**
  20639. * gets a boolean indicating if facetData is enabled
  20640. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20641. */
  20642. get: function () {
  20643. return this._facetData.facetDataEnabled;
  20644. },
  20645. enumerable: true,
  20646. configurable: true
  20647. });
  20648. /** @hidden */
  20649. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20650. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20651. return false;
  20652. }
  20653. this._markSubMeshesAsMiscDirty();
  20654. return true;
  20655. };
  20656. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20657. /** Set a function to call when this mesh collides with another one */
  20658. set: function (callback) {
  20659. if (this._onCollideObserver) {
  20660. this.onCollideObservable.remove(this._onCollideObserver);
  20661. }
  20662. this._onCollideObserver = this.onCollideObservable.add(callback);
  20663. },
  20664. enumerable: true,
  20665. configurable: true
  20666. });
  20667. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20668. /** Set a function to call when the collision's position changes */
  20669. set: function (callback) {
  20670. if (this._onCollisionPositionChangeObserver) {
  20671. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20672. }
  20673. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20674. },
  20675. enumerable: true,
  20676. configurable: true
  20677. });
  20678. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20679. /**
  20680. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20681. */
  20682. get: function () {
  20683. return this._visibility;
  20684. },
  20685. /**
  20686. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20687. */
  20688. set: function (value) {
  20689. if (this._visibility === value) {
  20690. return;
  20691. }
  20692. this._visibility = value;
  20693. this._markSubMeshesAsMiscDirty();
  20694. },
  20695. enumerable: true,
  20696. configurable: true
  20697. });
  20698. Object.defineProperty(AbstractMesh.prototype, "material", {
  20699. /** Gets or sets current material */
  20700. get: function () {
  20701. return this._material;
  20702. },
  20703. set: function (value) {
  20704. if (this._material === value) {
  20705. return;
  20706. }
  20707. this._material = value;
  20708. if (this.onMaterialChangedObservable.hasObservers) {
  20709. this.onMaterialChangedObservable.notifyObservers(this);
  20710. }
  20711. if (!this.subMeshes) {
  20712. return;
  20713. }
  20714. this._unBindEffect();
  20715. },
  20716. enumerable: true,
  20717. configurable: true
  20718. });
  20719. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20720. /**
  20721. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20722. * @see http://doc.babylonjs.com/babylon101/shadows
  20723. */
  20724. get: function () {
  20725. return this._receiveShadows;
  20726. },
  20727. set: function (value) {
  20728. if (this._receiveShadows === value) {
  20729. return;
  20730. }
  20731. this._receiveShadows = value;
  20732. this._markSubMeshesAsLightDirty();
  20733. },
  20734. enumerable: true,
  20735. configurable: true
  20736. });
  20737. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20738. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20739. get: function () {
  20740. return this._hasVertexAlpha;
  20741. },
  20742. set: function (value) {
  20743. if (this._hasVertexAlpha === value) {
  20744. return;
  20745. }
  20746. this._hasVertexAlpha = value;
  20747. this._markSubMeshesAsAttributesDirty();
  20748. this._markSubMeshesAsMiscDirty();
  20749. },
  20750. enumerable: true,
  20751. configurable: true
  20752. });
  20753. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20754. /** 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) */
  20755. get: function () {
  20756. return this._useVertexColors;
  20757. },
  20758. set: function (value) {
  20759. if (this._useVertexColors === value) {
  20760. return;
  20761. }
  20762. this._useVertexColors = value;
  20763. this._markSubMeshesAsAttributesDirty();
  20764. },
  20765. enumerable: true,
  20766. configurable: true
  20767. });
  20768. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20769. /**
  20770. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20771. */
  20772. get: function () {
  20773. return this._computeBonesUsingShaders;
  20774. },
  20775. set: function (value) {
  20776. if (this._computeBonesUsingShaders === value) {
  20777. return;
  20778. }
  20779. this._computeBonesUsingShaders = value;
  20780. this._markSubMeshesAsAttributesDirty();
  20781. },
  20782. enumerable: true,
  20783. configurable: true
  20784. });
  20785. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20786. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20787. get: function () {
  20788. return this._numBoneInfluencers;
  20789. },
  20790. set: function (value) {
  20791. if (this._numBoneInfluencers === value) {
  20792. return;
  20793. }
  20794. this._numBoneInfluencers = value;
  20795. this._markSubMeshesAsAttributesDirty();
  20796. },
  20797. enumerable: true,
  20798. configurable: true
  20799. });
  20800. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20801. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20802. get: function () {
  20803. return this._applyFog;
  20804. },
  20805. set: function (value) {
  20806. if (this._applyFog === value) {
  20807. return;
  20808. }
  20809. this._applyFog = value;
  20810. this._markSubMeshesAsMiscDirty();
  20811. },
  20812. enumerable: true,
  20813. configurable: true
  20814. });
  20815. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20816. /**
  20817. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20818. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20819. */
  20820. get: function () {
  20821. return this._layerMask;
  20822. },
  20823. set: function (value) {
  20824. if (value === this._layerMask) {
  20825. return;
  20826. }
  20827. this._layerMask = value;
  20828. this._resyncLightSources();
  20829. },
  20830. enumerable: true,
  20831. configurable: true
  20832. });
  20833. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20834. /**
  20835. * Gets or sets a collision mask used to mask collisions (default is -1).
  20836. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20837. */
  20838. get: function () {
  20839. return this._collisionMask;
  20840. },
  20841. set: function (mask) {
  20842. this._collisionMask = !isNaN(mask) ? mask : -1;
  20843. },
  20844. enumerable: true,
  20845. configurable: true
  20846. });
  20847. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20848. /**
  20849. * Gets or sets the current collision group mask (-1 by default).
  20850. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20851. */
  20852. get: function () {
  20853. return this._collisionGroup;
  20854. },
  20855. set: function (mask) {
  20856. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20862. /** @hidden */
  20863. get: function () {
  20864. return null;
  20865. },
  20866. enumerable: true,
  20867. configurable: true
  20868. });
  20869. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20870. get: function () {
  20871. return this._skeleton;
  20872. },
  20873. /**
  20874. * Gets or sets a skeleton to apply skining transformations
  20875. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20876. */
  20877. set: function (value) {
  20878. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20879. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20880. }
  20881. if (value && value.needInitialSkinMatrix) {
  20882. value._registerMeshWithPoseMatrix(this);
  20883. }
  20884. this._skeleton = value;
  20885. if (!this._skeleton) {
  20886. this._bonesTransformMatrices = null;
  20887. }
  20888. this._markSubMeshesAsAttributesDirty();
  20889. },
  20890. enumerable: true,
  20891. configurable: true
  20892. });
  20893. /**
  20894. * Returns the string "AbstractMesh"
  20895. * @returns "AbstractMesh"
  20896. */
  20897. AbstractMesh.prototype.getClassName = function () {
  20898. return "AbstractMesh";
  20899. };
  20900. /**
  20901. * Gets a string representation of the current mesh
  20902. * @param fullDetails defines a boolean indicating if full details must be included
  20903. * @returns a string representation of the current mesh
  20904. */
  20905. AbstractMesh.prototype.toString = function (fullDetails) {
  20906. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20907. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20908. if (this._skeleton) {
  20909. ret += ", skeleton: " + this._skeleton.name;
  20910. }
  20911. if (fullDetails) {
  20912. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20913. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20914. }
  20915. return ret;
  20916. };
  20917. /** @hidden */
  20918. AbstractMesh.prototype._rebuild = function () {
  20919. this.onRebuildObservable.notifyObservers(this);
  20920. if (this._occlusionQuery) {
  20921. this._occlusionQuery = null;
  20922. }
  20923. if (!this.subMeshes) {
  20924. return;
  20925. }
  20926. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20927. var subMesh = _a[_i];
  20928. subMesh._rebuild();
  20929. }
  20930. };
  20931. /** @hidden */
  20932. AbstractMesh.prototype._resyncLightSources = function () {
  20933. this._lightSources.length = 0;
  20934. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20935. var light = _a[_i];
  20936. if (!light.isEnabled()) {
  20937. continue;
  20938. }
  20939. if (light.canAffectMesh(this)) {
  20940. this._lightSources.push(light);
  20941. }
  20942. }
  20943. this._markSubMeshesAsLightDirty();
  20944. };
  20945. /** @hidden */
  20946. AbstractMesh.prototype._resyncLighSource = function (light) {
  20947. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20948. var index = this._lightSources.indexOf(light);
  20949. if (index === -1) {
  20950. if (!isIn) {
  20951. return;
  20952. }
  20953. this._lightSources.push(light);
  20954. }
  20955. else {
  20956. if (isIn) {
  20957. return;
  20958. }
  20959. this._lightSources.splice(index, 1);
  20960. }
  20961. this._markSubMeshesAsLightDirty();
  20962. };
  20963. /** @hidden */
  20964. AbstractMesh.prototype._unBindEffect = function () {
  20965. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20966. var subMesh = _a[_i];
  20967. subMesh.setEffect(null);
  20968. }
  20969. };
  20970. /** @hidden */
  20971. AbstractMesh.prototype._removeLightSource = function (light) {
  20972. var index = this._lightSources.indexOf(light);
  20973. if (index === -1) {
  20974. return;
  20975. }
  20976. this._lightSources.splice(index, 1);
  20977. this._markSubMeshesAsLightDirty();
  20978. };
  20979. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20980. if (!this.subMeshes) {
  20981. return;
  20982. }
  20983. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20984. var subMesh = _a[_i];
  20985. if (subMesh._materialDefines) {
  20986. func(subMesh._materialDefines);
  20987. }
  20988. }
  20989. };
  20990. /** @hidden */
  20991. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20992. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20993. };
  20994. /** @hidden */
  20995. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20996. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20997. };
  20998. /** @hidden */
  20999. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21000. if (!this.subMeshes) {
  21001. return;
  21002. }
  21003. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21004. var subMesh = _a[_i];
  21005. var material = subMesh.getMaterial();
  21006. if (material) {
  21007. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21008. }
  21009. }
  21010. };
  21011. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21012. /**
  21013. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21014. */
  21015. get: function () {
  21016. return this._scaling;
  21017. },
  21018. set: function (newScaling) {
  21019. this._scaling = newScaling;
  21020. if (this.physicsImpostor) {
  21021. this.physicsImpostor.forceUpdate();
  21022. }
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21028. // Methods
  21029. /**
  21030. * Returns true if the mesh is blocked. Implemented by child classes
  21031. */
  21032. get: function () {
  21033. return false;
  21034. },
  21035. enumerable: true,
  21036. configurable: true
  21037. });
  21038. /**
  21039. * Returns the mesh itself by default. Implemented by child classes
  21040. * @param camera defines the camera to use to pick the right LOD level
  21041. * @returns the currentAbstractMesh
  21042. */
  21043. AbstractMesh.prototype.getLOD = function (camera) {
  21044. return this;
  21045. };
  21046. /**
  21047. * Returns 0 by default. Implemented by child classes
  21048. * @returns an integer
  21049. */
  21050. AbstractMesh.prototype.getTotalVertices = function () {
  21051. return 0;
  21052. };
  21053. /**
  21054. * Returns null by default. Implemented by child classes
  21055. * @returns null
  21056. */
  21057. AbstractMesh.prototype.getIndices = function () {
  21058. return null;
  21059. };
  21060. /**
  21061. * Returns the array of the requested vertex data kind. Implemented by child classes
  21062. * @param kind defines the vertex data kind to use
  21063. * @returns null
  21064. */
  21065. AbstractMesh.prototype.getVerticesData = function (kind) {
  21066. return null;
  21067. };
  21068. /**
  21069. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21070. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21071. * Note that a new underlying VertexBuffer object is created each call.
  21072. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21073. * @param kind defines vertex data kind:
  21074. * * BABYLON.VertexBuffer.PositionKind
  21075. * * BABYLON.VertexBuffer.UVKind
  21076. * * BABYLON.VertexBuffer.UV2Kind
  21077. * * BABYLON.VertexBuffer.UV3Kind
  21078. * * BABYLON.VertexBuffer.UV4Kind
  21079. * * BABYLON.VertexBuffer.UV5Kind
  21080. * * BABYLON.VertexBuffer.UV6Kind
  21081. * * BABYLON.VertexBuffer.ColorKind
  21082. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21083. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21084. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21085. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21086. * @param data defines the data source
  21087. * @param updatable defines if the data must be flagged as updatable (or static)
  21088. * @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
  21089. * @returns the current mesh
  21090. */
  21091. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21092. return this;
  21093. };
  21094. /**
  21095. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21096. * If the mesh has no geometry, it is simply returned as it is.
  21097. * @param kind defines vertex data kind:
  21098. * * BABYLON.VertexBuffer.PositionKind
  21099. * * BABYLON.VertexBuffer.UVKind
  21100. * * BABYLON.VertexBuffer.UV2Kind
  21101. * * BABYLON.VertexBuffer.UV3Kind
  21102. * * BABYLON.VertexBuffer.UV4Kind
  21103. * * BABYLON.VertexBuffer.UV5Kind
  21104. * * BABYLON.VertexBuffer.UV6Kind
  21105. * * BABYLON.VertexBuffer.ColorKind
  21106. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21107. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21108. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21109. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21110. * @param data defines the data source
  21111. * @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
  21112. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21113. * @returns the current mesh
  21114. */
  21115. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21116. return this;
  21117. };
  21118. /**
  21119. * Sets the mesh indices,
  21120. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21121. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21122. * @param totalVertices Defines the total number of vertices
  21123. * @returns the current mesh
  21124. */
  21125. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21126. return this;
  21127. };
  21128. /**
  21129. * Gets a boolean indicating if specific vertex data is present
  21130. * @param kind defines the vertex data kind to use
  21131. * @returns true is data kind is present
  21132. */
  21133. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21134. return false;
  21135. };
  21136. /**
  21137. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21138. * @returns a BoundingInfo
  21139. */
  21140. AbstractMesh.prototype.getBoundingInfo = function () {
  21141. if (this._masterMesh) {
  21142. return this._masterMesh.getBoundingInfo();
  21143. }
  21144. if (!this._boundingInfo) {
  21145. // this._boundingInfo is being created here
  21146. this._updateBoundingInfo();
  21147. }
  21148. // cannot be null.
  21149. return this._boundingInfo;
  21150. };
  21151. /**
  21152. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21153. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21154. * @returns the current mesh
  21155. */
  21156. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21157. if (includeDescendants === void 0) { includeDescendants = true; }
  21158. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21159. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21160. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21161. if (maxDimension === 0) {
  21162. return this;
  21163. }
  21164. var scale = 1 / maxDimension;
  21165. this.scaling.scaleInPlace(scale);
  21166. return this;
  21167. };
  21168. /**
  21169. * Overwrite the current bounding info
  21170. * @param boundingInfo defines the new bounding info
  21171. * @returns the current mesh
  21172. */
  21173. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21174. this._boundingInfo = boundingInfo;
  21175. return this;
  21176. };
  21177. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21178. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21179. get: function () {
  21180. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. /** @hidden */
  21186. AbstractMesh.prototype._preActivate = function () {
  21187. };
  21188. /** @hidden */
  21189. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21190. };
  21191. /** @hidden */
  21192. AbstractMesh.prototype._activate = function (renderId) {
  21193. this._renderId = renderId;
  21194. };
  21195. /**
  21196. * Gets the current world matrix
  21197. * @returns a Matrix
  21198. */
  21199. AbstractMesh.prototype.getWorldMatrix = function () {
  21200. if (this._masterMesh) {
  21201. return this._masterMesh.getWorldMatrix();
  21202. }
  21203. return _super.prototype.getWorldMatrix.call(this);
  21204. };
  21205. /** @hidden */
  21206. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21207. if (this._masterMesh) {
  21208. return this._masterMesh._getWorldMatrixDeterminant();
  21209. }
  21210. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21211. };
  21212. // ================================== Point of View Movement =================================
  21213. /**
  21214. * Perform relative position change from the point of view of behind the front of the mesh.
  21215. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21216. * Supports definition of mesh facing forward or backward
  21217. * @param amountRight defines the distance on the right axis
  21218. * @param amountUp defines the distance on the up axis
  21219. * @param amountForward defines the distance on the forward axis
  21220. * @returns the current mesh
  21221. */
  21222. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21223. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21224. return this;
  21225. };
  21226. /**
  21227. * Calculate relative position change from the point of view of behind the front of the mesh.
  21228. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21229. * Supports definition of mesh facing forward or backward
  21230. * @param amountRight defines the distance on the right axis
  21231. * @param amountUp defines the distance on the up axis
  21232. * @param amountForward defines the distance on the forward axis
  21233. * @returns the new displacement vector
  21234. */
  21235. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21236. var rotMatrix = new BABYLON.Matrix();
  21237. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21238. rotQuaternion.toRotationMatrix(rotMatrix);
  21239. var translationDelta = BABYLON.Vector3.Zero();
  21240. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21241. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21242. return translationDelta;
  21243. };
  21244. // ================================== Point of View Rotation =================================
  21245. /**
  21246. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21247. * Supports definition of mesh facing forward or backward
  21248. * @param flipBack defines the flip
  21249. * @param twirlClockwise defines the twirl
  21250. * @param tiltRight defines the tilt
  21251. * @returns the current mesh
  21252. */
  21253. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21254. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21255. return this;
  21256. };
  21257. /**
  21258. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21259. * Supports definition of mesh facing forward or backward.
  21260. * @param flipBack defines the flip
  21261. * @param twirlClockwise defines the twirl
  21262. * @param tiltRight defines the tilt
  21263. * @returns the new rotation vector
  21264. */
  21265. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21266. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21267. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21268. };
  21269. /**
  21270. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21271. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21272. * @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
  21273. * @returns the new bounding vectors
  21274. */
  21275. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21276. if (includeDescendants === void 0) { includeDescendants = true; }
  21277. if (predicate === void 0) { predicate = null; }
  21278. // Ensures that all world matrix will be recomputed.
  21279. this.getScene().incrementRenderId();
  21280. this.computeWorldMatrix(true);
  21281. var min;
  21282. var max;
  21283. var boundingInfo = this.getBoundingInfo();
  21284. if (!this.subMeshes) {
  21285. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21286. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21287. }
  21288. else {
  21289. min = boundingInfo.boundingBox.minimumWorld;
  21290. max = boundingInfo.boundingBox.maximumWorld;
  21291. }
  21292. if (includeDescendants) {
  21293. var descendants = this.getDescendants(false);
  21294. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21295. var descendant = descendants_1[_i];
  21296. var childMesh = descendant;
  21297. childMesh.computeWorldMatrix(true);
  21298. // Filters meshes based on custom predicate function.
  21299. if (predicate && !predicate(childMesh)) {
  21300. continue;
  21301. }
  21302. //make sure we have the needed params to get mix and max
  21303. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21304. continue;
  21305. }
  21306. var childBoundingInfo = childMesh.getBoundingInfo();
  21307. var boundingBox = childBoundingInfo.boundingBox;
  21308. var minBox = boundingBox.minimumWorld;
  21309. var maxBox = boundingBox.maximumWorld;
  21310. BABYLON.Tools.CheckExtends(minBox, min, max);
  21311. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21312. }
  21313. }
  21314. return {
  21315. min: min,
  21316. max: max
  21317. };
  21318. };
  21319. /** @hidden */
  21320. AbstractMesh.prototype._updateBoundingInfo = function () {
  21321. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21322. this._boundingInfo.update(this.worldMatrixFromCache);
  21323. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21324. return this;
  21325. };
  21326. /** @hidden */
  21327. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21328. if (!this.subMeshes) {
  21329. return this;
  21330. }
  21331. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21332. var subMesh = this.subMeshes[subIndex];
  21333. if (!subMesh.IsGlobal) {
  21334. subMesh.updateBoundingInfo(matrix);
  21335. }
  21336. }
  21337. return this;
  21338. };
  21339. /** @hidden */
  21340. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21341. // Bounding info
  21342. this._updateBoundingInfo();
  21343. };
  21344. /**
  21345. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21346. * A mesh is in the frustum if its bounding box intersects the frustum
  21347. * @param frustumPlanes defines the frustum to test
  21348. * @returns true if the mesh is in the frustum planes
  21349. */
  21350. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21351. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21352. };
  21353. /**
  21354. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21355. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21356. * @param frustumPlanes defines the frustum to test
  21357. * @returns true if the mesh is completely in the frustum planes
  21358. */
  21359. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21360. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21361. };
  21362. /**
  21363. * True if the mesh intersects another mesh or a SolidParticle object
  21364. * @param mesh defines a target mesh or SolidParticle to test
  21365. * @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)
  21366. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21367. * @returns true if there is an intersection
  21368. */
  21369. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21370. if (precise === void 0) { precise = false; }
  21371. if (!this._boundingInfo || !mesh._boundingInfo) {
  21372. return false;
  21373. }
  21374. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21375. return true;
  21376. }
  21377. if (includeDescendants) {
  21378. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21379. var child = _a[_i];
  21380. if (child.intersectsMesh(mesh, precise, true)) {
  21381. return true;
  21382. }
  21383. }
  21384. }
  21385. return false;
  21386. };
  21387. /**
  21388. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21389. * @param point defines the point to test
  21390. * @returns true if there is an intersection
  21391. */
  21392. AbstractMesh.prototype.intersectsPoint = function (point) {
  21393. if (!this._boundingInfo) {
  21394. return false;
  21395. }
  21396. return this._boundingInfo.intersectsPoint(point);
  21397. };
  21398. /**
  21399. * Gets the position of the current mesh in camera space
  21400. * @param camera defines the camera to use
  21401. * @returns a position
  21402. */
  21403. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21404. if (camera === void 0) { camera = null; }
  21405. if (!camera) {
  21406. camera = this.getScene().activeCamera;
  21407. }
  21408. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21409. };
  21410. /**
  21411. * Returns the distance from the mesh to the active camera
  21412. * @param camera defines the camera to use
  21413. * @returns the distance
  21414. */
  21415. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21416. if (camera === void 0) { camera = null; }
  21417. if (!camera) {
  21418. camera = this.getScene().activeCamera;
  21419. }
  21420. return this.absolutePosition.subtract(camera.position).length();
  21421. };
  21422. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21423. // Collisions
  21424. /**
  21425. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21426. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21427. */
  21428. get: function () {
  21429. return this._checkCollisions;
  21430. },
  21431. set: function (collisionEnabled) {
  21432. this._checkCollisions = collisionEnabled;
  21433. if (this.getScene().workerCollisions) {
  21434. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21435. }
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21441. /**
  21442. * Gets Collider object used to compute collisions (not physics)
  21443. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21444. */
  21445. get: function () {
  21446. return this._collider;
  21447. },
  21448. enumerable: true,
  21449. configurable: true
  21450. });
  21451. /**
  21452. * Move the mesh using collision engine
  21453. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21454. * @param displacement defines the requested displacement vector
  21455. * @returns the current mesh
  21456. */
  21457. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21458. var globalPosition = this.getAbsolutePosition();
  21459. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21460. if (!this._collider) {
  21461. this._collider = new BABYLON.Collider();
  21462. }
  21463. this._collider._radius = this.ellipsoid;
  21464. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21465. return this;
  21466. };
  21467. // Collisions
  21468. /** @hidden */
  21469. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21470. this._generatePointsArray();
  21471. if (!this._positions) {
  21472. return this;
  21473. }
  21474. // Transformation
  21475. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21476. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21477. subMesh._lastColliderWorldVertices = [];
  21478. subMesh._trianglePlanes = [];
  21479. var start = subMesh.verticesStart;
  21480. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21481. for (var i = start; i < end; i++) {
  21482. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21483. }
  21484. }
  21485. // Collide
  21486. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21487. if (collider.collisionFound) {
  21488. collider.collidedMesh = this;
  21489. }
  21490. return this;
  21491. };
  21492. /** @hidden */
  21493. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21494. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21495. var len = subMeshes.length;
  21496. for (var index = 0; index < len; index++) {
  21497. var subMesh = subMeshes.data[index];
  21498. // Bounding test
  21499. if (len > 1 && !subMesh._checkCollision(collider))
  21500. continue;
  21501. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21502. }
  21503. return this;
  21504. };
  21505. /** @hidden */
  21506. AbstractMesh.prototype._checkCollision = function (collider) {
  21507. // Bounding box test
  21508. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21509. return this;
  21510. // Transformation matrix
  21511. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21512. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21513. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21514. return this;
  21515. };
  21516. // Picking
  21517. /** @hidden */
  21518. AbstractMesh.prototype._generatePointsArray = function () {
  21519. return false;
  21520. };
  21521. /**
  21522. * Checks if the passed Ray intersects with the mesh
  21523. * @param ray defines the ray to use
  21524. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21525. * @returns the picking info
  21526. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21527. */
  21528. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21529. var pickingInfo = new BABYLON.PickingInfo();
  21530. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21531. return pickingInfo;
  21532. }
  21533. if (!this._generatePointsArray()) {
  21534. return pickingInfo;
  21535. }
  21536. var intersectInfo = null;
  21537. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21538. var len = subMeshes.length;
  21539. for (var index = 0; index < len; index++) {
  21540. var subMesh = subMeshes.data[index];
  21541. // Bounding test
  21542. if (len > 1 && !subMesh.canIntersects(ray))
  21543. continue;
  21544. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21545. if (currentIntersectInfo) {
  21546. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21547. intersectInfo = currentIntersectInfo;
  21548. intersectInfo.subMeshId = index;
  21549. if (fastCheck) {
  21550. break;
  21551. }
  21552. }
  21553. }
  21554. }
  21555. if (intersectInfo) {
  21556. // Get picked point
  21557. var world = this.getWorldMatrix();
  21558. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21559. var direction = ray.direction.clone();
  21560. direction = direction.scale(intersectInfo.distance);
  21561. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21562. var pickedPoint = worldOrigin.add(worldDirection);
  21563. // Return result
  21564. pickingInfo.hit = true;
  21565. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21566. pickingInfo.pickedPoint = pickedPoint;
  21567. pickingInfo.pickedMesh = this;
  21568. pickingInfo.bu = intersectInfo.bu || 0;
  21569. pickingInfo.bv = intersectInfo.bv || 0;
  21570. pickingInfo.faceId = intersectInfo.faceId;
  21571. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21572. return pickingInfo;
  21573. }
  21574. return pickingInfo;
  21575. };
  21576. /**
  21577. * Clones the current mesh
  21578. * @param name defines the mesh name
  21579. * @param newParent defines the new mesh parent
  21580. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21581. * @returns the new mesh
  21582. */
  21583. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21584. return null;
  21585. };
  21586. /**
  21587. * Disposes all the submeshes of the current meshnp
  21588. * @returns the current mesh
  21589. */
  21590. AbstractMesh.prototype.releaseSubMeshes = function () {
  21591. if (this.subMeshes) {
  21592. while (this.subMeshes.length) {
  21593. this.subMeshes[0].dispose();
  21594. }
  21595. }
  21596. else {
  21597. this.subMeshes = new Array();
  21598. }
  21599. return this;
  21600. };
  21601. /**
  21602. * Releases resources associated with this abstract mesh.
  21603. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21604. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21605. */
  21606. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21607. var _this = this;
  21608. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21609. var index;
  21610. // Smart Array Retainers.
  21611. this.getScene().freeActiveMeshes();
  21612. this.getScene().freeRenderingGroups();
  21613. // Action manager
  21614. if (this.actionManager !== undefined && this.actionManager !== null) {
  21615. this.actionManager.dispose();
  21616. this.actionManager = null;
  21617. }
  21618. // Skeleton
  21619. this._skeleton = null;
  21620. // Intersections in progress
  21621. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21622. var other = this._intersectionsInProgress[index];
  21623. var pos = other._intersectionsInProgress.indexOf(this);
  21624. other._intersectionsInProgress.splice(pos, 1);
  21625. }
  21626. this._intersectionsInProgress = [];
  21627. // Lights
  21628. var lights = this.getScene().lights;
  21629. lights.forEach(function (light) {
  21630. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21631. if (meshIndex !== -1) {
  21632. light.includedOnlyMeshes.splice(meshIndex, 1);
  21633. }
  21634. meshIndex = light.excludedMeshes.indexOf(_this);
  21635. if (meshIndex !== -1) {
  21636. light.excludedMeshes.splice(meshIndex, 1);
  21637. }
  21638. // Shadow generators
  21639. var generator = light.getShadowGenerator();
  21640. if (generator) {
  21641. var shadowMap = generator.getShadowMap();
  21642. if (shadowMap && shadowMap.renderList) {
  21643. meshIndex = shadowMap.renderList.indexOf(_this);
  21644. if (meshIndex !== -1) {
  21645. shadowMap.renderList.splice(meshIndex, 1);
  21646. }
  21647. }
  21648. }
  21649. });
  21650. // SubMeshes
  21651. if (this.getClassName() !== "InstancedMesh") {
  21652. this.releaseSubMeshes();
  21653. }
  21654. // Query
  21655. var engine = this.getScene().getEngine();
  21656. if (this._occlusionQuery) {
  21657. this.isOcclusionQueryInProgress = false;
  21658. engine.deleteQuery(this._occlusionQuery);
  21659. this._occlusionQuery = null;
  21660. }
  21661. // Engine
  21662. engine.wipeCaches();
  21663. // Remove from scene
  21664. this.getScene().removeMesh(this);
  21665. if (disposeMaterialAndTextures) {
  21666. if (this.material) {
  21667. this.material.dispose(false, true);
  21668. }
  21669. }
  21670. if (!doNotRecurse) {
  21671. // Particles
  21672. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21673. if (this.getScene().particleSystems[index].emitter === this) {
  21674. this.getScene().particleSystems[index].dispose();
  21675. index--;
  21676. }
  21677. }
  21678. }
  21679. // facet data
  21680. if (this._facetData.facetDataEnabled) {
  21681. this.disableFacetData();
  21682. }
  21683. this.onAfterWorldMatrixUpdateObservable.clear();
  21684. this.onCollideObservable.clear();
  21685. this.onCollisionPositionChangeObservable.clear();
  21686. this.onRebuildObservable.clear();
  21687. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21688. };
  21689. /**
  21690. * Adds the passed mesh as a child to the current mesh
  21691. * @param mesh defines the child mesh
  21692. * @returns the current mesh
  21693. */
  21694. AbstractMesh.prototype.addChild = function (mesh) {
  21695. mesh.setParent(this);
  21696. return this;
  21697. };
  21698. /**
  21699. * Removes the passed mesh from the current mesh children list
  21700. * @param mesh defines the child mesh
  21701. * @returns the current mesh
  21702. */
  21703. AbstractMesh.prototype.removeChild = function (mesh) {
  21704. mesh.setParent(null);
  21705. return this;
  21706. };
  21707. // Facet data
  21708. /** @hidden */
  21709. AbstractMesh.prototype._initFacetData = function () {
  21710. var data = this._facetData;
  21711. if (!data.facetNormals) {
  21712. data.facetNormals = new Array();
  21713. }
  21714. if (!data.facetPositions) {
  21715. data.facetPositions = new Array();
  21716. }
  21717. if (!data.facetPartitioning) {
  21718. data.facetPartitioning = new Array();
  21719. }
  21720. data.facetNb = (this.getIndices().length / 3) | 0;
  21721. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21722. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21723. for (var f = 0; f < data.facetNb; f++) {
  21724. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21725. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21726. }
  21727. data.facetDataEnabled = true;
  21728. return this;
  21729. };
  21730. /**
  21731. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21732. * This method can be called within the render loop.
  21733. * 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
  21734. * @returns the current mesh
  21735. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21736. */
  21737. AbstractMesh.prototype.updateFacetData = function () {
  21738. var data = this._facetData;
  21739. if (!data.facetDataEnabled) {
  21740. this._initFacetData();
  21741. }
  21742. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21743. var indices = this.getIndices();
  21744. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21745. var bInfo = this.getBoundingInfo();
  21746. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21747. // init arrays, matrix and sort function on first call
  21748. data.facetDepthSortEnabled = true;
  21749. if (indices instanceof Uint16Array) {
  21750. data.depthSortedIndices = new Uint16Array(indices);
  21751. }
  21752. else if (indices instanceof Uint32Array) {
  21753. data.depthSortedIndices = new Uint32Array(indices);
  21754. }
  21755. else {
  21756. var needs32bits = false;
  21757. for (var i = 0; i < indices.length; i++) {
  21758. if (indices[i] > 65535) {
  21759. needs32bits = true;
  21760. break;
  21761. }
  21762. }
  21763. if (needs32bits) {
  21764. data.depthSortedIndices = new Uint32Array(indices);
  21765. }
  21766. else {
  21767. data.depthSortedIndices = new Uint16Array(indices);
  21768. }
  21769. }
  21770. data.facetDepthSortFunction = function (f1, f2) {
  21771. return (f2.sqDistance - f1.sqDistance);
  21772. };
  21773. if (!data.facetDepthSortFrom) {
  21774. var camera = this.getScene().activeCamera;
  21775. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21776. }
  21777. data.depthSortedFacets = [];
  21778. for (var f = 0; f < data.facetNb; f++) {
  21779. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21780. data.depthSortedFacets.push(depthSortedFacet);
  21781. }
  21782. data.invertedMatrix = BABYLON.Matrix.Identity();
  21783. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21784. }
  21785. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21786. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21787. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21788. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21789. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21790. data.subDiv.max = data.partitioningSubdivisions;
  21791. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21792. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21793. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21794. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21795. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21796. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21797. // set the parameters for ComputeNormals()
  21798. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21799. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21800. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21801. data.facetParameters.bInfo = bInfo;
  21802. data.facetParameters.bbSize = data.bbSize;
  21803. data.facetParameters.subDiv = data.subDiv;
  21804. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21805. data.facetParameters.depthSort = data.facetDepthSort;
  21806. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21807. this.computeWorldMatrix(true);
  21808. this._worldMatrix.invertToRef(data.invertedMatrix);
  21809. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21810. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21811. }
  21812. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21813. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21814. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21815. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21816. var l = (data.depthSortedIndices.length / 3) | 0;
  21817. for (var f = 0; f < l; f++) {
  21818. var sind = data.depthSortedFacets[f].ind;
  21819. data.depthSortedIndices[f * 3] = indices[sind];
  21820. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21821. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21822. }
  21823. this.updateIndices(data.depthSortedIndices);
  21824. }
  21825. return this;
  21826. };
  21827. /**
  21828. * Returns the facetLocalNormals array.
  21829. * The normals are expressed in the mesh local spac
  21830. * @returns an array of Vector3
  21831. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21832. */
  21833. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21834. if (!this._facetData.facetNormals) {
  21835. this.updateFacetData();
  21836. }
  21837. return this._facetData.facetNormals;
  21838. };
  21839. /**
  21840. * Returns the facetLocalPositions array.
  21841. * The facet positions are expressed in the mesh local space
  21842. * @returns an array of Vector3
  21843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21844. */
  21845. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21846. if (!this._facetData.facetPositions) {
  21847. this.updateFacetData();
  21848. }
  21849. return this._facetData.facetPositions;
  21850. };
  21851. /**
  21852. * Returns the facetLocalPartioning array
  21853. * @returns an array of array of numbers
  21854. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21855. */
  21856. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21857. if (!this._facetData.facetPartitioning) {
  21858. this.updateFacetData();
  21859. }
  21860. return this._facetData.facetPartitioning;
  21861. };
  21862. /**
  21863. * Returns the i-th facet position in the world system.
  21864. * This method allocates a new Vector3 per call
  21865. * @param i defines the facet index
  21866. * @returns a new Vector3
  21867. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21868. */
  21869. AbstractMesh.prototype.getFacetPosition = function (i) {
  21870. var pos = BABYLON.Vector3.Zero();
  21871. this.getFacetPositionToRef(i, pos);
  21872. return pos;
  21873. };
  21874. /**
  21875. * Sets the reference Vector3 with the i-th facet position in the world system
  21876. * @param i defines the facet index
  21877. * @param ref defines the target vector
  21878. * @returns the current mesh
  21879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21880. */
  21881. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21882. var localPos = (this.getFacetLocalPositions())[i];
  21883. var world = this.getWorldMatrix();
  21884. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21885. return this;
  21886. };
  21887. /**
  21888. * Returns the i-th facet normal in the world system.
  21889. * This method allocates a new Vector3 per call
  21890. * @param i defines the facet index
  21891. * @returns a new Vector3
  21892. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21893. */
  21894. AbstractMesh.prototype.getFacetNormal = function (i) {
  21895. var norm = BABYLON.Vector3.Zero();
  21896. this.getFacetNormalToRef(i, norm);
  21897. return norm;
  21898. };
  21899. /**
  21900. * Sets the reference Vector3 with the i-th facet normal in the world system
  21901. * @param i defines the facet index
  21902. * @param ref defines the target vector
  21903. * @returns the current mesh
  21904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21905. */
  21906. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21907. var localNorm = (this.getFacetLocalNormals())[i];
  21908. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21909. return this;
  21910. };
  21911. /**
  21912. * 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)
  21913. * @param x defines x coordinate
  21914. * @param y defines y coordinate
  21915. * @param z defines z coordinate
  21916. * @returns the array of facet indexes
  21917. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21918. */
  21919. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21920. var bInfo = this.getBoundingInfo();
  21921. var data = this._facetData;
  21922. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21923. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21924. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21925. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21926. return null;
  21927. }
  21928. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21929. };
  21930. /**
  21931. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21932. * @param projected sets as the (x,y,z) world projection on the facet
  21933. * @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
  21934. * @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
  21935. * @param x defines x coordinate
  21936. * @param y defines y coordinate
  21937. * @param z defines z coordinate
  21938. * @returns the face index if found (or null instead)
  21939. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21940. */
  21941. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21942. if (checkFace === void 0) { checkFace = false; }
  21943. if (facing === void 0) { facing = true; }
  21944. var world = this.getWorldMatrix();
  21945. var invMat = BABYLON.Tmp.Matrix[5];
  21946. world.invertToRef(invMat);
  21947. var invVect = BABYLON.Tmp.Vector3[8];
  21948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21949. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21950. if (projected) {
  21951. // tranform the local computed projected vector to world coordinates
  21952. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21953. }
  21954. return closest;
  21955. };
  21956. /**
  21957. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21958. * @param projected sets as the (x,y,z) local projection on the facet
  21959. * @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
  21960. * @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
  21961. * @param x defines x coordinate
  21962. * @param y defines y coordinate
  21963. * @param z defines z coordinate
  21964. * @returns the face index if found (or null instead)
  21965. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21966. */
  21967. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21968. if (checkFace === void 0) { checkFace = false; }
  21969. if (facing === void 0) { facing = true; }
  21970. var closest = null;
  21971. var tmpx = 0.0;
  21972. var tmpy = 0.0;
  21973. var tmpz = 0.0;
  21974. var d = 0.0; // tmp dot facet normal * facet position
  21975. var t0 = 0.0;
  21976. var projx = 0.0;
  21977. var projy = 0.0;
  21978. var projz = 0.0;
  21979. // Get all the facets in the same partitioning block than (x, y, z)
  21980. var facetPositions = this.getFacetLocalPositions();
  21981. var facetNormals = this.getFacetLocalNormals();
  21982. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21983. if (!facetsInBlock) {
  21984. return null;
  21985. }
  21986. // Get the closest facet to (x, y, z)
  21987. var shortest = Number.MAX_VALUE; // init distance vars
  21988. var tmpDistance = shortest;
  21989. var fib; // current facet in the block
  21990. var norm; // current facet normal
  21991. var p0; // current facet barycenter position
  21992. // loop on all the facets in the current partitioning block
  21993. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21994. fib = facetsInBlock[idx];
  21995. norm = facetNormals[fib];
  21996. p0 = facetPositions[fib];
  21997. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21998. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21999. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22000. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22001. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22002. projx = x + norm.x * t0;
  22003. projy = y + norm.y * t0;
  22004. projz = z + norm.z * t0;
  22005. tmpx = projx - x;
  22006. tmpy = projy - y;
  22007. tmpz = projz - z;
  22008. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22009. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22010. shortest = tmpDistance;
  22011. closest = fib;
  22012. if (projected) {
  22013. projected.x = projx;
  22014. projected.y = projy;
  22015. projected.z = projz;
  22016. }
  22017. }
  22018. }
  22019. }
  22020. return closest;
  22021. };
  22022. /**
  22023. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22024. * @returns the parameters
  22025. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22026. */
  22027. AbstractMesh.prototype.getFacetDataParameters = function () {
  22028. return this._facetData.facetParameters;
  22029. };
  22030. /**
  22031. * Disables the feature FacetData and frees the related memory
  22032. * @returns the current mesh
  22033. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22034. */
  22035. AbstractMesh.prototype.disableFacetData = function () {
  22036. if (this._facetData.facetDataEnabled) {
  22037. this._facetData.facetDataEnabled = false;
  22038. this._facetData.facetPositions = new Array();
  22039. this._facetData.facetNormals = new Array();
  22040. this._facetData.facetPartitioning = new Array();
  22041. this._facetData.facetParameters = null;
  22042. this._facetData.depthSortedIndices = new Uint32Array(0);
  22043. }
  22044. return this;
  22045. };
  22046. /**
  22047. * Updates the AbstractMesh indices array
  22048. * @param indices defines the data source
  22049. * @returns the current mesh
  22050. */
  22051. AbstractMesh.prototype.updateIndices = function (indices) {
  22052. return this;
  22053. };
  22054. /**
  22055. * Creates new normals data for the mesh
  22056. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22057. * @returns the current mesh
  22058. */
  22059. AbstractMesh.prototype.createNormals = function (updatable) {
  22060. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22061. var indices = this.getIndices();
  22062. var normals;
  22063. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22064. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22065. }
  22066. else {
  22067. normals = [];
  22068. }
  22069. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22070. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22071. return this;
  22072. };
  22073. /**
  22074. * Align the mesh with a normal
  22075. * @param normal defines the normal to use
  22076. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22077. * @returns the current mesh
  22078. */
  22079. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22080. if (!upDirection) {
  22081. upDirection = BABYLON.Axis.Y;
  22082. }
  22083. var axisX = BABYLON.Tmp.Vector3[0];
  22084. var axisZ = BABYLON.Tmp.Vector3[1];
  22085. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22086. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22087. if (this.rotationQuaternion) {
  22088. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22089. }
  22090. else {
  22091. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22092. }
  22093. return this;
  22094. };
  22095. /** @hidden */
  22096. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22097. return false;
  22098. };
  22099. /** No occlusion */
  22100. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22101. /** Occlusion set to optimisitic */
  22102. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22103. /** Occlusion set to strict */
  22104. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22105. /** Use an accurante occlusion algorithm */
  22106. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22107. /** Use a conservative occlusion algorithm */
  22108. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22109. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22110. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22111. /** Culling strategy with bounding sphere only and then frustum culling */
  22112. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22113. return AbstractMesh;
  22114. }(BABYLON.TransformNode));
  22115. BABYLON.AbstractMesh = AbstractMesh;
  22116. })(BABYLON || (BABYLON = {}));
  22117. //# sourceMappingURL=babylon.abstractMesh.js.map
  22118. var BABYLON;
  22119. (function (BABYLON) {
  22120. /**
  22121. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22122. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22123. * 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.
  22124. */
  22125. var Light = /** @class */ (function (_super) {
  22126. __extends(Light, _super);
  22127. /**
  22128. * Creates a Light object in the scene.
  22129. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22130. * @param name The firendly name of the light
  22131. * @param scene The scene the light belongs too
  22132. */
  22133. function Light(name, scene) {
  22134. var _this = _super.call(this, name, scene) || this;
  22135. /**
  22136. * Diffuse gives the basic color to an object.
  22137. */
  22138. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22139. /**
  22140. * Specular produces a highlight color on an object.
  22141. * Note: This is note affecting PBR materials.
  22142. */
  22143. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22144. /**
  22145. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22146. * falling off base on range or angle.
  22147. * This can be set to any values in Light.FALLOFF_x.
  22148. *
  22149. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22150. * other types of materials.
  22151. */
  22152. _this.falloffType = Light.FALLOFF_DEFAULT;
  22153. /**
  22154. * Strength of the light.
  22155. * Note: By default it is define in the framework own unit.
  22156. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22157. */
  22158. _this.intensity = 1.0;
  22159. _this._range = Number.MAX_VALUE;
  22160. _this._inverseSquaredRange = 0;
  22161. /**
  22162. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22163. * of light.
  22164. */
  22165. _this._photometricScale = 1.0;
  22166. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22167. _this._radius = 0.00001;
  22168. /**
  22169. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22170. * exceeding the number allowed of the materials.
  22171. */
  22172. _this.renderPriority = 0;
  22173. _this._shadowEnabled = true;
  22174. _this._excludeWithLayerMask = 0;
  22175. _this._includeOnlyWithLayerMask = 0;
  22176. _this._lightmapMode = 0;
  22177. /**
  22178. * @hidden Internal use only.
  22179. */
  22180. _this._excludedMeshesIds = new Array();
  22181. /**
  22182. * @hidden Internal use only.
  22183. */
  22184. _this._includedOnlyMeshesIds = new Array();
  22185. _this.getScene().addLight(_this);
  22186. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22187. _this._buildUniformLayout();
  22188. _this.includedOnlyMeshes = new Array();
  22189. _this.excludedMeshes = new Array();
  22190. _this._resyncMeshes();
  22191. return _this;
  22192. }
  22193. Object.defineProperty(Light.prototype, "range", {
  22194. /**
  22195. * Defines how far from the source the light is impacting in scene units.
  22196. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22197. */
  22198. get: function () {
  22199. return this._range;
  22200. },
  22201. /**
  22202. * Defines how far from the source the light is impacting in scene units.
  22203. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22204. */
  22205. set: function (value) {
  22206. this._range = value;
  22207. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Light.prototype, "intensityMode", {
  22213. /**
  22214. * Gets the photometric scale used to interpret the intensity.
  22215. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22216. */
  22217. get: function () {
  22218. return this._intensityMode;
  22219. },
  22220. /**
  22221. * Sets the photometric scale used to interpret the intensity.
  22222. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22223. */
  22224. set: function (value) {
  22225. this._intensityMode = value;
  22226. this._computePhotometricScale();
  22227. },
  22228. enumerable: true,
  22229. configurable: true
  22230. });
  22231. ;
  22232. ;
  22233. Object.defineProperty(Light.prototype, "radius", {
  22234. /**
  22235. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22236. */
  22237. get: function () {
  22238. return this._radius;
  22239. },
  22240. /**
  22241. * sets the light radius used by PBR Materials to simulate soft area lights.
  22242. */
  22243. set: function (value) {
  22244. this._radius = value;
  22245. this._computePhotometricScale();
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. ;
  22251. ;
  22252. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22253. /**
  22254. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22255. * the current shadow generator.
  22256. */
  22257. get: function () {
  22258. return this._shadowEnabled;
  22259. },
  22260. /**
  22261. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22262. * the current shadow generator.
  22263. */
  22264. set: function (value) {
  22265. if (this._shadowEnabled === value) {
  22266. return;
  22267. }
  22268. this._shadowEnabled = value;
  22269. this._markMeshesAsLightDirty();
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22275. /**
  22276. * Gets the only meshes impacted by this light.
  22277. */
  22278. get: function () {
  22279. return this._includedOnlyMeshes;
  22280. },
  22281. /**
  22282. * Sets the only meshes impacted by this light.
  22283. */
  22284. set: function (value) {
  22285. this._includedOnlyMeshes = value;
  22286. this._hookArrayForIncludedOnly(value);
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22292. /**
  22293. * Gets the meshes not impacted by this light.
  22294. */
  22295. get: function () {
  22296. return this._excludedMeshes;
  22297. },
  22298. /**
  22299. * Sets the meshes not impacted by this light.
  22300. */
  22301. set: function (value) {
  22302. this._excludedMeshes = value;
  22303. this._hookArrayForExcluded(value);
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22309. /**
  22310. * Gets the layer id use to find what meshes are not impacted by the light.
  22311. * Inactive if 0
  22312. */
  22313. get: function () {
  22314. return this._excludeWithLayerMask;
  22315. },
  22316. /**
  22317. * Sets the layer id use to find what meshes are not impacted by the light.
  22318. * Inactive if 0
  22319. */
  22320. set: function (value) {
  22321. this._excludeWithLayerMask = value;
  22322. this._resyncMeshes();
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22328. /**
  22329. * Gets the layer id use to find what meshes are impacted by the light.
  22330. * Inactive if 0
  22331. */
  22332. get: function () {
  22333. return this._includeOnlyWithLayerMask;
  22334. },
  22335. /**
  22336. * Sets the layer id use to find what meshes are impacted by the light.
  22337. * Inactive if 0
  22338. */
  22339. set: function (value) {
  22340. this._includeOnlyWithLayerMask = value;
  22341. this._resyncMeshes();
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. Object.defineProperty(Light.prototype, "lightmapMode", {
  22347. /**
  22348. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22349. */
  22350. get: function () {
  22351. return this._lightmapMode;
  22352. },
  22353. /**
  22354. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22355. */
  22356. set: function (value) {
  22357. if (this._lightmapMode === value) {
  22358. return;
  22359. }
  22360. this._lightmapMode = value;
  22361. this._markMeshesAsLightDirty();
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. /**
  22367. * Returns the string "Light".
  22368. * @returns the class name
  22369. */
  22370. Light.prototype.getClassName = function () {
  22371. return "Light";
  22372. };
  22373. /**
  22374. * Converts the light information to a readable string for debug purpose.
  22375. * @param fullDetails Supports for multiple levels of logging within scene loading
  22376. * @returns the human readable light info
  22377. */
  22378. Light.prototype.toString = function (fullDetails) {
  22379. var ret = "Name: " + this.name;
  22380. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22381. if (this.animations) {
  22382. for (var i = 0; i < this.animations.length; i++) {
  22383. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22384. }
  22385. }
  22386. if (fullDetails) {
  22387. }
  22388. return ret;
  22389. };
  22390. /** @hidden */
  22391. Light.prototype._syncParentEnabledState = function () {
  22392. _super.prototype._syncParentEnabledState.call(this);
  22393. this._resyncMeshes();
  22394. };
  22395. /**
  22396. * Set the enabled state of this node.
  22397. * @param value - the new enabled state
  22398. */
  22399. Light.prototype.setEnabled = function (value) {
  22400. _super.prototype.setEnabled.call(this, value);
  22401. this._resyncMeshes();
  22402. };
  22403. /**
  22404. * Returns the Light associated shadow generator if any.
  22405. * @return the associated shadow generator.
  22406. */
  22407. Light.prototype.getShadowGenerator = function () {
  22408. return this._shadowGenerator;
  22409. };
  22410. /**
  22411. * Returns a Vector3, the absolute light position in the World.
  22412. * @returns the world space position of the light
  22413. */
  22414. Light.prototype.getAbsolutePosition = function () {
  22415. return BABYLON.Vector3.Zero();
  22416. };
  22417. /**
  22418. * Specifies if the light will affect the passed mesh.
  22419. * @param mesh The mesh to test against the light
  22420. * @return true the mesh is affected otherwise, false.
  22421. */
  22422. Light.prototype.canAffectMesh = function (mesh) {
  22423. if (!mesh) {
  22424. return true;
  22425. }
  22426. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22427. return false;
  22428. }
  22429. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22430. return false;
  22431. }
  22432. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22433. return false;
  22434. }
  22435. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22436. return false;
  22437. }
  22438. return true;
  22439. };
  22440. /**
  22441. * Sort function to order lights for rendering.
  22442. * @param a First Light object to compare to second.
  22443. * @param b Second Light object to compare first.
  22444. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22445. */
  22446. Light.CompareLightsPriority = function (a, b) {
  22447. //shadow-casting lights have priority over non-shadow-casting lights
  22448. //the renderPrioirty is a secondary sort criterion
  22449. if (a.shadowEnabled !== b.shadowEnabled) {
  22450. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22451. }
  22452. return b.renderPriority - a.renderPriority;
  22453. };
  22454. /**
  22455. * Releases resources associated with this node.
  22456. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22457. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22458. */
  22459. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22460. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22461. if (this._shadowGenerator) {
  22462. this._shadowGenerator.dispose();
  22463. this._shadowGenerator = null;
  22464. }
  22465. // Animations
  22466. this.getScene().stopAnimation(this);
  22467. // Remove from meshes
  22468. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22469. var mesh = _a[_i];
  22470. mesh._removeLightSource(this);
  22471. }
  22472. this._uniformBuffer.dispose();
  22473. // Remove from scene
  22474. this.getScene().removeLight(this);
  22475. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22476. };
  22477. /**
  22478. * Returns the light type ID (integer).
  22479. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22480. */
  22481. Light.prototype.getTypeID = function () {
  22482. return 0;
  22483. };
  22484. /**
  22485. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22486. * @returns the scaled intensity in intensity mode unit
  22487. */
  22488. Light.prototype.getScaledIntensity = function () {
  22489. return this._photometricScale * this.intensity;
  22490. };
  22491. /**
  22492. * Returns a new Light object, named "name", from the current one.
  22493. * @param name The name of the cloned light
  22494. * @returns the new created light
  22495. */
  22496. Light.prototype.clone = function (name) {
  22497. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22498. if (!constructor) {
  22499. return null;
  22500. }
  22501. return BABYLON.SerializationHelper.Clone(constructor, this);
  22502. };
  22503. /**
  22504. * Serializes the current light into a Serialization object.
  22505. * @returns the serialized object.
  22506. */
  22507. Light.prototype.serialize = function () {
  22508. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22509. // Type
  22510. serializationObject.type = this.getTypeID();
  22511. // Parent
  22512. if (this.parent) {
  22513. serializationObject.parentId = this.parent.id;
  22514. }
  22515. // Inclusion / exclusions
  22516. if (this.excludedMeshes.length > 0) {
  22517. serializationObject.excludedMeshesIds = [];
  22518. this.excludedMeshes.forEach(function (mesh) {
  22519. serializationObject.excludedMeshesIds.push(mesh.id);
  22520. });
  22521. }
  22522. if (this.includedOnlyMeshes.length > 0) {
  22523. serializationObject.includedOnlyMeshesIds = [];
  22524. this.includedOnlyMeshes.forEach(function (mesh) {
  22525. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22526. });
  22527. }
  22528. // Animations
  22529. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22530. serializationObject.ranges = this.serializeAnimationRanges();
  22531. return serializationObject;
  22532. };
  22533. /**
  22534. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22535. * This new light is named "name" and added to the passed scene.
  22536. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22537. * @param name The friendly name of the light
  22538. * @param scene The scene the new light will belong to
  22539. * @returns the constructor function
  22540. */
  22541. Light.GetConstructorFromName = function (type, name, scene) {
  22542. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22543. if (constructorFunc) {
  22544. return constructorFunc;
  22545. }
  22546. // Default to no light for none present once.
  22547. return null;
  22548. };
  22549. /**
  22550. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22551. * @param parsedLight The JSON representation of the light
  22552. * @param scene The scene to create the parsed light in
  22553. * @returns the created light after parsing
  22554. */
  22555. Light.Parse = function (parsedLight, scene) {
  22556. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22557. if (!constructor) {
  22558. return null;
  22559. }
  22560. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22561. // Inclusion / exclusions
  22562. if (parsedLight.excludedMeshesIds) {
  22563. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22564. }
  22565. if (parsedLight.includedOnlyMeshesIds) {
  22566. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22567. }
  22568. // Parent
  22569. if (parsedLight.parentId) {
  22570. light._waitingParentId = parsedLight.parentId;
  22571. }
  22572. // Animations
  22573. if (parsedLight.animations) {
  22574. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22575. var parsedAnimation = parsedLight.animations[animationIndex];
  22576. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22577. }
  22578. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22579. }
  22580. if (parsedLight.autoAnimate) {
  22581. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22582. }
  22583. return light;
  22584. };
  22585. Light.prototype._hookArrayForExcluded = function (array) {
  22586. var _this = this;
  22587. var oldPush = array.push;
  22588. array.push = function () {
  22589. var items = [];
  22590. for (var _i = 0; _i < arguments.length; _i++) {
  22591. items[_i] = arguments[_i];
  22592. }
  22593. var result = oldPush.apply(array, items);
  22594. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22595. var item = items_1[_a];
  22596. item._resyncLighSource(_this);
  22597. }
  22598. return result;
  22599. };
  22600. var oldSplice = array.splice;
  22601. array.splice = function (index, deleteCount) {
  22602. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22603. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22604. var item = deleted_1[_i];
  22605. item._resyncLighSource(_this);
  22606. }
  22607. return deleted;
  22608. };
  22609. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22610. var item = array_1[_i];
  22611. item._resyncLighSource(this);
  22612. }
  22613. };
  22614. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22615. var _this = this;
  22616. var oldPush = array.push;
  22617. array.push = function () {
  22618. var items = [];
  22619. for (var _i = 0; _i < arguments.length; _i++) {
  22620. items[_i] = arguments[_i];
  22621. }
  22622. var result = oldPush.apply(array, items);
  22623. _this._resyncMeshes();
  22624. return result;
  22625. };
  22626. var oldSplice = array.splice;
  22627. array.splice = function (index, deleteCount) {
  22628. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22629. _this._resyncMeshes();
  22630. return deleted;
  22631. };
  22632. this._resyncMeshes();
  22633. };
  22634. Light.prototype._resyncMeshes = function () {
  22635. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22636. var mesh = _a[_i];
  22637. mesh._resyncLighSource(this);
  22638. }
  22639. };
  22640. /**
  22641. * Forces the meshes to update their light related information in their rendering used effects
  22642. * @hidden Internal Use Only
  22643. */
  22644. Light.prototype._markMeshesAsLightDirty = function () {
  22645. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22646. var mesh = _a[_i];
  22647. if (mesh._lightSources.indexOf(this) !== -1) {
  22648. mesh._markSubMeshesAsLightDirty();
  22649. }
  22650. }
  22651. };
  22652. /**
  22653. * Recomputes the cached photometric scale if needed.
  22654. */
  22655. Light.prototype._computePhotometricScale = function () {
  22656. this._photometricScale = this._getPhotometricScale();
  22657. this.getScene().resetCachedMaterial();
  22658. };
  22659. /**
  22660. * Returns the Photometric Scale according to the light type and intensity mode.
  22661. */
  22662. Light.prototype._getPhotometricScale = function () {
  22663. var photometricScale = 0.0;
  22664. var lightTypeID = this.getTypeID();
  22665. //get photometric mode
  22666. var photometricMode = this.intensityMode;
  22667. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22668. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22669. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22670. }
  22671. else {
  22672. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22673. }
  22674. }
  22675. //compute photometric scale
  22676. switch (lightTypeID) {
  22677. case Light.LIGHTTYPEID_POINTLIGHT:
  22678. case Light.LIGHTTYPEID_SPOTLIGHT:
  22679. switch (photometricMode) {
  22680. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22681. photometricScale = 1.0 / (4.0 * Math.PI);
  22682. break;
  22683. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22684. photometricScale = 1.0;
  22685. break;
  22686. case Light.INTENSITYMODE_LUMINANCE:
  22687. photometricScale = this.radius * this.radius;
  22688. break;
  22689. }
  22690. break;
  22691. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22692. switch (photometricMode) {
  22693. case Light.INTENSITYMODE_ILLUMINANCE:
  22694. photometricScale = 1.0;
  22695. break;
  22696. case Light.INTENSITYMODE_LUMINANCE:
  22697. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22698. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22699. var apexAngleRadians = this.radius;
  22700. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22701. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22702. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22703. photometricScale = solidAngle;
  22704. break;
  22705. }
  22706. break;
  22707. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22708. // No fall off in hemisperic light.
  22709. photometricScale = 1.0;
  22710. break;
  22711. }
  22712. return photometricScale;
  22713. };
  22714. /**
  22715. * Reorder the light in the scene according to their defined priority.
  22716. * @hidden Internal Use Only
  22717. */
  22718. Light.prototype._reorderLightsInScene = function () {
  22719. var scene = this.getScene();
  22720. if (this._renderPriority != 0) {
  22721. scene.requireLightSorting = true;
  22722. }
  22723. this.getScene().sortLightsByPriority();
  22724. };
  22725. /**
  22726. * Falloff Default: light is falling off following the material specification:
  22727. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22728. */
  22729. Light.FALLOFF_DEFAULT = 0;
  22730. /**
  22731. * Falloff Physical: light is falling off following the inverse squared distance law.
  22732. */
  22733. Light.FALLOFF_PHYSICAL = 1;
  22734. /**
  22735. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22736. * to enhance interoperability with other engines.
  22737. */
  22738. Light.FALLOFF_GLTF = 2;
  22739. /**
  22740. * Falloff Standard: light is falling off like in the standard material
  22741. * to enhance interoperability with other materials.
  22742. */
  22743. Light.FALLOFF_STANDARD = 3;
  22744. //lightmapMode Consts
  22745. /**
  22746. * If every light affecting the material is in this lightmapMode,
  22747. * material.lightmapTexture adds or multiplies
  22748. * (depends on material.useLightmapAsShadowmap)
  22749. * after every other light calculations.
  22750. */
  22751. Light.LIGHTMAP_DEFAULT = 0;
  22752. /**
  22753. * material.lightmapTexture as only diffuse lighting from this light
  22754. * adds only specular lighting from this light
  22755. * adds dynamic shadows
  22756. */
  22757. Light.LIGHTMAP_SPECULAR = 1;
  22758. /**
  22759. * material.lightmapTexture as only lighting
  22760. * no light calculation from this light
  22761. * only adds dynamic shadows from this light
  22762. */
  22763. Light.LIGHTMAP_SHADOWSONLY = 2;
  22764. // Intensity Mode Consts
  22765. /**
  22766. * Each light type uses the default quantity according to its type:
  22767. * point/spot lights use luminous intensity
  22768. * directional lights use illuminance
  22769. */
  22770. Light.INTENSITYMODE_AUTOMATIC = 0;
  22771. /**
  22772. * lumen (lm)
  22773. */
  22774. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22775. /**
  22776. * candela (lm/sr)
  22777. */
  22778. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22779. /**
  22780. * lux (lm/m^2)
  22781. */
  22782. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22783. /**
  22784. * nit (cd/m^2)
  22785. */
  22786. Light.INTENSITYMODE_LUMINANCE = 4;
  22787. // Light types ids const.
  22788. /**
  22789. * Light type const id of the point light.
  22790. */
  22791. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22792. /**
  22793. * Light type const id of the directional light.
  22794. */
  22795. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22796. /**
  22797. * Light type const id of the spot light.
  22798. */
  22799. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22800. /**
  22801. * Light type const id of the hemispheric light.
  22802. */
  22803. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22804. __decorate([
  22805. BABYLON.serializeAsColor3()
  22806. ], Light.prototype, "diffuse", void 0);
  22807. __decorate([
  22808. BABYLON.serializeAsColor3()
  22809. ], Light.prototype, "specular", void 0);
  22810. __decorate([
  22811. BABYLON.serialize()
  22812. ], Light.prototype, "falloffType", void 0);
  22813. __decorate([
  22814. BABYLON.serialize()
  22815. ], Light.prototype, "intensity", void 0);
  22816. __decorate([
  22817. BABYLON.serialize()
  22818. ], Light.prototype, "range", null);
  22819. __decorate([
  22820. BABYLON.serialize()
  22821. ], Light.prototype, "intensityMode", null);
  22822. __decorate([
  22823. BABYLON.serialize()
  22824. ], Light.prototype, "radius", null);
  22825. __decorate([
  22826. BABYLON.serialize()
  22827. ], Light.prototype, "_renderPriority", void 0);
  22828. __decorate([
  22829. BABYLON.expandToProperty("_reorderLightsInScene")
  22830. ], Light.prototype, "renderPriority", void 0);
  22831. __decorate([
  22832. BABYLON.serialize("shadowEnabled")
  22833. ], Light.prototype, "_shadowEnabled", void 0);
  22834. __decorate([
  22835. BABYLON.serialize("excludeWithLayerMask")
  22836. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22837. __decorate([
  22838. BABYLON.serialize("includeOnlyWithLayerMask")
  22839. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22840. __decorate([
  22841. BABYLON.serialize("lightmapMode")
  22842. ], Light.prototype, "_lightmapMode", void 0);
  22843. return Light;
  22844. }(BABYLON.Node));
  22845. BABYLON.Light = Light;
  22846. })(BABYLON || (BABYLON = {}));
  22847. //# sourceMappingURL=babylon.light.js.map
  22848. var BABYLON;
  22849. (function (BABYLON) {
  22850. /**
  22851. * This is the base class of all the camera used in the application.
  22852. * @see http://doc.babylonjs.com/features/cameras
  22853. */
  22854. var Camera = /** @class */ (function (_super) {
  22855. __extends(Camera, _super);
  22856. /**
  22857. * Instantiates a new camera object.
  22858. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22859. * @see http://doc.babylonjs.com/features/cameras
  22860. * @param name Defines the name of the camera in the scene
  22861. * @param position Defines the position of the camera
  22862. * @param scene Defines the scene the camera belongs too
  22863. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22864. */
  22865. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22866. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22867. var _this = _super.call(this, name, scene) || this;
  22868. /**
  22869. * The vector the camera should consider as up.
  22870. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22871. */
  22872. _this.upVector = BABYLON.Vector3.Up();
  22873. /**
  22874. * Define the current limit on the left side for an orthographic camera
  22875. * In scene unit
  22876. */
  22877. _this.orthoLeft = null;
  22878. /**
  22879. * Define the current limit on the right side for an orthographic camera
  22880. * In scene unit
  22881. */
  22882. _this.orthoRight = null;
  22883. /**
  22884. * Define the current limit on the bottom side for an orthographic camera
  22885. * In scene unit
  22886. */
  22887. _this.orthoBottom = null;
  22888. /**
  22889. * Define the current limit on the top side for an orthographic camera
  22890. * In scene unit
  22891. */
  22892. _this.orthoTop = null;
  22893. /**
  22894. * Field Of View is set in Radians. (default is 0.8)
  22895. */
  22896. _this.fov = 0.8;
  22897. /**
  22898. * Define the minimum distance the camera can see from.
  22899. * This is important to note that the depth buffer are not infinite and the closer it starts
  22900. * the more your scene might encounter depth fighting issue.
  22901. */
  22902. _this.minZ = 1;
  22903. /**
  22904. * Define the maximum distance the camera can see to.
  22905. * This is important to note that the depth buffer are not infinite and the further it end
  22906. * the more your scene might encounter depth fighting issue.
  22907. */
  22908. _this.maxZ = 10000.0;
  22909. /**
  22910. * Define the default inertia of the camera.
  22911. * This helps giving a smooth feeling to the camera movement.
  22912. */
  22913. _this.inertia = 0.9;
  22914. /**
  22915. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22916. */
  22917. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22918. /**
  22919. * Define wether the camera is intermediate.
  22920. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22921. */
  22922. _this.isIntermediate = false;
  22923. /**
  22924. * Define the viewport of the camera.
  22925. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22926. */
  22927. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22928. /**
  22929. * Restricts the camera to viewing objects with the same layerMask.
  22930. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22931. */
  22932. _this.layerMask = 0x0FFFFFFF;
  22933. /**
  22934. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22935. */
  22936. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22937. /**
  22938. * Rig mode of the camera.
  22939. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22940. * This is normally controlled byt the camera themselves as internal use.
  22941. */
  22942. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22943. /**
  22944. * Defines the list of custom render target the camera should render to.
  22945. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22946. * else in the scene.
  22947. */
  22948. _this.customRenderTargets = new Array();
  22949. /**
  22950. * Observable triggered when the camera view matrix has changed.
  22951. */
  22952. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22953. /**
  22954. * Observable triggered when the camera Projection matrix has changed.
  22955. */
  22956. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22957. /**
  22958. * Observable triggered when the inputs have been processed.
  22959. */
  22960. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22961. /**
  22962. * Observable triggered when reset has been called and applied to the camera.
  22963. */
  22964. _this.onRestoreStateObservable = new BABYLON.Observable();
  22965. /** @hidden */
  22966. _this._rigCameras = new Array();
  22967. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22968. /** @hidden */
  22969. _this._skipRendering = false;
  22970. /** @hidden */
  22971. _this._projectionMatrix = new BABYLON.Matrix();
  22972. /** @hidden */
  22973. _this._postProcesses = new Array();
  22974. /** @hidden */
  22975. _this._activeMeshes = new BABYLON.SmartArray(256);
  22976. _this._globalPosition = BABYLON.Vector3.Zero();
  22977. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22978. _this._doNotComputeProjectionMatrix = false;
  22979. _this._transformMatrix = BABYLON.Matrix.Zero();
  22980. _this._refreshFrustumPlanes = true;
  22981. _this.getScene().addCamera(_this);
  22982. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22983. _this.getScene().activeCamera = _this;
  22984. }
  22985. _this.position = position;
  22986. return _this;
  22987. }
  22988. /**
  22989. * Store current camera state (fov, position, etc..)
  22990. * @returns the camera
  22991. */
  22992. Camera.prototype.storeState = function () {
  22993. this._stateStored = true;
  22994. this._storedFov = this.fov;
  22995. return this;
  22996. };
  22997. /**
  22998. * Restores the camera state values if it has been stored. You must call storeState() first
  22999. */
  23000. Camera.prototype._restoreStateValues = function () {
  23001. if (!this._stateStored) {
  23002. return false;
  23003. }
  23004. this.fov = this._storedFov;
  23005. return true;
  23006. };
  23007. /**
  23008. * Restored camera state. You must call storeState() first.
  23009. * @returns true if restored and false otherwise
  23010. */
  23011. Camera.prototype.restoreState = function () {
  23012. if (this._restoreStateValues()) {
  23013. this.onRestoreStateObservable.notifyObservers(this);
  23014. return true;
  23015. }
  23016. return false;
  23017. };
  23018. /**
  23019. * Gets the class name of the camera.
  23020. * @returns the class name
  23021. */
  23022. Camera.prototype.getClassName = function () {
  23023. return "Camera";
  23024. };
  23025. /**
  23026. * Gets a string representation of the camera usefull for debug purpose.
  23027. * @param fullDetails Defines that a more verboe level of logging is required
  23028. * @returns the string representation
  23029. */
  23030. Camera.prototype.toString = function (fullDetails) {
  23031. var ret = "Name: " + this.name;
  23032. ret += ", type: " + this.getClassName();
  23033. if (this.animations) {
  23034. for (var i = 0; i < this.animations.length; i++) {
  23035. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23036. }
  23037. }
  23038. if (fullDetails) {
  23039. }
  23040. return ret;
  23041. };
  23042. Object.defineProperty(Camera.prototype, "globalPosition", {
  23043. /**
  23044. * Gets the current world space position of the camera.
  23045. */
  23046. get: function () {
  23047. return this._globalPosition;
  23048. },
  23049. enumerable: true,
  23050. configurable: true
  23051. });
  23052. /**
  23053. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23054. * @returns the active meshe list
  23055. */
  23056. Camera.prototype.getActiveMeshes = function () {
  23057. return this._activeMeshes;
  23058. };
  23059. /**
  23060. * Check wether a mesh is part of the current active mesh list of the camera
  23061. * @param mesh Defines the mesh to check
  23062. * @returns true if active, false otherwise
  23063. */
  23064. Camera.prototype.isActiveMesh = function (mesh) {
  23065. return (this._activeMeshes.indexOf(mesh) !== -1);
  23066. };
  23067. /**
  23068. * Is this camera ready to be used/rendered
  23069. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23070. * @return true if the camera is ready
  23071. */
  23072. Camera.prototype.isReady = function (completeCheck) {
  23073. if (completeCheck === void 0) { completeCheck = false; }
  23074. if (completeCheck) {
  23075. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23076. var pp = _a[_i];
  23077. if (pp && !pp.isReady()) {
  23078. return false;
  23079. }
  23080. }
  23081. }
  23082. return _super.prototype.isReady.call(this, completeCheck);
  23083. };
  23084. /** @hidden */
  23085. Camera.prototype._initCache = function () {
  23086. _super.prototype._initCache.call(this);
  23087. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23088. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23089. this._cache.mode = undefined;
  23090. this._cache.minZ = undefined;
  23091. this._cache.maxZ = undefined;
  23092. this._cache.fov = undefined;
  23093. this._cache.fovMode = undefined;
  23094. this._cache.aspectRatio = undefined;
  23095. this._cache.orthoLeft = undefined;
  23096. this._cache.orthoRight = undefined;
  23097. this._cache.orthoBottom = undefined;
  23098. this._cache.orthoTop = undefined;
  23099. this._cache.renderWidth = undefined;
  23100. this._cache.renderHeight = undefined;
  23101. };
  23102. /** @hidden */
  23103. Camera.prototype._updateCache = function (ignoreParentClass) {
  23104. if (!ignoreParentClass) {
  23105. _super.prototype._updateCache.call(this);
  23106. }
  23107. this._cache.position.copyFrom(this.position);
  23108. this._cache.upVector.copyFrom(this.upVector);
  23109. };
  23110. /** @hidden */
  23111. Camera.prototype._isSynchronized = function () {
  23112. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23113. };
  23114. /** @hidden */
  23115. Camera.prototype._isSynchronizedViewMatrix = function () {
  23116. if (!_super.prototype._isSynchronized.call(this))
  23117. return false;
  23118. return this._cache.position.equals(this.position)
  23119. && this._cache.upVector.equals(this.upVector)
  23120. && this.isSynchronizedWithParent();
  23121. };
  23122. /** @hidden */
  23123. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23124. var check = this._cache.mode === this.mode
  23125. && this._cache.minZ === this.minZ
  23126. && this._cache.maxZ === this.maxZ;
  23127. if (!check) {
  23128. return false;
  23129. }
  23130. var engine = this.getEngine();
  23131. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23132. check = this._cache.fov === this.fov
  23133. && this._cache.fovMode === this.fovMode
  23134. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23135. }
  23136. else {
  23137. check = this._cache.orthoLeft === this.orthoLeft
  23138. && this._cache.orthoRight === this.orthoRight
  23139. && this._cache.orthoBottom === this.orthoBottom
  23140. && this._cache.orthoTop === this.orthoTop
  23141. && this._cache.renderWidth === engine.getRenderWidth()
  23142. && this._cache.renderHeight === engine.getRenderHeight();
  23143. }
  23144. return check;
  23145. };
  23146. /**
  23147. * Attach the input controls to a specific dom element to get the input from.
  23148. * @param element Defines the element the controls should be listened from
  23149. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23150. */
  23151. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23152. };
  23153. /**
  23154. * Detach the current controls from the specified dom element.
  23155. * @param element Defines the element to stop listening the inputs from
  23156. */
  23157. Camera.prototype.detachControl = function (element) {
  23158. };
  23159. /**
  23160. * Update the camera state according to the different inputs gathered during the frame.
  23161. */
  23162. Camera.prototype.update = function () {
  23163. this._checkInputs();
  23164. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23165. this._updateRigCameras();
  23166. }
  23167. };
  23168. /** @hidden */
  23169. Camera.prototype._checkInputs = function () {
  23170. this.onAfterCheckInputsObservable.notifyObservers(this);
  23171. };
  23172. Object.defineProperty(Camera.prototype, "rigCameras", {
  23173. /** @hidden */
  23174. get: function () {
  23175. return this._rigCameras;
  23176. },
  23177. enumerable: true,
  23178. configurable: true
  23179. });
  23180. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23181. /**
  23182. * Gets the post process used by the rig cameras
  23183. */
  23184. get: function () {
  23185. return this._rigPostProcess;
  23186. },
  23187. enumerable: true,
  23188. configurable: true
  23189. });
  23190. /**
  23191. * Internal, gets the first post proces.
  23192. * @returns the first post process to be run on this camera.
  23193. */
  23194. Camera.prototype._getFirstPostProcess = function () {
  23195. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23196. if (this._postProcesses[ppIndex] !== null) {
  23197. return this._postProcesses[ppIndex];
  23198. }
  23199. }
  23200. return null;
  23201. };
  23202. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23203. // invalidate framebuffer
  23204. var firstPostProcess = this._getFirstPostProcess();
  23205. if (firstPostProcess) {
  23206. firstPostProcess.markTextureDirty();
  23207. }
  23208. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23209. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23210. var cam = this._rigCameras[i];
  23211. var rigPostProcess = cam._rigPostProcess;
  23212. // for VR rig, there does not have to be a post process
  23213. if (rigPostProcess) {
  23214. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23215. if (isPass) {
  23216. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23217. cam.isIntermediate = this._postProcesses.length === 0;
  23218. }
  23219. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23220. rigPostProcess.markTextureDirty();
  23221. }
  23222. else {
  23223. cam._postProcesses = this._postProcesses.slice(0);
  23224. }
  23225. }
  23226. };
  23227. /**
  23228. * Attach a post process to the camera.
  23229. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23230. * @param postProcess The post process to attach to the camera
  23231. * @param insertAt The position of the post process in case several of them are in use in the scene
  23232. * @returns the position the post process has been inserted at
  23233. */
  23234. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23235. if (insertAt === void 0) { insertAt = null; }
  23236. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23237. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23238. return 0;
  23239. }
  23240. if (insertAt == null || insertAt < 0) {
  23241. this._postProcesses.push(postProcess);
  23242. }
  23243. else if (this._postProcesses[insertAt] === null) {
  23244. this._postProcesses[insertAt] = postProcess;
  23245. }
  23246. else {
  23247. this._postProcesses.splice(insertAt, 0, postProcess);
  23248. }
  23249. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23250. return this._postProcesses.indexOf(postProcess);
  23251. };
  23252. /**
  23253. * Detach a post process to the camera.
  23254. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23255. * @param postProcess The post process to detach from the camera
  23256. */
  23257. Camera.prototype.detachPostProcess = function (postProcess) {
  23258. var idx = this._postProcesses.indexOf(postProcess);
  23259. if (idx !== -1) {
  23260. this._postProcesses[idx] = null;
  23261. }
  23262. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23263. };
  23264. /**
  23265. * Gets the current world matrix of the camera
  23266. */
  23267. Camera.prototype.getWorldMatrix = function () {
  23268. if (this._isSynchronizedViewMatrix()) {
  23269. return this._worldMatrix;
  23270. }
  23271. // Getting the the view matrix will also compute the world matrix.
  23272. this.getViewMatrix();
  23273. return this._worldMatrix;
  23274. };
  23275. /** @hidden */
  23276. Camera.prototype._getViewMatrix = function () {
  23277. return BABYLON.Matrix.Identity();
  23278. };
  23279. /**
  23280. * Gets the current view matrix of the camera.
  23281. * @param force forces the camera to recompute the matrix without looking at the cached state
  23282. * @returns the view matrix
  23283. */
  23284. Camera.prototype.getViewMatrix = function (force) {
  23285. if (!force && this._isSynchronizedViewMatrix()) {
  23286. return this._computedViewMatrix;
  23287. }
  23288. this.updateCache();
  23289. this._computedViewMatrix = this._getViewMatrix();
  23290. this._currentRenderId = this.getScene().getRenderId();
  23291. this._childRenderId = this._currentRenderId;
  23292. this._refreshFrustumPlanes = true;
  23293. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23294. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23295. }
  23296. this.onViewMatrixChangedObservable.notifyObservers(this);
  23297. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23298. return this._computedViewMatrix;
  23299. };
  23300. /**
  23301. * Freeze the projection matrix.
  23302. * It will prevent the cache check of the camera projection compute and can speed up perf
  23303. * if no parameter of the camera are meant to change
  23304. * @param projection Defines manually a projection if necessary
  23305. */
  23306. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23307. this._doNotComputeProjectionMatrix = true;
  23308. if (projection !== undefined) {
  23309. this._projectionMatrix = projection;
  23310. }
  23311. };
  23312. ;
  23313. /**
  23314. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23315. */
  23316. Camera.prototype.unfreezeProjectionMatrix = function () {
  23317. this._doNotComputeProjectionMatrix = false;
  23318. };
  23319. ;
  23320. /**
  23321. * Gets the current projection matrix of the camera.
  23322. * @param force forces the camera to recompute the matrix without looking at the cached state
  23323. * @returns the projection matrix
  23324. */
  23325. Camera.prototype.getProjectionMatrix = function (force) {
  23326. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23327. return this._projectionMatrix;
  23328. }
  23329. // Cache
  23330. this._cache.mode = this.mode;
  23331. this._cache.minZ = this.minZ;
  23332. this._cache.maxZ = this.maxZ;
  23333. // Matrix
  23334. this._refreshFrustumPlanes = true;
  23335. var engine = this.getEngine();
  23336. var scene = this.getScene();
  23337. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23338. this._cache.fov = this.fov;
  23339. this._cache.fovMode = this.fovMode;
  23340. this._cache.aspectRatio = engine.getAspectRatio(this);
  23341. if (this.minZ <= 0) {
  23342. this.minZ = 0.1;
  23343. }
  23344. if (scene.useRightHandedSystem) {
  23345. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23346. }
  23347. else {
  23348. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23349. }
  23350. }
  23351. else {
  23352. var halfWidth = engine.getRenderWidth() / 2.0;
  23353. var halfHeight = engine.getRenderHeight() / 2.0;
  23354. if (scene.useRightHandedSystem) {
  23355. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23356. }
  23357. else {
  23358. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23359. }
  23360. this._cache.orthoLeft = this.orthoLeft;
  23361. this._cache.orthoRight = this.orthoRight;
  23362. this._cache.orthoBottom = this.orthoBottom;
  23363. this._cache.orthoTop = this.orthoTop;
  23364. this._cache.renderWidth = engine.getRenderWidth();
  23365. this._cache.renderHeight = engine.getRenderHeight();
  23366. }
  23367. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23368. return this._projectionMatrix;
  23369. };
  23370. /**
  23371. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23372. * @returns a Matrix
  23373. */
  23374. Camera.prototype.getTransformationMatrix = function () {
  23375. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23376. return this._transformMatrix;
  23377. };
  23378. Camera.prototype._updateFrustumPlanes = function () {
  23379. if (!this._refreshFrustumPlanes) {
  23380. return;
  23381. }
  23382. this.getTransformationMatrix();
  23383. if (!this._frustumPlanes) {
  23384. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23385. }
  23386. else {
  23387. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23388. }
  23389. this._refreshFrustumPlanes = false;
  23390. };
  23391. /**
  23392. * Checks if a cullable object (mesh...) is in the camera frustum
  23393. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23394. * @param target The object to check
  23395. * @returns true if the object is in frustum otherwise false
  23396. */
  23397. Camera.prototype.isInFrustum = function (target) {
  23398. this._updateFrustumPlanes();
  23399. return target.isInFrustum(this._frustumPlanes);
  23400. };
  23401. /**
  23402. * Checks if a cullable object (mesh...) is in the camera frustum
  23403. * Unlike isInFrustum this cheks the full bounding box
  23404. * @param target The object to check
  23405. * @returns true if the object is in frustum otherwise false
  23406. */
  23407. Camera.prototype.isCompletelyInFrustum = function (target) {
  23408. this._updateFrustumPlanes();
  23409. return target.isCompletelyInFrustum(this._frustumPlanes);
  23410. };
  23411. /**
  23412. * Gets a ray in the forward direction from the camera.
  23413. * @param length Defines the length of the ray to create
  23414. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23415. * @param origin Defines the start point of the ray which defaults to the camera position
  23416. * @returns the forward ray
  23417. */
  23418. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23419. if (length === void 0) { length = 100; }
  23420. if (!transform) {
  23421. transform = this.getWorldMatrix();
  23422. }
  23423. if (!origin) {
  23424. origin = this.position;
  23425. }
  23426. var forward = new BABYLON.Vector3(0, 0, 1);
  23427. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23428. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23429. return new BABYLON.Ray(origin, direction, length);
  23430. };
  23431. /**
  23432. * Releases resources associated with this node.
  23433. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23434. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23435. */
  23436. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23437. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23438. // Observables
  23439. this.onViewMatrixChangedObservable.clear();
  23440. this.onProjectionMatrixChangedObservable.clear();
  23441. this.onAfterCheckInputsObservable.clear();
  23442. this.onRestoreStateObservable.clear();
  23443. // Inputs
  23444. if (this.inputs) {
  23445. this.inputs.clear();
  23446. }
  23447. // Animations
  23448. this.getScene().stopAnimation(this);
  23449. // Remove from scene
  23450. this.getScene().removeCamera(this);
  23451. while (this._rigCameras.length > 0) {
  23452. var camera = this._rigCameras.pop();
  23453. if (camera) {
  23454. camera.dispose();
  23455. }
  23456. }
  23457. // Postprocesses
  23458. if (this._rigPostProcess) {
  23459. this._rigPostProcess.dispose(this);
  23460. this._rigPostProcess = null;
  23461. this._postProcesses = [];
  23462. }
  23463. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23464. this._rigPostProcess = null;
  23465. this._postProcesses = [];
  23466. }
  23467. else {
  23468. var i = this._postProcesses.length;
  23469. while (--i >= 0) {
  23470. var postProcess = this._postProcesses[i];
  23471. if (postProcess) {
  23472. postProcess.dispose(this);
  23473. }
  23474. }
  23475. }
  23476. // Render targets
  23477. var i = this.customRenderTargets.length;
  23478. while (--i >= 0) {
  23479. this.customRenderTargets[i].dispose();
  23480. }
  23481. this.customRenderTargets = [];
  23482. // Active Meshes
  23483. this._activeMeshes.dispose();
  23484. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23485. };
  23486. Object.defineProperty(Camera.prototype, "leftCamera", {
  23487. /**
  23488. * Gets the left camera of a rig setup in case of Rigged Camera
  23489. */
  23490. get: function () {
  23491. if (this._rigCameras.length < 1) {
  23492. return null;
  23493. }
  23494. return this._rigCameras[0];
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. Object.defineProperty(Camera.prototype, "rightCamera", {
  23500. /**
  23501. * Gets the right camera of a rig setup in case of Rigged Camera
  23502. */
  23503. get: function () {
  23504. if (this._rigCameras.length < 2) {
  23505. return null;
  23506. }
  23507. return this._rigCameras[1];
  23508. },
  23509. enumerable: true,
  23510. configurable: true
  23511. });
  23512. /**
  23513. * Gets the left camera target of a rig setup in case of Rigged Camera
  23514. * @returns the target position
  23515. */
  23516. Camera.prototype.getLeftTarget = function () {
  23517. if (this._rigCameras.length < 1) {
  23518. return null;
  23519. }
  23520. return this._rigCameras[0].getTarget();
  23521. };
  23522. /**
  23523. * Gets the right camera target of a rig setup in case of Rigged Camera
  23524. * @returns the target position
  23525. */
  23526. Camera.prototype.getRightTarget = function () {
  23527. if (this._rigCameras.length < 2) {
  23528. return null;
  23529. }
  23530. return this._rigCameras[1].getTarget();
  23531. };
  23532. /**
  23533. * @hidden
  23534. */
  23535. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23536. if (this.cameraRigMode === mode) {
  23537. return;
  23538. }
  23539. while (this._rigCameras.length > 0) {
  23540. var camera = this._rigCameras.pop();
  23541. if (camera) {
  23542. camera.dispose();
  23543. }
  23544. }
  23545. this.cameraRigMode = mode;
  23546. this._cameraRigParams = {};
  23547. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23548. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23549. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23550. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23551. // create the rig cameras, unless none
  23552. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23553. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23554. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23555. if (leftCamera && rightCamera) {
  23556. this._rigCameras.push(leftCamera);
  23557. this._rigCameras.push(rightCamera);
  23558. }
  23559. }
  23560. switch (this.cameraRigMode) {
  23561. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23562. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23563. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23564. break;
  23565. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23566. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23567. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23568. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23569. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23570. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23571. break;
  23572. case Camera.RIG_MODE_VR:
  23573. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23574. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23575. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23576. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23577. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23578. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23579. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23580. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23581. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23582. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23583. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23584. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23585. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23586. if (metrics.compensateDistortion) {
  23587. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23588. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23589. }
  23590. break;
  23591. case Camera.RIG_MODE_WEBVR:
  23592. if (rigParams.vrDisplay) {
  23593. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23594. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23595. //Left eye
  23596. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23597. this._rigCameras[0].setCameraRigParameter("left", true);
  23598. //leaving this for future reference
  23599. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23600. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23601. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23602. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23603. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23604. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23605. this._rigCameras[0].parent = this;
  23606. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23607. //Right eye
  23608. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23609. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23610. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23611. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23612. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23613. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23614. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23615. this._rigCameras[1].parent = this;
  23616. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23617. if (Camera.UseAlternateWebVRRendering) {
  23618. this._rigCameras[1]._skipRendering = true;
  23619. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23620. }
  23621. }
  23622. break;
  23623. }
  23624. this._cascadePostProcessesToRigCams();
  23625. this.update();
  23626. };
  23627. Camera.prototype._getVRProjectionMatrix = function () {
  23628. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23629. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23630. return this._projectionMatrix;
  23631. };
  23632. Camera.prototype._updateCameraRotationMatrix = function () {
  23633. //Here for WebVR
  23634. };
  23635. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23636. //Here for WebVR
  23637. };
  23638. /**
  23639. * This function MUST be overwritten by the different WebVR cameras available.
  23640. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23641. */
  23642. Camera.prototype._getWebVRProjectionMatrix = function () {
  23643. return BABYLON.Matrix.Identity();
  23644. };
  23645. /**
  23646. * This function MUST be overwritten by the different WebVR cameras available.
  23647. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23648. */
  23649. Camera.prototype._getWebVRViewMatrix = function () {
  23650. return BABYLON.Matrix.Identity();
  23651. };
  23652. /** @hidden */
  23653. Camera.prototype.setCameraRigParameter = function (name, value) {
  23654. if (!this._cameraRigParams) {
  23655. this._cameraRigParams = {};
  23656. }
  23657. this._cameraRigParams[name] = value;
  23658. //provisionnally:
  23659. if (name === "interaxialDistance") {
  23660. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23661. }
  23662. };
  23663. /**
  23664. * needs to be overridden by children so sub has required properties to be copied
  23665. * @hidden
  23666. */
  23667. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23668. return null;
  23669. };
  23670. /**
  23671. * May need to be overridden by children
  23672. * @hidden
  23673. */
  23674. Camera.prototype._updateRigCameras = function () {
  23675. for (var i = 0; i < this._rigCameras.length; i++) {
  23676. this._rigCameras[i].minZ = this.minZ;
  23677. this._rigCameras[i].maxZ = this.maxZ;
  23678. this._rigCameras[i].fov = this.fov;
  23679. }
  23680. // only update viewport when ANAGLYPH
  23681. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23682. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23683. }
  23684. };
  23685. /** @hidden */
  23686. Camera.prototype._setupInputs = function () {
  23687. };
  23688. /**
  23689. * Serialiaze the camera setup to a json represention
  23690. * @returns the JSON representation
  23691. */
  23692. Camera.prototype.serialize = function () {
  23693. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23694. // Type
  23695. serializationObject.type = this.getClassName();
  23696. // Parent
  23697. if (this.parent) {
  23698. serializationObject.parentId = this.parent.id;
  23699. }
  23700. if (this.inputs) {
  23701. this.inputs.serialize(serializationObject);
  23702. }
  23703. // Animations
  23704. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23705. serializationObject.ranges = this.serializeAnimationRanges();
  23706. return serializationObject;
  23707. };
  23708. /**
  23709. * Clones the current camera.
  23710. * @param name The cloned camera name
  23711. * @returns the cloned camera
  23712. */
  23713. Camera.prototype.clone = function (name) {
  23714. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23715. };
  23716. /**
  23717. * Gets the direction of the camera relative to a given local axis.
  23718. * @param localAxis Defines the reference axis to provide a relative direction.
  23719. * @return the direction
  23720. */
  23721. Camera.prototype.getDirection = function (localAxis) {
  23722. var result = BABYLON.Vector3.Zero();
  23723. this.getDirectionToRef(localAxis, result);
  23724. return result;
  23725. };
  23726. /**
  23727. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23728. * @param localAxis Defines the reference axis to provide a relative direction.
  23729. * @param result Defines the vector to store the result in
  23730. */
  23731. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23732. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23733. };
  23734. /**
  23735. * Gets a camera constructor for a given camera type
  23736. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23737. * @param name The name of the camera the result will be able to instantiate
  23738. * @param scene The scene the result will construct the camera in
  23739. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23740. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23741. * @returns a factory method to construc the camera
  23742. */
  23743. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23744. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23745. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23746. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23747. interaxial_distance: interaxial_distance,
  23748. isStereoscopicSideBySide: isStereoscopicSideBySide
  23749. });
  23750. if (constructorFunc) {
  23751. return constructorFunc;
  23752. }
  23753. // Default to universal camera
  23754. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23755. };
  23756. /**
  23757. * Compute the world matrix of the camera.
  23758. * @returns the camera workd matrix
  23759. */
  23760. Camera.prototype.computeWorldMatrix = function () {
  23761. return this.getWorldMatrix();
  23762. };
  23763. /**
  23764. * Parse a JSON and creates the camera from the parsed information
  23765. * @param parsedCamera The JSON to parse
  23766. * @param scene The scene to instantiate the camera in
  23767. * @returns the newly constructed camera
  23768. */
  23769. Camera.Parse = function (parsedCamera, scene) {
  23770. var type = parsedCamera.type;
  23771. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23772. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23773. // Parent
  23774. if (parsedCamera.parentId) {
  23775. camera._waitingParentId = parsedCamera.parentId;
  23776. }
  23777. //If camera has an input manager, let it parse inputs settings
  23778. if (camera.inputs) {
  23779. camera.inputs.parse(parsedCamera);
  23780. camera._setupInputs();
  23781. }
  23782. if (camera.setPosition) { // need to force position
  23783. camera.position.copyFromFloats(0, 0, 0);
  23784. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23785. }
  23786. // Target
  23787. if (parsedCamera.target) {
  23788. if (camera.setTarget) {
  23789. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23790. }
  23791. }
  23792. // Apply 3d rig, when found
  23793. if (parsedCamera.cameraRigMode) {
  23794. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23795. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23796. }
  23797. // Animations
  23798. if (parsedCamera.animations) {
  23799. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23800. var parsedAnimation = parsedCamera.animations[animationIndex];
  23801. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23802. }
  23803. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23804. }
  23805. if (parsedCamera.autoAnimate) {
  23806. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23807. }
  23808. return camera;
  23809. };
  23810. /**
  23811. * This is the default projection mode used by the cameras.
  23812. * It helps recreating a feeling of perspective and better appreciate depth.
  23813. * This is the best way to simulate real life cameras.
  23814. */
  23815. Camera.PERSPECTIVE_CAMERA = 0;
  23816. /**
  23817. * This helps creating camera with an orthographic mode.
  23818. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23819. */
  23820. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23821. /**
  23822. * This is the default FOV mode for perspective cameras.
  23823. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23824. */
  23825. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23826. /**
  23827. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23828. */
  23829. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23830. /**
  23831. * This specifies ther is no need for a camera rig.
  23832. * Basically only one eye is rendered corresponding to the camera.
  23833. */
  23834. Camera.RIG_MODE_NONE = 0;
  23835. /**
  23836. * Simulates a camera Rig with one blue eye and one red eye.
  23837. * This can be use with 3d blue and red glasses.
  23838. */
  23839. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23840. /**
  23841. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23842. */
  23843. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23844. /**
  23845. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23846. */
  23847. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23848. /**
  23849. * Defines that both eyes of the camera will be rendered over under each other.
  23850. */
  23851. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23852. /**
  23853. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23854. */
  23855. Camera.RIG_MODE_VR = 20;
  23856. /**
  23857. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23858. */
  23859. Camera.RIG_MODE_WEBVR = 21;
  23860. /**
  23861. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23862. */
  23863. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23864. /**
  23865. * @hidden
  23866. * Might be removed once multiview will be a thing
  23867. */
  23868. Camera.UseAlternateWebVRRendering = false;
  23869. __decorate([
  23870. BABYLON.serializeAsVector3()
  23871. ], Camera.prototype, "position", void 0);
  23872. __decorate([
  23873. BABYLON.serializeAsVector3()
  23874. ], Camera.prototype, "upVector", void 0);
  23875. __decorate([
  23876. BABYLON.serialize()
  23877. ], Camera.prototype, "orthoLeft", void 0);
  23878. __decorate([
  23879. BABYLON.serialize()
  23880. ], Camera.prototype, "orthoRight", void 0);
  23881. __decorate([
  23882. BABYLON.serialize()
  23883. ], Camera.prototype, "orthoBottom", void 0);
  23884. __decorate([
  23885. BABYLON.serialize()
  23886. ], Camera.prototype, "orthoTop", void 0);
  23887. __decorate([
  23888. BABYLON.serialize()
  23889. ], Camera.prototype, "fov", void 0);
  23890. __decorate([
  23891. BABYLON.serialize()
  23892. ], Camera.prototype, "minZ", void 0);
  23893. __decorate([
  23894. BABYLON.serialize()
  23895. ], Camera.prototype, "maxZ", void 0);
  23896. __decorate([
  23897. BABYLON.serialize()
  23898. ], Camera.prototype, "inertia", void 0);
  23899. __decorate([
  23900. BABYLON.serialize()
  23901. ], Camera.prototype, "mode", void 0);
  23902. __decorate([
  23903. BABYLON.serialize()
  23904. ], Camera.prototype, "layerMask", void 0);
  23905. __decorate([
  23906. BABYLON.serialize()
  23907. ], Camera.prototype, "fovMode", void 0);
  23908. __decorate([
  23909. BABYLON.serialize()
  23910. ], Camera.prototype, "cameraRigMode", void 0);
  23911. __decorate([
  23912. BABYLON.serialize()
  23913. ], Camera.prototype, "interaxialDistance", void 0);
  23914. __decorate([
  23915. BABYLON.serialize()
  23916. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23917. return Camera;
  23918. }(BABYLON.Node));
  23919. BABYLON.Camera = Camera;
  23920. })(BABYLON || (BABYLON = {}));
  23921. //# sourceMappingURL=babylon.camera.js.map
  23922. var BABYLON;
  23923. (function (BABYLON) {
  23924. /**
  23925. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23926. * It is enable to manage the different groups as well as the different necessary sort functions.
  23927. * This should not be used directly aside of the few static configurations
  23928. */
  23929. var RenderingManager = /** @class */ (function () {
  23930. /**
  23931. * Instantiates a new rendering group for a particular scene
  23932. * @param scene Defines the scene the groups belongs to
  23933. */
  23934. function RenderingManager(scene) {
  23935. /**
  23936. * @hidden
  23937. */
  23938. this._useSceneAutoClearSetup = false;
  23939. this._renderingGroups = new Array();
  23940. this._autoClearDepthStencil = {};
  23941. this._customOpaqueSortCompareFn = {};
  23942. this._customAlphaTestSortCompareFn = {};
  23943. this._customTransparentSortCompareFn = {};
  23944. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23945. this._scene = scene;
  23946. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23947. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23948. }
  23949. }
  23950. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23951. if (depth === void 0) { depth = true; }
  23952. if (stencil === void 0) { stencil = true; }
  23953. if (this._depthStencilBufferAlreadyCleaned) {
  23954. return;
  23955. }
  23956. this._scene.getEngine().clear(null, false, depth, stencil);
  23957. this._depthStencilBufferAlreadyCleaned = true;
  23958. };
  23959. /**
  23960. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23961. * @hidden
  23962. */
  23963. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23964. // Update the observable context (not null as it only goes away on dispose)
  23965. var info = this._renderingGroupInfo;
  23966. info.scene = this._scene;
  23967. info.camera = this._scene.activeCamera;
  23968. // Dispatch sprites
  23969. if (this._scene.spriteManagers && renderSprites) {
  23970. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23971. var manager = this._scene.spriteManagers[index];
  23972. this.dispatchSprites(manager);
  23973. }
  23974. }
  23975. // Render
  23976. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23977. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23978. var renderingGroup = this._renderingGroups[index];
  23979. if (!renderingGroup)
  23980. continue;
  23981. var renderingGroupMask = Math.pow(2, index);
  23982. info.renderingGroupId = index;
  23983. // Before Observable
  23984. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23985. // Clear depth/stencil if needed
  23986. if (RenderingManager.AUTOCLEAR) {
  23987. var autoClear = this._useSceneAutoClearSetup ?
  23988. this._scene.getAutoClearDepthStencilSetup(index) :
  23989. this._autoClearDepthStencil[index];
  23990. if (autoClear && autoClear.autoClear) {
  23991. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23992. }
  23993. }
  23994. // Render
  23995. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23996. var step = _a[_i];
  23997. step.action(index);
  23998. }
  23999. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24000. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24001. var step = _c[_b];
  24002. step.action(index);
  24003. }
  24004. // After Observable
  24005. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24006. }
  24007. };
  24008. /**
  24009. * Resets the different information of the group to prepare a new frame
  24010. * @hidden
  24011. */
  24012. RenderingManager.prototype.reset = function () {
  24013. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24014. var renderingGroup = this._renderingGroups[index];
  24015. if (renderingGroup) {
  24016. renderingGroup.prepare();
  24017. }
  24018. }
  24019. };
  24020. /**
  24021. * Dispose and release the group and its associated resources.
  24022. * @hidden
  24023. */
  24024. RenderingManager.prototype.dispose = function () {
  24025. this.freeRenderingGroups();
  24026. this._renderingGroups.length = 0;
  24027. this._renderingGroupInfo = null;
  24028. };
  24029. /**
  24030. * Clear the info related to rendering groups preventing retention points during dispose.
  24031. */
  24032. RenderingManager.prototype.freeRenderingGroups = function () {
  24033. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24034. var renderingGroup = this._renderingGroups[index];
  24035. if (renderingGroup) {
  24036. renderingGroup.dispose();
  24037. }
  24038. }
  24039. };
  24040. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24041. if (this._renderingGroups[renderingGroupId] === undefined) {
  24042. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24043. }
  24044. };
  24045. /**
  24046. * Add a sprite manager to the rendering manager in order to render it this frame.
  24047. * @param spriteManager Define the sprite manager to render
  24048. */
  24049. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24050. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24051. this._prepareRenderingGroup(renderingGroupId);
  24052. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24053. };
  24054. /**
  24055. * Add a particle system to the rendering manager in order to render it this frame.
  24056. * @param particleSystem Define the particle system to render
  24057. */
  24058. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24059. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24060. this._prepareRenderingGroup(renderingGroupId);
  24061. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24062. };
  24063. /**
  24064. * Add a submesh to the manager in order to render it this frame
  24065. * @param subMesh The submesh to dispatch
  24066. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24067. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24068. */
  24069. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24070. if (mesh === undefined) {
  24071. mesh = subMesh.getMesh();
  24072. }
  24073. var renderingGroupId = mesh.renderingGroupId || 0;
  24074. this._prepareRenderingGroup(renderingGroupId);
  24075. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24076. };
  24077. /**
  24078. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24079. * This allowed control for front to back rendering or reversly depending of the special needs.
  24080. *
  24081. * @param renderingGroupId The rendering group id corresponding to its index
  24082. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24083. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24084. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24085. */
  24086. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24087. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24088. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24089. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24090. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24091. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24092. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24093. if (this._renderingGroups[renderingGroupId]) {
  24094. var group = this._renderingGroups[renderingGroupId];
  24095. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24096. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24097. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24098. }
  24099. };
  24100. /**
  24101. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24102. *
  24103. * @param renderingGroupId The rendering group id corresponding to its index
  24104. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24105. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24106. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24107. */
  24108. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24109. if (depth === void 0) { depth = true; }
  24110. if (stencil === void 0) { stencil = true; }
  24111. this._autoClearDepthStencil[renderingGroupId] = {
  24112. autoClear: autoClearDepthStencil,
  24113. depth: depth,
  24114. stencil: stencil
  24115. };
  24116. };
  24117. /**
  24118. * Gets the current auto clear configuration for one rendering group of the rendering
  24119. * manager.
  24120. * @param index the rendering group index to get the information for
  24121. * @returns The auto clear setup for the requested rendering group
  24122. */
  24123. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24124. return this._autoClearDepthStencil[index];
  24125. };
  24126. /**
  24127. * The max id used for rendering groups (not included)
  24128. */
  24129. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24130. /**
  24131. * The min id used for rendering groups (included)
  24132. */
  24133. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24134. /**
  24135. * Used to globally prevent autoclearing scenes.
  24136. */
  24137. RenderingManager.AUTOCLEAR = true;
  24138. return RenderingManager;
  24139. }());
  24140. BABYLON.RenderingManager = RenderingManager;
  24141. })(BABYLON || (BABYLON = {}));
  24142. //# sourceMappingURL=babylon.renderingManager.js.map
  24143. var BABYLON;
  24144. (function (BABYLON) {
  24145. /**
  24146. * This represents the object necessary to create a rendering group.
  24147. * This is exclusively used and created by the rendering manager.
  24148. * To modify the behavior, you use the available helpers in your scene or meshes.
  24149. * @hidden
  24150. */
  24151. var RenderingGroup = /** @class */ (function () {
  24152. /**
  24153. * Creates a new rendering group.
  24154. * @param index The rendering group index
  24155. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24156. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24157. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24158. */
  24159. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24160. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24161. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24162. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24163. this.index = index;
  24164. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24165. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24166. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24167. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24168. this._particleSystems = new BABYLON.SmartArray(256);
  24169. this._spriteManagers = new BABYLON.SmartArray(256);
  24170. this._edgesRenderers = new BABYLON.SmartArray(16);
  24171. this._scene = scene;
  24172. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24173. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24174. this.transparentSortCompareFn = transparentSortCompareFn;
  24175. }
  24176. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24177. /**
  24178. * Set the opaque sort comparison function.
  24179. * If null the sub meshes will be render in the order they were created
  24180. */
  24181. set: function (value) {
  24182. this._opaqueSortCompareFn = value;
  24183. if (value) {
  24184. this._renderOpaque = this.renderOpaqueSorted;
  24185. }
  24186. else {
  24187. this._renderOpaque = RenderingGroup.renderUnsorted;
  24188. }
  24189. },
  24190. enumerable: true,
  24191. configurable: true
  24192. });
  24193. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24194. /**
  24195. * Set the alpha test sort comparison function.
  24196. * If null the sub meshes will be render in the order they were created
  24197. */
  24198. set: function (value) {
  24199. this._alphaTestSortCompareFn = value;
  24200. if (value) {
  24201. this._renderAlphaTest = this.renderAlphaTestSorted;
  24202. }
  24203. else {
  24204. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24205. }
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24211. /**
  24212. * Set the transparent sort comparison function.
  24213. * If null the sub meshes will be render in the order they were created
  24214. */
  24215. set: function (value) {
  24216. if (value) {
  24217. this._transparentSortCompareFn = value;
  24218. }
  24219. else {
  24220. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24221. }
  24222. this._renderTransparent = this.renderTransparentSorted;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. /**
  24228. * Render all the sub meshes contained in the group.
  24229. * @param customRenderFunction Used to override the default render behaviour of the group.
  24230. * @returns true if rendered some submeshes.
  24231. */
  24232. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24233. if (customRenderFunction) {
  24234. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24235. return;
  24236. }
  24237. var engine = this._scene.getEngine();
  24238. // Depth only
  24239. if (this._depthOnlySubMeshes.length !== 0) {
  24240. engine.setColorWrite(false);
  24241. this._renderAlphaTest(this._depthOnlySubMeshes);
  24242. engine.setColorWrite(true);
  24243. }
  24244. // Opaque
  24245. if (this._opaqueSubMeshes.length !== 0) {
  24246. this._renderOpaque(this._opaqueSubMeshes);
  24247. }
  24248. // Alpha test
  24249. if (this._alphaTestSubMeshes.length !== 0) {
  24250. this._renderAlphaTest(this._alphaTestSubMeshes);
  24251. }
  24252. var stencilState = engine.getStencilBuffer();
  24253. engine.setStencilBuffer(false);
  24254. // Sprites
  24255. if (renderSprites) {
  24256. this._renderSprites();
  24257. }
  24258. // Particles
  24259. if (renderParticles) {
  24260. this._renderParticles(activeMeshes);
  24261. }
  24262. if (this.onBeforeTransparentRendering) {
  24263. this.onBeforeTransparentRendering();
  24264. }
  24265. // Transparent
  24266. if (this._transparentSubMeshes.length !== 0) {
  24267. this._renderTransparent(this._transparentSubMeshes);
  24268. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24269. }
  24270. // Set back stencil to false in case it changes before the edge renderer.
  24271. engine.setStencilBuffer(false);
  24272. // Edges
  24273. if (this._edgesRenderers.length) {
  24274. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24275. this._edgesRenderers.data[edgesRendererIndex].render();
  24276. }
  24277. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24278. }
  24279. // Restore Stencil state.
  24280. engine.setStencilBuffer(stencilState);
  24281. };
  24282. /**
  24283. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24284. * @param subMeshes The submeshes to render
  24285. */
  24286. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24287. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24288. };
  24289. /**
  24290. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24291. * @param subMeshes The submeshes to render
  24292. */
  24293. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24294. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24295. };
  24296. /**
  24297. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24298. * @param subMeshes The submeshes to render
  24299. */
  24300. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24301. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24302. };
  24303. /**
  24304. * Renders the submeshes in a specified order.
  24305. * @param subMeshes The submeshes to sort before render
  24306. * @param sortCompareFn The comparison function use to sort
  24307. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24308. * @param transparent Specifies to activate blending if true
  24309. */
  24310. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24311. var subIndex = 0;
  24312. var subMesh;
  24313. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24314. for (; subIndex < subMeshes.length; subIndex++) {
  24315. subMesh = subMeshes.data[subIndex];
  24316. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24317. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24318. }
  24319. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24320. if (sortCompareFn) {
  24321. sortedArray.sort(sortCompareFn);
  24322. }
  24323. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24324. subMesh = sortedArray[subIndex];
  24325. if (transparent) {
  24326. var material = subMesh.getMaterial();
  24327. if (material && material.needDepthPrePass) {
  24328. var engine = material.getScene().getEngine();
  24329. engine.setColorWrite(false);
  24330. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24331. subMesh.render(false);
  24332. engine.setColorWrite(true);
  24333. }
  24334. }
  24335. subMesh.render(transparent);
  24336. }
  24337. };
  24338. /**
  24339. * Renders the submeshes in the order they were dispatched (no sort applied).
  24340. * @param subMeshes The submeshes to render
  24341. */
  24342. RenderingGroup.renderUnsorted = function (subMeshes) {
  24343. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24344. var submesh = subMeshes.data[subIndex];
  24345. submesh.render(false);
  24346. }
  24347. };
  24348. /**
  24349. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24350. * are rendered back to front if in the same alpha index.
  24351. *
  24352. * @param a The first submesh
  24353. * @param b The second submesh
  24354. * @returns The result of the comparison
  24355. */
  24356. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24357. // Alpha index first
  24358. if (a._alphaIndex > b._alphaIndex) {
  24359. return 1;
  24360. }
  24361. if (a._alphaIndex < b._alphaIndex) {
  24362. return -1;
  24363. }
  24364. // Then distance to camera
  24365. return RenderingGroup.backToFrontSortCompare(a, b);
  24366. };
  24367. /**
  24368. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24369. * are rendered back to front.
  24370. *
  24371. * @param a The first submesh
  24372. * @param b The second submesh
  24373. * @returns The result of the comparison
  24374. */
  24375. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24376. // Then distance to camera
  24377. if (a._distanceToCamera < b._distanceToCamera) {
  24378. return 1;
  24379. }
  24380. if (a._distanceToCamera > b._distanceToCamera) {
  24381. return -1;
  24382. }
  24383. return 0;
  24384. };
  24385. /**
  24386. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24387. * are rendered front to back (prevent overdraw).
  24388. *
  24389. * @param a The first submesh
  24390. * @param b The second submesh
  24391. * @returns The result of the comparison
  24392. */
  24393. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24394. // Then distance to camera
  24395. if (a._distanceToCamera < b._distanceToCamera) {
  24396. return -1;
  24397. }
  24398. if (a._distanceToCamera > b._distanceToCamera) {
  24399. return 1;
  24400. }
  24401. return 0;
  24402. };
  24403. /**
  24404. * Resets the different lists of submeshes to prepare a new frame.
  24405. */
  24406. RenderingGroup.prototype.prepare = function () {
  24407. this._opaqueSubMeshes.reset();
  24408. this._transparentSubMeshes.reset();
  24409. this._alphaTestSubMeshes.reset();
  24410. this._depthOnlySubMeshes.reset();
  24411. this._particleSystems.reset();
  24412. this._spriteManagers.reset();
  24413. this._edgesRenderers.reset();
  24414. };
  24415. RenderingGroup.prototype.dispose = function () {
  24416. this._opaqueSubMeshes.dispose();
  24417. this._transparentSubMeshes.dispose();
  24418. this._alphaTestSubMeshes.dispose();
  24419. this._depthOnlySubMeshes.dispose();
  24420. this._particleSystems.dispose();
  24421. this._spriteManagers.dispose();
  24422. this._edgesRenderers.dispose();
  24423. };
  24424. /**
  24425. * Inserts the submesh in its correct queue depending on its material.
  24426. * @param subMesh The submesh to dispatch
  24427. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24428. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24429. */
  24430. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24431. // Get mesh and materials if not provided
  24432. if (mesh === undefined) {
  24433. mesh = subMesh.getMesh();
  24434. }
  24435. if (material === undefined) {
  24436. material = subMesh.getMaterial();
  24437. }
  24438. if (material === null || material === undefined) {
  24439. return;
  24440. }
  24441. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24442. this._transparentSubMeshes.push(subMesh);
  24443. }
  24444. else if (material.needAlphaTesting()) { // Alpha test
  24445. if (material.needDepthPrePass) {
  24446. this._depthOnlySubMeshes.push(subMesh);
  24447. }
  24448. this._alphaTestSubMeshes.push(subMesh);
  24449. }
  24450. else {
  24451. if (material.needDepthPrePass) {
  24452. this._depthOnlySubMeshes.push(subMesh);
  24453. }
  24454. this._opaqueSubMeshes.push(subMesh); // Opaque
  24455. }
  24456. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24457. this._edgesRenderers.push(mesh._edgesRenderer);
  24458. }
  24459. };
  24460. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24461. this._spriteManagers.push(spriteManager);
  24462. };
  24463. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24464. this._particleSystems.push(particleSystem);
  24465. };
  24466. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24467. if (this._particleSystems.length === 0) {
  24468. return;
  24469. }
  24470. // Particles
  24471. var activeCamera = this._scene.activeCamera;
  24472. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24473. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24474. var particleSystem = this._particleSystems.data[particleIndex];
  24475. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24476. continue;
  24477. }
  24478. var emitter = particleSystem.emitter;
  24479. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24480. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24481. }
  24482. }
  24483. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24484. };
  24485. RenderingGroup.prototype._renderSprites = function () {
  24486. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24487. return;
  24488. }
  24489. // Sprites
  24490. var activeCamera = this._scene.activeCamera;
  24491. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24492. for (var id = 0; id < this._spriteManagers.length; id++) {
  24493. var spriteManager = this._spriteManagers.data[id];
  24494. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24495. spriteManager.render();
  24496. }
  24497. }
  24498. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24499. };
  24500. return RenderingGroup;
  24501. }());
  24502. BABYLON.RenderingGroup = RenderingGroup;
  24503. })(BABYLON || (BABYLON = {}));
  24504. //# sourceMappingURL=babylon.renderingGroup.js.map
  24505. var BABYLON;
  24506. (function (BABYLON) {
  24507. /**
  24508. * Groups all the scene component constants in one place to ease maintenance.
  24509. * @hidden
  24510. */
  24511. var SceneComponentConstants = /** @class */ (function () {
  24512. function SceneComponentConstants() {
  24513. }
  24514. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24515. SceneComponentConstants.NAME_LAYER = "Layer";
  24516. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24517. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24518. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24519. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24520. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24521. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24522. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24523. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24524. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24525. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24526. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24527. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24528. SceneComponentConstants.NAME_OCTREE = "Octree";
  24529. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24530. SceneComponentConstants.NAME_AUDIO = "Audio";
  24531. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24532. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24533. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24534. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24535. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24536. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24537. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24538. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24539. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24540. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24541. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24542. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24543. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24544. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24545. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24546. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24547. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24548. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24549. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24550. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24551. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24552. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24553. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24554. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24555. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24556. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24557. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24558. return SceneComponentConstants;
  24559. }());
  24560. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24561. /**
  24562. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24563. * @hidden
  24564. */
  24565. var Stage = /** @class */ (function (_super) {
  24566. __extends(Stage, _super);
  24567. /**
  24568. * Hide ctor from the rest of the world.
  24569. * @param items The items to add.
  24570. */
  24571. function Stage(items) {
  24572. return _super.apply(this, items) || this;
  24573. }
  24574. /**
  24575. * Creates a new Stage.
  24576. * @returns A new instance of a Stage
  24577. */
  24578. Stage.Create = function () {
  24579. return Object.create(Stage.prototype);
  24580. };
  24581. /**
  24582. * Registers a step in an ordered way in the targeted stage.
  24583. * @param index Defines the position to register the step in
  24584. * @param component Defines the component attached to the step
  24585. * @param action Defines the action to launch during the step
  24586. */
  24587. Stage.prototype.registerStep = function (index, component, action) {
  24588. var i = 0;
  24589. var maxIndex = Number.MAX_VALUE;
  24590. for (; i < this.length && i < maxIndex; i++) {
  24591. var step = this[i];
  24592. maxIndex = step.index;
  24593. }
  24594. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24595. };
  24596. /**
  24597. * Clears all the steps from the stage.
  24598. */
  24599. Stage.prototype.clear = function () {
  24600. this.length = 0;
  24601. };
  24602. return Stage;
  24603. }(Array));
  24604. BABYLON.Stage = Stage;
  24605. })(BABYLON || (BABYLON = {}));
  24606. //# sourceMappingURL=babylon.sceneComponent.js.map
  24607. var BABYLON;
  24608. (function (BABYLON) {
  24609. /**
  24610. * Base class of the scene acting as a container for the different elements composing a scene.
  24611. * This class is dynamically extended by the different components of the scene increasing
  24612. * flexibility and reducing coupling
  24613. */
  24614. var AbstractScene = /** @class */ (function () {
  24615. function AbstractScene() {
  24616. /**
  24617. * Gets the list of root nodes (ie. nodes with no parent)
  24618. */
  24619. this.rootNodes = new Array();
  24620. /** All of the cameras added to this scene
  24621. * @see http://doc.babylonjs.com/babylon101/cameras
  24622. */
  24623. this.cameras = new Array();
  24624. /**
  24625. * All of the lights added to this scene
  24626. * @see http://doc.babylonjs.com/babylon101/lights
  24627. */
  24628. this.lights = new Array();
  24629. /**
  24630. * All of the (abstract) meshes added to this scene
  24631. */
  24632. this.meshes = new Array();
  24633. /**
  24634. * The list of skeletons added to the scene
  24635. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24636. */
  24637. this.skeletons = new Array();
  24638. /**
  24639. * All of the particle systems added to this scene
  24640. * @see http://doc.babylonjs.com/babylon101/particles
  24641. */
  24642. this.particleSystems = new Array();
  24643. /**
  24644. * Gets a list of Animations associated with the scene
  24645. */
  24646. this.animations = [];
  24647. /**
  24648. * All of the animation groups added to this scene
  24649. * @see http://doc.babylonjs.com/how_to/group
  24650. */
  24651. this.animationGroups = new Array();
  24652. /**
  24653. * All of the multi-materials added to this scene
  24654. * @see http://doc.babylonjs.com/how_to/multi_materials
  24655. */
  24656. this.multiMaterials = new Array();
  24657. /**
  24658. * All of the materials added to this scene
  24659. * @see http://doc.babylonjs.com/babylon101/materials
  24660. */
  24661. this.materials = new Array();
  24662. /**
  24663. * The list of morph target managers added to the scene
  24664. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24665. */
  24666. this.morphTargetManagers = new Array();
  24667. /**
  24668. * The list of geometries used in the scene.
  24669. */
  24670. this.geometries = new Array();
  24671. /**
  24672. * All of the tranform nodes added to this scene
  24673. * @see http://doc.babylonjs.com/how_to/transformnode
  24674. */
  24675. this.transformNodes = new Array();
  24676. /**
  24677. * ActionManagers available on the scene.
  24678. */
  24679. this.actionManagers = new Array();
  24680. /**
  24681. * Textures to keep.
  24682. */
  24683. this.textures = new Array();
  24684. }
  24685. /**
  24686. * Adds a parser in the list of available ones
  24687. * @param name Defines the name of the parser
  24688. * @param parser Defines the parser to add
  24689. */
  24690. AbstractScene.AddParser = function (name, parser) {
  24691. this._BabylonFileParsers[name] = parser;
  24692. };
  24693. /**
  24694. * Gets a general parser from the list of avaialble ones
  24695. * @param name Defines the name of the parser
  24696. * @returns the requested parser or null
  24697. */
  24698. AbstractScene.GetParser = function (name) {
  24699. if (this._BabylonFileParsers[name]) {
  24700. return this._BabylonFileParsers[name];
  24701. }
  24702. return null;
  24703. };
  24704. /**
  24705. * Adds n individual parser in the list of available ones
  24706. * @param name Defines the name of the parser
  24707. * @param parser Defines the parser to add
  24708. */
  24709. AbstractScene.AddIndividualParser = function (name, parser) {
  24710. this._IndividualBabylonFileParsers[name] = parser;
  24711. };
  24712. /**
  24713. * Gets an individual parser from the list of avaialble ones
  24714. * @param name Defines the name of the parser
  24715. * @returns the requested parser or null
  24716. */
  24717. AbstractScene.GetIndividualParser = function (name) {
  24718. if (this._IndividualBabylonFileParsers[name]) {
  24719. return this._IndividualBabylonFileParsers[name];
  24720. }
  24721. return null;
  24722. };
  24723. /**
  24724. * Parser json data and populate both a scene and its associated container object
  24725. * @param jsonData Defines the data to parse
  24726. * @param scene Defines the scene to parse the data for
  24727. * @param container Defines the container attached to the parsing sequence
  24728. * @param rootUrl Defines the root url of the data
  24729. */
  24730. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24731. for (var parserName in this._BabylonFileParsers) {
  24732. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24733. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24734. }
  24735. }
  24736. };
  24737. /**
  24738. * Stores the list of available parsers in the application.
  24739. */
  24740. AbstractScene._BabylonFileParsers = {};
  24741. /**
  24742. * Stores the list of available individual parsers in the application.
  24743. */
  24744. AbstractScene._IndividualBabylonFileParsers = {};
  24745. return AbstractScene;
  24746. }());
  24747. BABYLON.AbstractScene = AbstractScene;
  24748. })(BABYLON || (BABYLON = {}));
  24749. //# sourceMappingURL=babylon.abstractScene.js.map
  24750. var BABYLON;
  24751. (function (BABYLON) {
  24752. /** @hidden */
  24753. var ClickInfo = /** @class */ (function () {
  24754. function ClickInfo() {
  24755. this._singleClick = false;
  24756. this._doubleClick = false;
  24757. this._hasSwiped = false;
  24758. this._ignore = false;
  24759. }
  24760. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24761. get: function () {
  24762. return this._singleClick;
  24763. },
  24764. set: function (b) {
  24765. this._singleClick = b;
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24771. get: function () {
  24772. return this._doubleClick;
  24773. },
  24774. set: function (b) {
  24775. this._doubleClick = b;
  24776. },
  24777. enumerable: true,
  24778. configurable: true
  24779. });
  24780. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24781. get: function () {
  24782. return this._hasSwiped;
  24783. },
  24784. set: function (b) {
  24785. this._hasSwiped = b;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24791. get: function () {
  24792. return this._ignore;
  24793. },
  24794. set: function (b) {
  24795. this._ignore = b;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. return ClickInfo;
  24801. }());
  24802. /**
  24803. * This class is used by the onRenderingGroupObservable
  24804. */
  24805. var RenderingGroupInfo = /** @class */ (function () {
  24806. function RenderingGroupInfo() {
  24807. }
  24808. return RenderingGroupInfo;
  24809. }());
  24810. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24811. /**
  24812. * Represents a scene to be rendered by the engine.
  24813. * @see http://doc.babylonjs.com/features/scene
  24814. */
  24815. var Scene = /** @class */ (function (_super) {
  24816. __extends(Scene, _super);
  24817. /**
  24818. * Creates a new Scene
  24819. * @param engine defines the engine to use to render this scene
  24820. */
  24821. function Scene(engine) {
  24822. var _this = _super.call(this) || this;
  24823. // Members
  24824. /**
  24825. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24826. */
  24827. _this.autoClear = true;
  24828. /**
  24829. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24830. */
  24831. _this.autoClearDepthAndStencil = true;
  24832. /**
  24833. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24834. */
  24835. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24836. /**
  24837. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24838. */
  24839. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24840. _this._forceWireframe = false;
  24841. _this._forcePointsCloud = false;
  24842. /**
  24843. * Gets or sets a boolean indicating if animations are enabled
  24844. */
  24845. _this.animationsEnabled = true;
  24846. _this._animationPropertiesOverride = null;
  24847. /**
  24848. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24849. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24850. */
  24851. _this.useConstantAnimationDeltaTime = false;
  24852. /**
  24853. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24854. * Please note that it requires to run a ray cast through the scene on every frame
  24855. */
  24856. _this.constantlyUpdateMeshUnderPointer = false;
  24857. /**
  24858. * Defines the HTML cursor to use when hovering over interactive elements
  24859. */
  24860. _this.hoverCursor = "pointer";
  24861. /**
  24862. * Defines the HTML default cursor to use (empty by default)
  24863. */
  24864. _this.defaultCursor = "";
  24865. /**
  24866. * This is used to call preventDefault() on pointer down
  24867. * in order to block unwanted artifacts like system double clicks
  24868. */
  24869. _this.preventDefaultOnPointerDown = true;
  24870. // Metadata
  24871. /**
  24872. * Gets or sets user defined metadata
  24873. */
  24874. _this.metadata = null;
  24875. /**
  24876. * Use this array to add regular expressions used to disable offline support for specific urls
  24877. */
  24878. _this.disableOfflineSupportExceptionRules = new Array();
  24879. /**
  24880. * An event triggered when the scene is disposed.
  24881. */
  24882. _this.onDisposeObservable = new BABYLON.Observable();
  24883. _this._onDisposeObserver = null;
  24884. /**
  24885. * An event triggered before rendering the scene (right after animations and physics)
  24886. */
  24887. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24888. _this._onBeforeRenderObserver = null;
  24889. /**
  24890. * An event triggered after rendering the scene
  24891. */
  24892. _this.onAfterRenderObservable = new BABYLON.Observable();
  24893. _this._onAfterRenderObserver = null;
  24894. /**
  24895. * An event triggered before animating the scene
  24896. */
  24897. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24898. /**
  24899. * An event triggered after animations processing
  24900. */
  24901. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24902. /**
  24903. * An event triggered before draw calls are ready to be sent
  24904. */
  24905. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24906. /**
  24907. * An event triggered after draw calls have been sent
  24908. */
  24909. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24910. /**
  24911. * An event triggered when the scene is ready
  24912. */
  24913. _this.onReadyObservable = new BABYLON.Observable();
  24914. /**
  24915. * An event triggered before rendering a camera
  24916. */
  24917. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24918. _this._onBeforeCameraRenderObserver = null;
  24919. /**
  24920. * An event triggered after rendering a camera
  24921. */
  24922. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24923. _this._onAfterCameraRenderObserver = null;
  24924. /**
  24925. * An event triggered when active meshes evaluation is about to start
  24926. */
  24927. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24928. /**
  24929. * An event triggered when active meshes evaluation is done
  24930. */
  24931. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24932. /**
  24933. * An event triggered when particles rendering is about to start
  24934. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24935. */
  24936. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24937. /**
  24938. * An event triggered when particles rendering is done
  24939. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24940. */
  24941. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24942. /**
  24943. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24944. */
  24945. _this.onDataLoadedObservable = new BABYLON.Observable();
  24946. /**
  24947. * An event triggered when a camera is created
  24948. */
  24949. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24950. /**
  24951. * An event triggered when a camera is removed
  24952. */
  24953. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24954. /**
  24955. * An event triggered when a light is created
  24956. */
  24957. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24958. /**
  24959. * An event triggered when a light is removed
  24960. */
  24961. _this.onLightRemovedObservable = new BABYLON.Observable();
  24962. /**
  24963. * An event triggered when a geometry is created
  24964. */
  24965. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24966. /**
  24967. * An event triggered when a geometry is removed
  24968. */
  24969. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24970. /**
  24971. * An event triggered when a transform node is created
  24972. */
  24973. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24974. /**
  24975. * An event triggered when a transform node is removed
  24976. */
  24977. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24978. /**
  24979. * An event triggered when a mesh is created
  24980. */
  24981. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24982. /**
  24983. * An event triggered when a mesh is removed
  24984. */
  24985. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24986. /**
  24987. * An event triggered when a material is created
  24988. */
  24989. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24990. /**
  24991. * An event triggered when a material is removed
  24992. */
  24993. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24994. /**
  24995. * An event triggered when a texture is created
  24996. */
  24997. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24998. /**
  24999. * An event triggered when a texture is removed
  25000. */
  25001. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25002. /**
  25003. * An event triggered when render targets are about to be rendered
  25004. * Can happen multiple times per frame.
  25005. */
  25006. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25007. /**
  25008. * An event triggered when render targets were rendered.
  25009. * Can happen multiple times per frame.
  25010. */
  25011. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25012. /**
  25013. * An event triggered before calculating deterministic simulation step
  25014. */
  25015. _this.onBeforeStepObservable = new BABYLON.Observable();
  25016. /**
  25017. * An event triggered after calculating deterministic simulation step
  25018. */
  25019. _this.onAfterStepObservable = new BABYLON.Observable();
  25020. /**
  25021. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25022. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25023. * 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)
  25024. */
  25025. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25026. /**
  25027. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25028. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25029. * 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)
  25030. */
  25031. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25032. /**
  25033. * This Observable will when a mesh has been imported into the scene.
  25034. */
  25035. _this.onMeshImportedObservable = new BABYLON.Observable();
  25036. // Animations
  25037. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25038. /**
  25039. * 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).
  25040. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25041. */
  25042. _this.onPrePointerObservable = new BABYLON.Observable();
  25043. /**
  25044. * Observable event triggered each time an input event is received from the rendering canvas
  25045. */
  25046. _this.onPointerObservable = new BABYLON.Observable();
  25047. _this._meshPickProceed = false;
  25048. _this._currentPickResult = null;
  25049. _this._previousPickResult = null;
  25050. _this._totalPointersPressed = 0;
  25051. _this._doubleClickOccured = false;
  25052. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25053. _this.cameraToUseForPointers = null;
  25054. _this._pointerX = 0;
  25055. _this._pointerY = 0;
  25056. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25057. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25058. _this._startingPointerTime = 0;
  25059. _this._previousStartingPointerTime = 0;
  25060. _this._pointerCaptures = {};
  25061. // Deterministic lockstep
  25062. _this._timeAccumulator = 0;
  25063. _this._currentStepId = 0;
  25064. _this._currentInternalStep = 0;
  25065. // Keyboard
  25066. /**
  25067. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25068. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25069. */
  25070. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25071. /**
  25072. * Observable event triggered each time an keyboard event is received from the hosting window
  25073. */
  25074. _this.onKeyboardObservable = new BABYLON.Observable();
  25075. // Coordinates system
  25076. _this._useRightHandedSystem = false;
  25077. // Fog
  25078. _this._fogEnabled = true;
  25079. _this._fogMode = Scene.FOGMODE_NONE;
  25080. /**
  25081. * Gets or sets the fog color to use
  25082. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25083. * (Default is Color3(0.2, 0.2, 0.3))
  25084. */
  25085. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25086. /**
  25087. * Gets or sets the fog density to use
  25088. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25089. * (Default is 0.1)
  25090. */
  25091. _this.fogDensity = 0.1;
  25092. /**
  25093. * Gets or sets the fog start distance to use
  25094. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25095. * (Default is 0)
  25096. */
  25097. _this.fogStart = 0;
  25098. /**
  25099. * Gets or sets the fog end distance to use
  25100. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25101. * (Default is 1000)
  25102. */
  25103. _this.fogEnd = 1000.0;
  25104. // Lights
  25105. _this._shadowsEnabled = true;
  25106. _this._lightsEnabled = true;
  25107. /** All of the active cameras added to this scene. */
  25108. _this.activeCameras = new Array();
  25109. // Textures
  25110. _this._texturesEnabled = true;
  25111. // Particles
  25112. /**
  25113. * Gets or sets a boolean indicating if particles are enabled on this scene
  25114. */
  25115. _this.particlesEnabled = true;
  25116. // Sprites
  25117. /**
  25118. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25119. */
  25120. _this.spritesEnabled = true;
  25121. // Skeletons
  25122. _this._skeletonsEnabled = true;
  25123. // Lens flares
  25124. /**
  25125. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25126. */
  25127. _this.lensFlaresEnabled = true;
  25128. // Collisions
  25129. /**
  25130. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25131. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25132. */
  25133. _this.collisionsEnabled = true;
  25134. /**
  25135. * Defines the gravity applied to this scene (used only for collisions)
  25136. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25137. */
  25138. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25139. // Postprocesses
  25140. /**
  25141. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25142. */
  25143. _this.postProcessesEnabled = true;
  25144. /**
  25145. * The list of postprocesses added to the scene
  25146. */
  25147. _this.postProcesses = new Array();
  25148. // Customs render targets
  25149. /**
  25150. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25151. */
  25152. _this.renderTargetsEnabled = true;
  25153. /**
  25154. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25155. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25156. */
  25157. _this.dumpNextRenderTargets = false;
  25158. /**
  25159. * The list of user defined render targets added to the scene
  25160. */
  25161. _this.customRenderTargets = new Array();
  25162. /**
  25163. * Gets the list of meshes imported to the scene through SceneLoader
  25164. */
  25165. _this.importedMeshesFiles = new Array();
  25166. // Probes
  25167. /**
  25168. * Gets or sets a boolean indicating if probes are enabled on this scene
  25169. */
  25170. _this.probesEnabled = true;
  25171. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25172. // Procedural textures
  25173. /**
  25174. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25175. */
  25176. _this.proceduralTexturesEnabled = true;
  25177. // Performance counters
  25178. _this._totalVertices = new BABYLON.PerfCounter();
  25179. /** @hidden */
  25180. _this._activeIndices = new BABYLON.PerfCounter();
  25181. /** @hidden */
  25182. _this._activeParticles = new BABYLON.PerfCounter();
  25183. /** @hidden */
  25184. _this._activeBones = new BABYLON.PerfCounter();
  25185. _this._animationTime = 0;
  25186. /**
  25187. * Gets or sets a general scale for animation speed
  25188. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25189. */
  25190. _this.animationTimeScale = 1;
  25191. _this._renderId = 0;
  25192. _this._frameId = 0;
  25193. _this._executeWhenReadyTimeoutId = -1;
  25194. _this._intermediateRendering = false;
  25195. _this._viewUpdateFlag = -1;
  25196. _this._projectionUpdateFlag = -1;
  25197. _this._alternateViewUpdateFlag = -1;
  25198. _this._alternateProjectionUpdateFlag = -1;
  25199. /** @hidden */
  25200. _this._toBeDisposed = new Array(256);
  25201. _this._activeRequests = new Array();
  25202. _this._pendingData = new Array();
  25203. _this._isDisposed = false;
  25204. /**
  25205. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25206. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25207. */
  25208. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25209. _this._activeMeshes = new BABYLON.SmartArray(256);
  25210. _this._processedMaterials = new BABYLON.SmartArray(256);
  25211. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25212. /** @hidden */
  25213. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25214. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25215. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25216. /** @hidden */
  25217. _this._activeAnimatables = new Array();
  25218. _this._transformMatrix = BABYLON.Matrix.Zero();
  25219. _this._useAlternateCameraConfiguration = false;
  25220. _this._alternateRendering = false;
  25221. /**
  25222. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25223. * This is useful if there are more lights that the maximum simulteanous authorized
  25224. */
  25225. _this.requireLightSorting = false;
  25226. /**
  25227. * @hidden
  25228. * Backing store of defined scene components.
  25229. */
  25230. _this._components = [];
  25231. /**
  25232. * @hidden
  25233. * Backing store of defined scene components.
  25234. */
  25235. _this._serializableComponents = [];
  25236. /**
  25237. * List of components to register on the next registration step.
  25238. */
  25239. _this._transientComponents = [];
  25240. /**
  25241. * @hidden
  25242. * Defines the actions happening before camera updates.
  25243. */
  25244. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25245. /**
  25246. * @hidden
  25247. * Defines the actions happening before clear the canvas.
  25248. */
  25249. _this._beforeClearStage = BABYLON.Stage.Create();
  25250. /**
  25251. * @hidden
  25252. * Defines the actions when collecting render targets for the frame.
  25253. */
  25254. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25255. /**
  25256. * @hidden
  25257. * Defines the actions happening for one camera in the frame.
  25258. */
  25259. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25260. /**
  25261. * @hidden
  25262. * Defines the actions happening during the per mesh ready checks.
  25263. */
  25264. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25265. /**
  25266. * @hidden
  25267. * Defines the actions happening before evaluate active mesh checks.
  25268. */
  25269. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25270. /**
  25271. * @hidden
  25272. * Defines the actions happening during the evaluate sub mesh checks.
  25273. */
  25274. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25275. /**
  25276. * @hidden
  25277. * Defines the actions happening during the active mesh stage.
  25278. */
  25279. _this._activeMeshStage = BABYLON.Stage.Create();
  25280. /**
  25281. * @hidden
  25282. * Defines the actions happening during the per camera render target step.
  25283. */
  25284. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25285. /**
  25286. * @hidden
  25287. * Defines the actions happening just before the active camera is drawing.
  25288. */
  25289. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25290. /**
  25291. * @hidden
  25292. * Defines the actions happening just before a rendering group is drawing.
  25293. */
  25294. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25295. /**
  25296. * @hidden
  25297. * Defines the actions happening just before a mesh is drawing.
  25298. */
  25299. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25300. /**
  25301. * @hidden
  25302. * Defines the actions happening just after a mesh has been drawn.
  25303. */
  25304. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25305. /**
  25306. * @hidden
  25307. * Defines the actions happening just after a rendering group has been drawn.
  25308. */
  25309. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25310. /**
  25311. * @hidden
  25312. * Defines the actions happening just after the active camera has been drawn.
  25313. */
  25314. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25315. /**
  25316. * @hidden
  25317. * Defines the actions happening just after rendering all cameras and computing intersections.
  25318. */
  25319. _this._afterRenderStage = BABYLON.Stage.Create();
  25320. /**
  25321. * @hidden
  25322. * Defines the actions happening when a pointer move event happens.
  25323. */
  25324. _this._pointerMoveStage = BABYLON.Stage.Create();
  25325. /**
  25326. * @hidden
  25327. * Defines the actions happening when a pointer down event happens.
  25328. */
  25329. _this._pointerDownStage = BABYLON.Stage.Create();
  25330. /**
  25331. * @hidden
  25332. * Defines the actions happening when a pointer up event happens.
  25333. */
  25334. _this._pointerUpStage = BABYLON.Stage.Create();
  25335. _this._defaultMeshCandidates = {
  25336. data: [],
  25337. length: 0
  25338. };
  25339. _this._defaultSubMeshCandidates = {
  25340. data: [],
  25341. length: 0
  25342. };
  25343. _this._activeMeshesFrozen = false;
  25344. /** @hidden */
  25345. _this._allowPostProcessClearColor = true;
  25346. /**
  25347. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25348. */
  25349. _this.getDeterministicFrameTime = function () {
  25350. return 1000.0 / 60.0; // frame time in ms
  25351. };
  25352. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25353. _this._blockMaterialDirtyMechanism = false;
  25354. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25355. _this._engine.scenes.push(_this);
  25356. _this._uid = null;
  25357. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25358. if (BABYLON.PostProcessManager) {
  25359. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25360. }
  25361. if (BABYLON.Tools.IsWindowObjectExist()) {
  25362. _this.attachControl();
  25363. }
  25364. //collision coordinator initialization. For now legacy per default.
  25365. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25366. // Uniform Buffer
  25367. _this._createUbo();
  25368. // Default Image processing definition
  25369. if (BABYLON.ImageProcessingConfiguration) {
  25370. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25371. }
  25372. _this.setDefaultCandidateProviders();
  25373. return _this;
  25374. }
  25375. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25376. /**
  25377. * Texture used in all pbr material as the reflection texture.
  25378. * As in the majority of the scene they are the same (exception for multi room and so on),
  25379. * this is easier to reference from here than from all the materials.
  25380. */
  25381. get: function () {
  25382. return this._environmentTexture;
  25383. },
  25384. /**
  25385. * Texture used in all pbr material as the reflection texture.
  25386. * As in the majority of the scene they are the same (exception for multi room and so on),
  25387. * this is easier to set here than in all the materials.
  25388. */
  25389. set: function (value) {
  25390. if (this._environmentTexture === value) {
  25391. return;
  25392. }
  25393. this._environmentTexture = value;
  25394. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25395. },
  25396. enumerable: true,
  25397. configurable: true
  25398. });
  25399. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25400. /**
  25401. * Default image processing configuration used either in the rendering
  25402. * Forward main pass or through the imageProcessingPostProcess if present.
  25403. * As in the majority of the scene they are the same (exception for multi camera),
  25404. * this is easier to reference from here than from all the materials and post process.
  25405. *
  25406. * No setter as we it is a shared configuration, you can set the values instead.
  25407. */
  25408. get: function () {
  25409. return this._imageProcessingConfiguration;
  25410. },
  25411. enumerable: true,
  25412. configurable: true
  25413. });
  25414. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25415. get: function () {
  25416. return this._forceWireframe;
  25417. },
  25418. /**
  25419. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25420. */
  25421. set: function (value) {
  25422. if (this._forceWireframe === value) {
  25423. return;
  25424. }
  25425. this._forceWireframe = value;
  25426. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25427. },
  25428. enumerable: true,
  25429. configurable: true
  25430. });
  25431. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25432. get: function () {
  25433. return this._forcePointsCloud;
  25434. },
  25435. /**
  25436. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25437. */
  25438. set: function (value) {
  25439. if (this._forcePointsCloud === value) {
  25440. return;
  25441. }
  25442. this._forcePointsCloud = value;
  25443. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25444. },
  25445. enumerable: true,
  25446. configurable: true
  25447. });
  25448. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25449. /**
  25450. * Gets or sets the animation properties override
  25451. */
  25452. get: function () {
  25453. return this._animationPropertiesOverride;
  25454. },
  25455. set: function (value) {
  25456. this._animationPropertiesOverride = value;
  25457. },
  25458. enumerable: true,
  25459. configurable: true
  25460. });
  25461. Object.defineProperty(Scene.prototype, "onDispose", {
  25462. /** Sets a function to be executed when this scene is disposed. */
  25463. set: function (callback) {
  25464. if (this._onDisposeObserver) {
  25465. this.onDisposeObservable.remove(this._onDisposeObserver);
  25466. }
  25467. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25468. },
  25469. enumerable: true,
  25470. configurable: true
  25471. });
  25472. Object.defineProperty(Scene.prototype, "beforeRender", {
  25473. /** Sets a function to be executed before rendering this scene */
  25474. set: function (callback) {
  25475. if (this._onBeforeRenderObserver) {
  25476. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25477. }
  25478. if (callback) {
  25479. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25480. }
  25481. },
  25482. enumerable: true,
  25483. configurable: true
  25484. });
  25485. Object.defineProperty(Scene.prototype, "afterRender", {
  25486. /** Sets a function to be executed after rendering this scene */
  25487. set: function (callback) {
  25488. if (this._onAfterRenderObserver) {
  25489. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25490. }
  25491. if (callback) {
  25492. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25493. }
  25494. },
  25495. enumerable: true,
  25496. configurable: true
  25497. });
  25498. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25499. /** Sets a function to be executed before rendering a camera*/
  25500. set: function (callback) {
  25501. if (this._onBeforeCameraRenderObserver) {
  25502. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25503. }
  25504. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25505. },
  25506. enumerable: true,
  25507. configurable: true
  25508. });
  25509. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25510. /** Sets a function to be executed after rendering a camera*/
  25511. set: function (callback) {
  25512. if (this._onAfterCameraRenderObserver) {
  25513. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25514. }
  25515. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25521. /**
  25522. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25523. */
  25524. get: function () {
  25525. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25526. },
  25527. enumerable: true,
  25528. configurable: true
  25529. });
  25530. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25531. get: function () {
  25532. return this._useRightHandedSystem;
  25533. },
  25534. /**
  25535. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25536. */
  25537. set: function (value) {
  25538. if (this._useRightHandedSystem === value) {
  25539. return;
  25540. }
  25541. this._useRightHandedSystem = value;
  25542. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25543. },
  25544. enumerable: true,
  25545. configurable: true
  25546. });
  25547. /**
  25548. * Sets the step Id used by deterministic lock step
  25549. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25550. * @param newStepId defines the step Id
  25551. */
  25552. Scene.prototype.setStepId = function (newStepId) {
  25553. this._currentStepId = newStepId;
  25554. };
  25555. ;
  25556. /**
  25557. * Gets the step Id used by deterministic lock step
  25558. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25559. * @returns the step Id
  25560. */
  25561. Scene.prototype.getStepId = function () {
  25562. return this._currentStepId;
  25563. };
  25564. ;
  25565. /**
  25566. * Gets the internal step used by deterministic lock step
  25567. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25568. * @returns the internal step
  25569. */
  25570. Scene.prototype.getInternalStep = function () {
  25571. return this._currentInternalStep;
  25572. };
  25573. ;
  25574. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25575. get: function () {
  25576. return this._fogEnabled;
  25577. },
  25578. /**
  25579. * Gets or sets a boolean indicating if fog is enabled on this scene
  25580. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25581. * (Default is true)
  25582. */
  25583. set: function (value) {
  25584. if (this._fogEnabled === value) {
  25585. return;
  25586. }
  25587. this._fogEnabled = value;
  25588. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25589. },
  25590. enumerable: true,
  25591. configurable: true
  25592. });
  25593. Object.defineProperty(Scene.prototype, "fogMode", {
  25594. get: function () {
  25595. return this._fogMode;
  25596. },
  25597. /**
  25598. * Gets or sets the fog mode to use
  25599. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25600. * | mode | value |
  25601. * | --- | --- |
  25602. * | FOGMODE_NONE | 0 |
  25603. * | FOGMODE_EXP | 1 |
  25604. * | FOGMODE_EXP2 | 2 |
  25605. * | FOGMODE_LINEAR | 3 |
  25606. */
  25607. set: function (value) {
  25608. if (this._fogMode === value) {
  25609. return;
  25610. }
  25611. this._fogMode = value;
  25612. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25613. },
  25614. enumerable: true,
  25615. configurable: true
  25616. });
  25617. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25618. get: function () {
  25619. return this._shadowsEnabled;
  25620. },
  25621. /**
  25622. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25623. */
  25624. set: function (value) {
  25625. if (this._shadowsEnabled === value) {
  25626. return;
  25627. }
  25628. this._shadowsEnabled = value;
  25629. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25635. get: function () {
  25636. return this._lightsEnabled;
  25637. },
  25638. /**
  25639. * Gets or sets a boolean indicating if lights are enabled on this scene
  25640. */
  25641. set: function (value) {
  25642. if (this._lightsEnabled === value) {
  25643. return;
  25644. }
  25645. this._lightsEnabled = value;
  25646. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25647. },
  25648. enumerable: true,
  25649. configurable: true
  25650. });
  25651. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25652. /** The default material used on meshes when no material is affected */
  25653. get: function () {
  25654. if (!this._defaultMaterial) {
  25655. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25656. }
  25657. return this._defaultMaterial;
  25658. },
  25659. /** The default material used on meshes when no material is affected */
  25660. set: function (value) {
  25661. this._defaultMaterial = value;
  25662. },
  25663. enumerable: true,
  25664. configurable: true
  25665. });
  25666. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25667. get: function () {
  25668. return this._texturesEnabled;
  25669. },
  25670. /**
  25671. * Gets or sets a boolean indicating if textures are enabled on this scene
  25672. */
  25673. set: function (value) {
  25674. if (this._texturesEnabled === value) {
  25675. return;
  25676. }
  25677. this._texturesEnabled = value;
  25678. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25679. },
  25680. enumerable: true,
  25681. configurable: true
  25682. });
  25683. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25684. get: function () {
  25685. return this._skeletonsEnabled;
  25686. },
  25687. /**
  25688. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25689. */
  25690. set: function (value) {
  25691. if (this._skeletonsEnabled === value) {
  25692. return;
  25693. }
  25694. this._skeletonsEnabled = value;
  25695. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25696. },
  25697. enumerable: true,
  25698. configurable: true
  25699. });
  25700. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25701. /** @hidden */
  25702. get: function () {
  25703. return this._alternateRendering;
  25704. },
  25705. enumerable: true,
  25706. configurable: true
  25707. });
  25708. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25709. /**
  25710. * Gets the list of frustum planes (built from the active camera)
  25711. */
  25712. get: function () {
  25713. return this._frustumPlanes;
  25714. },
  25715. enumerable: true,
  25716. configurable: true
  25717. });
  25718. /**
  25719. * Registers the transient components if needed.
  25720. */
  25721. Scene.prototype._registerTransientComponents = function () {
  25722. // Register components that have been associated lately to the scene.
  25723. if (this._transientComponents.length > 0) {
  25724. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25725. var component = _a[_i];
  25726. component.register();
  25727. }
  25728. this._transientComponents = [];
  25729. }
  25730. };
  25731. /**
  25732. * @hidden
  25733. * Add a component to the scene.
  25734. * Note that the ccomponent could be registered on th next frame if this is called after
  25735. * the register component stage.
  25736. * @param component Defines the component to add to the scene
  25737. */
  25738. Scene.prototype._addComponent = function (component) {
  25739. this._components.push(component);
  25740. this._transientComponents.push(component);
  25741. var serializableComponent = component;
  25742. if (serializableComponent.addFromContainer) {
  25743. this._serializableComponents.push(serializableComponent);
  25744. }
  25745. };
  25746. /**
  25747. * @hidden
  25748. * Gets a component from the scene.
  25749. * @param name defines the name of the component to retrieve
  25750. * @returns the component or null if not present
  25751. */
  25752. Scene.prototype._getComponent = function (name) {
  25753. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25754. var component = _a[_i];
  25755. if (component.name === name) {
  25756. return component;
  25757. }
  25758. }
  25759. return null;
  25760. };
  25761. /**
  25762. * @hidden
  25763. */
  25764. Scene.prototype._getDefaultMeshCandidates = function () {
  25765. this._defaultMeshCandidates.data = this.meshes;
  25766. this._defaultMeshCandidates.length = this.meshes.length;
  25767. return this._defaultMeshCandidates;
  25768. };
  25769. /**
  25770. * @hidden
  25771. */
  25772. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25773. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25774. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25775. return this._defaultSubMeshCandidates;
  25776. };
  25777. /**
  25778. * Sets the default candidate providers for the scene.
  25779. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25780. * and getCollidingSubMeshCandidates to their default function
  25781. */
  25782. Scene.prototype.setDefaultCandidateProviders = function () {
  25783. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25784. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25785. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25786. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25787. };
  25788. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25789. /**
  25790. * Gets a boolean indicating if collisions are processed on a web worker
  25791. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25792. */
  25793. get: function () {
  25794. return this._workerCollisions;
  25795. },
  25796. set: function (enabled) {
  25797. if (!BABYLON.CollisionCoordinatorLegacy) {
  25798. return;
  25799. }
  25800. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25801. this._workerCollisions = enabled;
  25802. if (this.collisionCoordinator) {
  25803. this.collisionCoordinator.destroy();
  25804. }
  25805. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25806. this.collisionCoordinator.init(this);
  25807. },
  25808. enumerable: true,
  25809. configurable: true
  25810. });
  25811. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25812. /**
  25813. * Gets the mesh that is currently under the pointer
  25814. */
  25815. get: function () {
  25816. return this._pointerOverMesh;
  25817. },
  25818. enumerable: true,
  25819. configurable: true
  25820. });
  25821. Object.defineProperty(Scene.prototype, "pointerX", {
  25822. /**
  25823. * Gets the current on-screen X position of the pointer
  25824. */
  25825. get: function () {
  25826. return this._pointerX;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(Scene.prototype, "pointerY", {
  25832. /**
  25833. * Gets the current on-screen Y position of the pointer
  25834. */
  25835. get: function () {
  25836. return this._pointerY;
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. /**
  25842. * Gets the cached material (ie. the latest rendered one)
  25843. * @returns the cached material
  25844. */
  25845. Scene.prototype.getCachedMaterial = function () {
  25846. return this._cachedMaterial;
  25847. };
  25848. /**
  25849. * Gets the cached effect (ie. the latest rendered one)
  25850. * @returns the cached effect
  25851. */
  25852. Scene.prototype.getCachedEffect = function () {
  25853. return this._cachedEffect;
  25854. };
  25855. /**
  25856. * Gets the cached visibility state (ie. the latest rendered one)
  25857. * @returns the cached visibility state
  25858. */
  25859. Scene.prototype.getCachedVisibility = function () {
  25860. return this._cachedVisibility;
  25861. };
  25862. /**
  25863. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25864. * @param material defines the current material
  25865. * @param effect defines the current effect
  25866. * @param visibility defines the current visibility state
  25867. * @returns true if one parameter is not cached
  25868. */
  25869. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25870. if (visibility === void 0) { visibility = 1; }
  25871. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25872. };
  25873. /**
  25874. * Gets the engine associated with the scene
  25875. * @returns an Engine
  25876. */
  25877. Scene.prototype.getEngine = function () {
  25878. return this._engine;
  25879. };
  25880. /**
  25881. * Gets the total number of vertices rendered per frame
  25882. * @returns the total number of vertices rendered per frame
  25883. */
  25884. Scene.prototype.getTotalVertices = function () {
  25885. return this._totalVertices.current;
  25886. };
  25887. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25888. /**
  25889. * Gets the performance counter for total vertices
  25890. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25891. */
  25892. get: function () {
  25893. return this._totalVertices;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. /**
  25899. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25900. * @returns the total number of active indices rendered per frame
  25901. */
  25902. Scene.prototype.getActiveIndices = function () {
  25903. return this._activeIndices.current;
  25904. };
  25905. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25906. /**
  25907. * Gets the performance counter for active indices
  25908. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25909. */
  25910. get: function () {
  25911. return this._activeIndices;
  25912. },
  25913. enumerable: true,
  25914. configurable: true
  25915. });
  25916. /**
  25917. * Gets the total number of active particles rendered per frame
  25918. * @returns the total number of active particles rendered per frame
  25919. */
  25920. Scene.prototype.getActiveParticles = function () {
  25921. return this._activeParticles.current;
  25922. };
  25923. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25924. /**
  25925. * Gets the performance counter for active particles
  25926. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25927. */
  25928. get: function () {
  25929. return this._activeParticles;
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. /**
  25935. * Gets the total number of active bones rendered per frame
  25936. * @returns the total number of active bones rendered per frame
  25937. */
  25938. Scene.prototype.getActiveBones = function () {
  25939. return this._activeBones.current;
  25940. };
  25941. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25942. /**
  25943. * Gets the performance counter for active bones
  25944. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25945. */
  25946. get: function () {
  25947. return this._activeBones;
  25948. },
  25949. enumerable: true,
  25950. configurable: true
  25951. });
  25952. /** @hidden */
  25953. Scene.prototype.getInterFramePerfCounter = function () {
  25954. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25955. return 0;
  25956. };
  25957. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25958. /** @hidden */
  25959. get: function () {
  25960. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25961. return null;
  25962. },
  25963. enumerable: true,
  25964. configurable: true
  25965. });
  25966. /** @hidden */
  25967. Scene.prototype.getLastFrameDuration = function () {
  25968. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25969. return 0;
  25970. };
  25971. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25972. /** @hidden */
  25973. get: function () {
  25974. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25975. return null;
  25976. },
  25977. enumerable: true,
  25978. configurable: true
  25979. });
  25980. /** @hidden */
  25981. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25982. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25983. return 0;
  25984. };
  25985. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25986. /** @hidden */
  25987. get: function () {
  25988. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25989. return null;
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. /**
  25995. * Gets the array of active meshes
  25996. * @returns an array of AbstractMesh
  25997. */
  25998. Scene.prototype.getActiveMeshes = function () {
  25999. return this._activeMeshes;
  26000. };
  26001. /** @hidden */
  26002. Scene.prototype.getRenderTargetsDuration = function () {
  26003. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26004. return 0;
  26005. };
  26006. /** @hidden */
  26007. Scene.prototype.getRenderDuration = function () {
  26008. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26009. return 0;
  26010. };
  26011. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26012. /** @hidden */
  26013. get: function () {
  26014. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26015. return null;
  26016. },
  26017. enumerable: true,
  26018. configurable: true
  26019. });
  26020. /** @hidden */
  26021. Scene.prototype.getParticlesDuration = function () {
  26022. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26023. return 0;
  26024. };
  26025. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26026. /** @hidden */
  26027. get: function () {
  26028. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26029. return null;
  26030. },
  26031. enumerable: true,
  26032. configurable: true
  26033. });
  26034. /** @hidden */
  26035. Scene.prototype.getSpritesDuration = function () {
  26036. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26037. return 0;
  26038. };
  26039. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26040. /** @hidden */
  26041. get: function () {
  26042. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26043. return null;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. /**
  26049. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26050. * @returns a number
  26051. */
  26052. Scene.prototype.getAnimationRatio = function () {
  26053. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26054. };
  26055. /**
  26056. * Gets an unique Id for the current render phase
  26057. * @returns a number
  26058. */
  26059. Scene.prototype.getRenderId = function () {
  26060. return this._renderId;
  26061. };
  26062. /**
  26063. * Gets an unique Id for the current frame
  26064. * @returns a number
  26065. */
  26066. Scene.prototype.getFrameId = function () {
  26067. return this._frameId;
  26068. };
  26069. /** Call this function if you want to manually increment the render Id*/
  26070. Scene.prototype.incrementRenderId = function () {
  26071. this._renderId++;
  26072. };
  26073. Scene.prototype._updatePointerPosition = function (evt) {
  26074. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26075. if (!canvasRect) {
  26076. return;
  26077. }
  26078. this._pointerX = evt.clientX - canvasRect.left;
  26079. this._pointerY = evt.clientY - canvasRect.top;
  26080. this._unTranslatedPointerX = this._pointerX;
  26081. this._unTranslatedPointerY = this._pointerY;
  26082. };
  26083. Scene.prototype._createUbo = function () {
  26084. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26085. this._sceneUbo.addUniform("viewProjection", 16);
  26086. this._sceneUbo.addUniform("view", 16);
  26087. };
  26088. Scene.prototype._createAlternateUbo = function () {
  26089. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26090. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26091. this._alternateSceneUbo.addUniform("view", 16);
  26092. };
  26093. // Pointers handling
  26094. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26095. if (pointerInfo.pickInfo) {
  26096. if (!pointerInfo.pickInfo.ray) {
  26097. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26098. }
  26099. }
  26100. };
  26101. /**
  26102. * Use this method to simulate a pointer move on a mesh
  26103. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26104. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26105. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26106. * @returns the current scene
  26107. */
  26108. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26109. var evt = new PointerEvent("pointermove", pointerEventInit);
  26110. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26111. return this;
  26112. }
  26113. return this._processPointerMove(pickResult, evt);
  26114. };
  26115. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26116. var canvas = this._engine.getRenderingCanvas();
  26117. if (!canvas) {
  26118. return this;
  26119. }
  26120. // Restore pointer
  26121. canvas.style.cursor = this.defaultCursor;
  26122. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26123. if (isMeshPicked) {
  26124. this.setPointerOverMesh(pickResult.pickedMesh);
  26125. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26126. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26127. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26128. }
  26129. else {
  26130. canvas.style.cursor = this.hoverCursor;
  26131. }
  26132. }
  26133. }
  26134. else {
  26135. this.setPointerOverMesh(null);
  26136. }
  26137. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26138. var step = _a[_i];
  26139. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26140. }
  26141. if (pickResult) {
  26142. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26143. if (this.onPointerMove) {
  26144. this.onPointerMove(evt, pickResult, type);
  26145. }
  26146. if (this.onPointerObservable.hasObservers()) {
  26147. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26148. this._setRayOnPointerInfo(pi);
  26149. this.onPointerObservable.notifyObservers(pi, type);
  26150. }
  26151. }
  26152. return this;
  26153. };
  26154. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26155. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26156. if (pickResult) {
  26157. pi.ray = pickResult.ray;
  26158. }
  26159. this.onPrePointerObservable.notifyObservers(pi, type);
  26160. if (pi.skipOnPointerObservable) {
  26161. return true;
  26162. }
  26163. else {
  26164. return false;
  26165. }
  26166. };
  26167. /**
  26168. * Use this method to simulate a pointer down on a mesh
  26169. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26170. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26171. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26172. * @returns the current scene
  26173. */
  26174. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26175. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26176. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26177. return this;
  26178. }
  26179. return this._processPointerDown(pickResult, evt);
  26180. };
  26181. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26182. var _this = this;
  26183. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26184. this._pickedDownMesh = pickResult.pickedMesh;
  26185. var actionManager = pickResult.pickedMesh.actionManager;
  26186. if (actionManager) {
  26187. if (actionManager.hasPickTriggers) {
  26188. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26189. switch (evt.button) {
  26190. case 0:
  26191. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26192. break;
  26193. case 1:
  26194. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26195. break;
  26196. case 2:
  26197. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26198. break;
  26199. }
  26200. }
  26201. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26202. window.setTimeout(function () {
  26203. 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);
  26204. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26205. if (_this._totalPointersPressed !== 0 &&
  26206. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26207. !_this._isPointerSwiping()) {
  26208. _this._startingPointerTime = 0;
  26209. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26210. }
  26211. }
  26212. }, Scene.LongPressDelay);
  26213. }
  26214. }
  26215. }
  26216. else {
  26217. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26218. var step = _a[_i];
  26219. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26220. }
  26221. }
  26222. if (pickResult) {
  26223. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26224. if (this.onPointerDown) {
  26225. this.onPointerDown(evt, pickResult, type);
  26226. }
  26227. if (this.onPointerObservable.hasObservers()) {
  26228. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26229. this._setRayOnPointerInfo(pi);
  26230. this.onPointerObservable.notifyObservers(pi, type);
  26231. }
  26232. }
  26233. return this;
  26234. };
  26235. /**
  26236. * Use this method to simulate a pointer up on a mesh
  26237. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26238. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26239. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26240. * @returns the current scene
  26241. */
  26242. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26243. var evt = new PointerEvent("pointerup", pointerEventInit);
  26244. var clickInfo = new ClickInfo();
  26245. clickInfo.singleClick = true;
  26246. clickInfo.ignore = true;
  26247. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26248. return this;
  26249. }
  26250. return this._processPointerUp(pickResult, evt, clickInfo);
  26251. };
  26252. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26253. if (pickResult && pickResult && pickResult.pickedMesh) {
  26254. this._pickedUpMesh = pickResult.pickedMesh;
  26255. if (this._pickedDownMesh === this._pickedUpMesh) {
  26256. if (this.onPointerPick) {
  26257. this.onPointerPick(evt, pickResult);
  26258. }
  26259. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26260. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26261. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26262. this._setRayOnPointerInfo(pi);
  26263. this.onPointerObservable.notifyObservers(pi, type_1);
  26264. }
  26265. }
  26266. if (pickResult.pickedMesh.actionManager) {
  26267. if (clickInfo.ignore) {
  26268. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26269. }
  26270. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26271. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26272. }
  26273. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26274. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26275. }
  26276. }
  26277. }
  26278. else {
  26279. if (!clickInfo.ignore) {
  26280. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26281. var step = _a[_i];
  26282. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26283. }
  26284. }
  26285. }
  26286. if (this._pickedDownMesh &&
  26287. this._pickedDownMesh.actionManager &&
  26288. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26289. this._pickedDownMesh !== this._pickedUpMesh) {
  26290. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26291. }
  26292. var type = BABYLON.PointerEventTypes.POINTERUP;
  26293. if (this.onPointerObservable.hasObservers()) {
  26294. if (!clickInfo.ignore) {
  26295. if (!clickInfo.hasSwiped) {
  26296. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26297. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26298. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26299. this._setRayOnPointerInfo(pi);
  26300. this.onPointerObservable.notifyObservers(pi, type_2);
  26301. }
  26302. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26303. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26304. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26305. this._setRayOnPointerInfo(pi);
  26306. this.onPointerObservable.notifyObservers(pi, type_3);
  26307. }
  26308. }
  26309. }
  26310. else {
  26311. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26312. this._setRayOnPointerInfo(pi);
  26313. this.onPointerObservable.notifyObservers(pi, type);
  26314. }
  26315. }
  26316. if (this.onPointerUp) {
  26317. this.onPointerUp(evt, pickResult, type);
  26318. }
  26319. return this;
  26320. };
  26321. /**
  26322. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26323. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26324. * @returns true if the pointer was captured
  26325. */
  26326. Scene.prototype.isPointerCaptured = function (pointerId) {
  26327. if (pointerId === void 0) { pointerId = 0; }
  26328. return this._pointerCaptures[pointerId];
  26329. };
  26330. /** @hidden */
  26331. Scene.prototype._isPointerSwiping = function () {
  26332. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26333. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26334. };
  26335. /**
  26336. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26337. * @param attachUp defines if you want to attach events to pointerup
  26338. * @param attachDown defines if you want to attach events to pointerdown
  26339. * @param attachMove defines if you want to attach events to pointermove
  26340. */
  26341. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26342. var _this = this;
  26343. if (attachUp === void 0) { attachUp = true; }
  26344. if (attachDown === void 0) { attachDown = true; }
  26345. if (attachMove === void 0) { attachMove = true; }
  26346. this._initActionManager = function (act, clickInfo) {
  26347. if (!_this._meshPickProceed) {
  26348. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26349. _this._currentPickResult = pickResult;
  26350. if (pickResult) {
  26351. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26352. }
  26353. _this._meshPickProceed = true;
  26354. }
  26355. return act;
  26356. };
  26357. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26358. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26359. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26360. btn !== _this._previousButtonPressed) {
  26361. _this._doubleClickOccured = false;
  26362. clickInfo.singleClick = true;
  26363. clickInfo.ignore = false;
  26364. cb(clickInfo, _this._currentPickResult);
  26365. }
  26366. };
  26367. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26368. var clickInfo = new ClickInfo();
  26369. _this._currentPickResult = null;
  26370. var act = null;
  26371. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26372. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26373. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26374. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26375. act = _this._initActionManager(act, clickInfo);
  26376. if (act)
  26377. checkPicking = act.hasPickTriggers;
  26378. }
  26379. if (checkPicking) {
  26380. var btn = evt.button;
  26381. clickInfo.hasSwiped = _this._isPointerSwiping();
  26382. if (!clickInfo.hasSwiped) {
  26383. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26384. if (!checkSingleClickImmediately) {
  26385. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26386. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26387. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26388. act = _this._initActionManager(act, clickInfo);
  26389. if (act)
  26390. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26391. }
  26392. }
  26393. if (checkSingleClickImmediately) {
  26394. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26395. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26396. btn !== _this._previousButtonPressed) {
  26397. clickInfo.singleClick = true;
  26398. cb(clickInfo, _this._currentPickResult);
  26399. }
  26400. }
  26401. // at least one double click is required to be check and exclusive double click is enabled
  26402. else {
  26403. // wait that no double click has been raised during the double click delay
  26404. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26405. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26406. }
  26407. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26408. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26409. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26410. act = _this._initActionManager(act, clickInfo);
  26411. if (act)
  26412. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26413. }
  26414. if (checkDoubleClick) {
  26415. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26416. if (btn === _this._previousButtonPressed &&
  26417. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26418. !_this._doubleClickOccured) {
  26419. // pointer has not moved for 2 clicks, it's a double click
  26420. if (!clickInfo.hasSwiped &&
  26421. !_this._isPointerSwiping()) {
  26422. _this._previousStartingPointerTime = 0;
  26423. _this._doubleClickOccured = true;
  26424. clickInfo.doubleClick = true;
  26425. clickInfo.ignore = false;
  26426. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26427. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26428. }
  26429. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26430. cb(clickInfo, _this._currentPickResult);
  26431. }
  26432. // if the two successive clicks are too far, it's just two simple clicks
  26433. else {
  26434. _this._doubleClickOccured = false;
  26435. _this._previousStartingPointerTime = _this._startingPointerTime;
  26436. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26437. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26438. _this._previousButtonPressed = btn;
  26439. if (Scene.ExclusiveDoubleClickMode) {
  26440. if (_this._previousDelayedSimpleClickTimeout) {
  26441. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26442. }
  26443. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26444. cb(clickInfo, _this._previousPickResult);
  26445. }
  26446. else {
  26447. cb(clickInfo, _this._currentPickResult);
  26448. }
  26449. }
  26450. }
  26451. // just the first click of the double has been raised
  26452. else {
  26453. _this._doubleClickOccured = false;
  26454. _this._previousStartingPointerTime = _this._startingPointerTime;
  26455. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26456. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26457. _this._previousButtonPressed = btn;
  26458. }
  26459. }
  26460. }
  26461. }
  26462. clickInfo.ignore = true;
  26463. cb(clickInfo, _this._currentPickResult);
  26464. };
  26465. this._onPointerMove = function (evt) {
  26466. _this._updatePointerPosition(evt);
  26467. // PreObservable support
  26468. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26469. return;
  26470. }
  26471. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26472. return;
  26473. }
  26474. if (!_this.pointerMovePredicate) {
  26475. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26476. }
  26477. // Meshes
  26478. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26479. _this._processPointerMove(pickResult, evt);
  26480. };
  26481. this._onPointerDown = function (evt) {
  26482. _this._totalPointersPressed++;
  26483. _this._pickedDownMesh = null;
  26484. _this._meshPickProceed = false;
  26485. _this._updatePointerPosition(evt);
  26486. if (_this.preventDefaultOnPointerDown && canvas) {
  26487. evt.preventDefault();
  26488. canvas.focus();
  26489. }
  26490. // PreObservable support
  26491. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26492. return;
  26493. }
  26494. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26495. return;
  26496. }
  26497. _this._pointerCaptures[evt.pointerId] = true;
  26498. _this._startingPointerPosition.x = _this._pointerX;
  26499. _this._startingPointerPosition.y = _this._pointerY;
  26500. _this._startingPointerTime = Date.now();
  26501. if (!_this.pointerDownPredicate) {
  26502. _this.pointerDownPredicate = function (mesh) {
  26503. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26504. };
  26505. }
  26506. // Meshes
  26507. _this._pickedDownMesh = null;
  26508. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26509. _this._processPointerDown(pickResult, evt);
  26510. };
  26511. this._onPointerUp = function (evt) {
  26512. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26513. return; // So we need to test it the pointer down was pressed before.
  26514. }
  26515. _this._totalPointersPressed--;
  26516. _this._pickedUpMesh = null;
  26517. _this._meshPickProceed = false;
  26518. _this._updatePointerPosition(evt);
  26519. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26520. // PreObservable support
  26521. if (_this.onPrePointerObservable.hasObservers()) {
  26522. if (!clickInfo.ignore) {
  26523. if (!clickInfo.hasSwiped) {
  26524. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26525. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26526. return;
  26527. }
  26528. }
  26529. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26530. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26531. return;
  26532. }
  26533. }
  26534. }
  26535. }
  26536. else {
  26537. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26538. return;
  26539. }
  26540. }
  26541. }
  26542. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26543. return;
  26544. }
  26545. _this._pointerCaptures[evt.pointerId] = false;
  26546. if (!_this.pointerUpPredicate) {
  26547. _this.pointerUpPredicate = function (mesh) {
  26548. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26549. };
  26550. }
  26551. // Meshes
  26552. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26553. _this._initActionManager(null, clickInfo);
  26554. }
  26555. if (!pickResult) {
  26556. pickResult = _this._currentPickResult;
  26557. }
  26558. _this._processPointerUp(pickResult, evt, clickInfo);
  26559. _this._previousPickResult = _this._currentPickResult;
  26560. });
  26561. };
  26562. this._onKeyDown = function (evt) {
  26563. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26564. if (_this.onPreKeyboardObservable.hasObservers()) {
  26565. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26566. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26567. if (pi.skipOnPointerObservable) {
  26568. return;
  26569. }
  26570. }
  26571. if (_this.onKeyboardObservable.hasObservers()) {
  26572. var pi = new BABYLON.KeyboardInfo(type, evt);
  26573. _this.onKeyboardObservable.notifyObservers(pi, type);
  26574. }
  26575. if (_this.actionManager) {
  26576. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26577. }
  26578. };
  26579. this._onKeyUp = function (evt) {
  26580. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26581. if (_this.onPreKeyboardObservable.hasObservers()) {
  26582. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26583. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26584. if (pi.skipOnPointerObservable) {
  26585. return;
  26586. }
  26587. }
  26588. if (_this.onKeyboardObservable.hasObservers()) {
  26589. var pi = new BABYLON.KeyboardInfo(type, evt);
  26590. _this.onKeyboardObservable.notifyObservers(pi, type);
  26591. }
  26592. if (_this.actionManager) {
  26593. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26594. }
  26595. };
  26596. var engine = this.getEngine();
  26597. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26598. if (!canvas) {
  26599. return;
  26600. }
  26601. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26602. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26603. });
  26604. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26605. if (!canvas) {
  26606. return;
  26607. }
  26608. canvas.removeEventListener("keydown", _this._onKeyDown);
  26609. canvas.removeEventListener("keyup", _this._onKeyUp);
  26610. });
  26611. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26612. var canvas = this._engine.getRenderingCanvas();
  26613. if (!canvas) {
  26614. return;
  26615. }
  26616. if (attachMove) {
  26617. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26618. // Wheel
  26619. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26620. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26621. }
  26622. if (attachDown) {
  26623. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26624. }
  26625. if (attachUp) {
  26626. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26627. }
  26628. canvas.tabIndex = 1;
  26629. };
  26630. /** Detaches all event handlers*/
  26631. Scene.prototype.detachControl = function () {
  26632. var engine = this.getEngine();
  26633. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26634. var canvas = engine.getRenderingCanvas();
  26635. if (!canvas) {
  26636. return;
  26637. }
  26638. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26639. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26640. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26641. if (this._onCanvasBlurObserver) {
  26642. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26643. }
  26644. if (this._onCanvasFocusObserver) {
  26645. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26646. }
  26647. // Wheel
  26648. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26649. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26650. // Keyboard
  26651. canvas.removeEventListener("keydown", this._onKeyDown);
  26652. canvas.removeEventListener("keyup", this._onKeyUp);
  26653. // Observables
  26654. this.onKeyboardObservable.clear();
  26655. this.onPreKeyboardObservable.clear();
  26656. this.onPointerObservable.clear();
  26657. this.onPrePointerObservable.clear();
  26658. };
  26659. /**
  26660. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26661. * Delay loaded resources are not taking in account
  26662. * @return true if all required resources are ready
  26663. */
  26664. Scene.prototype.isReady = function () {
  26665. if (this._isDisposed) {
  26666. return false;
  26667. }
  26668. if (this._pendingData.length > 0) {
  26669. return false;
  26670. }
  26671. var index;
  26672. var engine = this.getEngine();
  26673. // Geometries
  26674. for (index = 0; index < this.geometries.length; index++) {
  26675. var geometry = this.geometries[index];
  26676. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26677. return false;
  26678. }
  26679. }
  26680. // Meshes
  26681. for (index = 0; index < this.meshes.length; index++) {
  26682. var mesh = this.meshes[index];
  26683. if (!mesh.isEnabled()) {
  26684. continue;
  26685. }
  26686. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26687. continue;
  26688. }
  26689. if (!mesh.isReady(true)) {
  26690. return false;
  26691. }
  26692. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26693. // Is Ready For Mesh
  26694. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26695. var step = _a[_i];
  26696. if (!step.action(mesh, hardwareInstancedRendering)) {
  26697. return false;
  26698. }
  26699. }
  26700. }
  26701. // Post-processes
  26702. if (this.activeCameras && this.activeCameras.length > 0) {
  26703. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26704. var camera = _c[_b];
  26705. if (!camera.isReady(true)) {
  26706. return false;
  26707. }
  26708. }
  26709. }
  26710. else if (this.activeCamera) {
  26711. if (!this.activeCamera.isReady(true)) {
  26712. return false;
  26713. }
  26714. }
  26715. // Particles
  26716. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26717. var particleSystem = _e[_d];
  26718. if (!particleSystem.isReady()) {
  26719. return false;
  26720. }
  26721. }
  26722. return true;
  26723. };
  26724. /** Resets all cached information relative to material (including effect and visibility) */
  26725. Scene.prototype.resetCachedMaterial = function () {
  26726. this._cachedMaterial = null;
  26727. this._cachedEffect = null;
  26728. this._cachedVisibility = null;
  26729. };
  26730. /**
  26731. * Registers a function to be called before every frame render
  26732. * @param func defines the function to register
  26733. */
  26734. Scene.prototype.registerBeforeRender = function (func) {
  26735. this.onBeforeRenderObservable.add(func);
  26736. };
  26737. /**
  26738. * Unregisters a function called before every frame render
  26739. * @param func defines the function to unregister
  26740. */
  26741. Scene.prototype.unregisterBeforeRender = function (func) {
  26742. this.onBeforeRenderObservable.removeCallback(func);
  26743. };
  26744. /**
  26745. * Registers a function to be called after every frame render
  26746. * @param func defines the function to register
  26747. */
  26748. Scene.prototype.registerAfterRender = function (func) {
  26749. this.onAfterRenderObservable.add(func);
  26750. };
  26751. /**
  26752. * Unregisters a function called after every frame render
  26753. * @param func defines the function to unregister
  26754. */
  26755. Scene.prototype.unregisterAfterRender = function (func) {
  26756. this.onAfterRenderObservable.removeCallback(func);
  26757. };
  26758. Scene.prototype._executeOnceBeforeRender = function (func) {
  26759. var _this = this;
  26760. var execFunc = function () {
  26761. func();
  26762. setTimeout(function () {
  26763. _this.unregisterBeforeRender(execFunc);
  26764. });
  26765. };
  26766. this.registerBeforeRender(execFunc);
  26767. };
  26768. /**
  26769. * The provided function will run before render once and will be disposed afterwards.
  26770. * A timeout delay can be provided so that the function will be executed in N ms.
  26771. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26772. * @param func The function to be executed.
  26773. * @param timeout optional delay in ms
  26774. */
  26775. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26776. var _this = this;
  26777. if (timeout !== undefined) {
  26778. setTimeout(function () {
  26779. _this._executeOnceBeforeRender(func);
  26780. }, timeout);
  26781. }
  26782. else {
  26783. this._executeOnceBeforeRender(func);
  26784. }
  26785. };
  26786. /** @hidden */
  26787. Scene.prototype._addPendingData = function (data) {
  26788. this._pendingData.push(data);
  26789. };
  26790. /** @hidden */
  26791. Scene.prototype._removePendingData = function (data) {
  26792. var wasLoading = this.isLoading;
  26793. var index = this._pendingData.indexOf(data);
  26794. if (index !== -1) {
  26795. this._pendingData.splice(index, 1);
  26796. }
  26797. if (wasLoading && !this.isLoading) {
  26798. this.onDataLoadedObservable.notifyObservers(this);
  26799. }
  26800. };
  26801. /**
  26802. * Returns the number of items waiting to be loaded
  26803. * @returns the number of items waiting to be loaded
  26804. */
  26805. Scene.prototype.getWaitingItemsCount = function () {
  26806. return this._pendingData.length;
  26807. };
  26808. Object.defineProperty(Scene.prototype, "isLoading", {
  26809. /**
  26810. * Returns a boolean indicating if the scene is still loading data
  26811. */
  26812. get: function () {
  26813. return this._pendingData.length > 0;
  26814. },
  26815. enumerable: true,
  26816. configurable: true
  26817. });
  26818. /**
  26819. * Registers a function to be executed when the scene is ready
  26820. * @param {Function} func - the function to be executed
  26821. */
  26822. Scene.prototype.executeWhenReady = function (func) {
  26823. var _this = this;
  26824. this.onReadyObservable.add(func);
  26825. if (this._executeWhenReadyTimeoutId !== -1) {
  26826. return;
  26827. }
  26828. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26829. _this._checkIsReady();
  26830. }, 150);
  26831. };
  26832. /**
  26833. * Returns a promise that resolves when the scene is ready
  26834. * @returns A promise that resolves when the scene is ready
  26835. */
  26836. Scene.prototype.whenReadyAsync = function () {
  26837. var _this = this;
  26838. return new Promise(function (resolve) {
  26839. _this.executeWhenReady(function () {
  26840. resolve();
  26841. });
  26842. });
  26843. };
  26844. /** @hidden */
  26845. Scene.prototype._checkIsReady = function () {
  26846. var _this = this;
  26847. this._registerTransientComponents();
  26848. if (this.isReady()) {
  26849. this.onReadyObservable.notifyObservers(this);
  26850. this.onReadyObservable.clear();
  26851. this._executeWhenReadyTimeoutId = -1;
  26852. return;
  26853. }
  26854. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26855. _this._checkIsReady();
  26856. }, 150);
  26857. };
  26858. // Animations
  26859. /**
  26860. * Will start the animation sequence of a given target
  26861. * @param target defines the target
  26862. * @param from defines from which frame should animation start
  26863. * @param to defines until which frame should animation run.
  26864. * @param weight defines the weight to apply to the animation (1.0 by default)
  26865. * @param loop defines if the animation loops
  26866. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26867. * @param onAnimationEnd defines the function to be executed when the animation ends
  26868. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26869. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26870. * @returns the animatable object created for this animation
  26871. */
  26872. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26873. if (weight === void 0) { weight = 1.0; }
  26874. if (speedRatio === void 0) { speedRatio = 1.0; }
  26875. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26876. returnedAnimatable.weight = weight;
  26877. return returnedAnimatable;
  26878. };
  26879. /**
  26880. * Will start the animation sequence of a given target
  26881. * @param target defines the target
  26882. * @param from defines from which frame should animation start
  26883. * @param to defines until which frame should animation run.
  26884. * @param loop defines if the animation loops
  26885. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26886. * @param onAnimationEnd defines the function to be executed when the animation ends
  26887. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26888. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26889. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26890. * @returns the animatable object created for this animation
  26891. */
  26892. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26893. if (speedRatio === void 0) { speedRatio = 1.0; }
  26894. if (stopCurrent === void 0) { stopCurrent = true; }
  26895. if (from > to && speedRatio > 0) {
  26896. speedRatio *= -1;
  26897. }
  26898. if (stopCurrent) {
  26899. this.stopAnimation(target, undefined, targetMask);
  26900. }
  26901. if (!animatable) {
  26902. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26903. }
  26904. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26905. // Local animations
  26906. if (target.animations && shouldRunTargetAnimations) {
  26907. animatable.appendAnimations(target, target.animations);
  26908. }
  26909. // Children animations
  26910. if (target.getAnimatables) {
  26911. var animatables = target.getAnimatables();
  26912. for (var index = 0; index < animatables.length; index++) {
  26913. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26914. }
  26915. }
  26916. animatable.reset();
  26917. return animatable;
  26918. };
  26919. /**
  26920. * Begin a new animation on a given node
  26921. * @param target defines the target where the animation will take place
  26922. * @param animations defines the list of animations to start
  26923. * @param from defines the initial value
  26924. * @param to defines the final value
  26925. * @param loop defines if you want animation to loop (off by default)
  26926. * @param speedRatio defines the speed ratio to apply to all animations
  26927. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26928. * @returns the list of created animatables
  26929. */
  26930. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26931. if (speedRatio === undefined) {
  26932. speedRatio = 1.0;
  26933. }
  26934. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26935. return animatable;
  26936. };
  26937. /**
  26938. * Begin a new animation on a given node and its hierarchy
  26939. * @param target defines the root node where the animation will take place
  26940. * @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.
  26941. * @param animations defines the list of animations to start
  26942. * @param from defines the initial value
  26943. * @param to defines the final value
  26944. * @param loop defines if you want animation to loop (off by default)
  26945. * @param speedRatio defines the speed ratio to apply to all animations
  26946. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26947. * @returns the list of animatables created for all nodes
  26948. */
  26949. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26950. var children = target.getDescendants(directDescendantsOnly);
  26951. var result = [];
  26952. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26953. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26954. var child = children_1[_i];
  26955. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26956. }
  26957. return result;
  26958. };
  26959. /**
  26960. * Gets the animatable associated with a specific target
  26961. * @param target defines the target of the animatable
  26962. * @returns the required animatable if found
  26963. */
  26964. Scene.prototype.getAnimatableByTarget = function (target) {
  26965. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26966. if (this._activeAnimatables[index].target === target) {
  26967. return this._activeAnimatables[index];
  26968. }
  26969. }
  26970. return null;
  26971. };
  26972. /**
  26973. * Gets all animatables associated with a given target
  26974. * @param target defines the target to look animatables for
  26975. * @returns an array of Animatables
  26976. */
  26977. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26978. var result = [];
  26979. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26980. if (this._activeAnimatables[index].target === target) {
  26981. result.push(this._activeAnimatables[index]);
  26982. }
  26983. }
  26984. return result;
  26985. };
  26986. Object.defineProperty(Scene.prototype, "animatables", {
  26987. /**
  26988. * Gets all animatable attached to the scene
  26989. */
  26990. get: function () {
  26991. return this._activeAnimatables;
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. /**
  26997. * Will stop the animation of the given target
  26998. * @param target - the target
  26999. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27000. * @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)
  27001. */
  27002. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27003. var animatables = this.getAllAnimatablesByTarget(target);
  27004. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27005. var animatable = animatables_1[_i];
  27006. animatable.stop(animationName, targetMask);
  27007. }
  27008. };
  27009. /**
  27010. * Stops and removes all animations that have been applied to the scene
  27011. */
  27012. Scene.prototype.stopAllAnimations = function () {
  27013. if (this._activeAnimatables) {
  27014. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27015. this._activeAnimatables[i].stop();
  27016. }
  27017. this._activeAnimatables = [];
  27018. }
  27019. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27020. var group = _a[_i];
  27021. group.stop();
  27022. }
  27023. };
  27024. Scene.prototype._animate = function () {
  27025. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27026. return;
  27027. }
  27028. // Getting time
  27029. var now = BABYLON.Tools.Now;
  27030. if (!this._animationTimeLast) {
  27031. if (this._pendingData.length > 0) {
  27032. return;
  27033. }
  27034. this._animationTimeLast = now;
  27035. }
  27036. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27037. this._animationTime += deltaTime;
  27038. this._animationTimeLast = now;
  27039. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27040. this._activeAnimatables[index]._animate(this._animationTime);
  27041. }
  27042. // Late animation bindings
  27043. this._processLateAnimationBindings();
  27044. };
  27045. /** @hidden */
  27046. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27047. var target = runtimeAnimation.target;
  27048. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27049. if (!target._lateAnimationHolders) {
  27050. target._lateAnimationHolders = {};
  27051. }
  27052. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27053. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27054. totalWeight: 0,
  27055. animations: [],
  27056. originalValue: originalValue
  27057. };
  27058. }
  27059. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27060. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27061. };
  27062. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27063. var normalizer = 1.0;
  27064. var finalPosition = BABYLON.Tmp.Vector3[0];
  27065. var finalScaling = BABYLON.Tmp.Vector3[1];
  27066. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27067. var startIndex = 0;
  27068. var originalAnimation = holder.animations[0];
  27069. var originalValue = holder.originalValue;
  27070. var scale = 1;
  27071. if (holder.totalWeight < 1.0) {
  27072. // We need to mix the original value in
  27073. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27074. scale = 1.0 - holder.totalWeight;
  27075. }
  27076. else {
  27077. startIndex = 1;
  27078. // We need to normalize the weights
  27079. normalizer = holder.totalWeight;
  27080. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27081. scale = originalAnimation.weight / normalizer;
  27082. if (scale == 1) {
  27083. return originalAnimation.currentValue;
  27084. }
  27085. }
  27086. finalScaling.scaleInPlace(scale);
  27087. finalPosition.scaleInPlace(scale);
  27088. finalQuaternion.scaleInPlace(scale);
  27089. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27090. var runtimeAnimation = holder.animations[animIndex];
  27091. var scale = runtimeAnimation.weight / normalizer;
  27092. var currentPosition = BABYLON.Tmp.Vector3[2];
  27093. var currentScaling = BABYLON.Tmp.Vector3[3];
  27094. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27095. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27096. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27097. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27098. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27099. }
  27100. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27101. return originalAnimation._workValue;
  27102. };
  27103. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27104. var originalAnimation = holder.animations[0];
  27105. var originalValue = holder.originalValue;
  27106. if (holder.animations.length === 1) {
  27107. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27108. return refQuaternion;
  27109. }
  27110. var normalizer = 1.0;
  27111. var quaternions;
  27112. var weights;
  27113. if (holder.totalWeight < 1.0) {
  27114. var scale = 1.0 - holder.totalWeight;
  27115. quaternions = [];
  27116. weights = [];
  27117. quaternions.push(originalValue);
  27118. weights.push(scale);
  27119. }
  27120. else {
  27121. if (holder.animations.length === 2) { // Slerp as soon as we can
  27122. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27123. return refQuaternion;
  27124. }
  27125. quaternions = [];
  27126. weights = [];
  27127. normalizer = holder.totalWeight;
  27128. }
  27129. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27130. var runtimeAnimation = holder.animations[animIndex];
  27131. quaternions.push(runtimeAnimation.currentValue);
  27132. weights.push(runtimeAnimation.weight / normalizer);
  27133. }
  27134. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27135. var cumulativeAmount = 0;
  27136. var cumulativeQuaternion = null;
  27137. for (var index = 0; index < quaternions.length;) {
  27138. if (!cumulativeQuaternion) {
  27139. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27140. cumulativeQuaternion = refQuaternion;
  27141. cumulativeAmount = weights[index] + weights[index + 1];
  27142. index += 2;
  27143. continue;
  27144. }
  27145. cumulativeAmount += weights[index];
  27146. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27147. index++;
  27148. }
  27149. return cumulativeQuaternion;
  27150. };
  27151. Scene.prototype._processLateAnimationBindings = function () {
  27152. if (!this._registeredForLateAnimationBindings.length) {
  27153. return;
  27154. }
  27155. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27156. var target = this._registeredForLateAnimationBindings.data[index];
  27157. for (var path in target._lateAnimationHolders) {
  27158. var holder = target._lateAnimationHolders[path];
  27159. var originalAnimation = holder.animations[0];
  27160. var originalValue = holder.originalValue;
  27161. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27162. var finalValue = target[path];
  27163. if (matrixDecomposeMode) {
  27164. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27165. }
  27166. else {
  27167. var quaternionMode = originalValue.w !== undefined;
  27168. if (quaternionMode) {
  27169. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27170. }
  27171. else {
  27172. var startIndex = 0;
  27173. var normalizer = 1.0;
  27174. if (holder.totalWeight < 1.0) {
  27175. // We need to mix the original value in
  27176. if (originalValue.scale) {
  27177. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27178. }
  27179. else {
  27180. finalValue = originalValue * (1.0 - holder.totalWeight);
  27181. }
  27182. }
  27183. else {
  27184. // We need to normalize the weights
  27185. normalizer = holder.totalWeight;
  27186. var scale_1 = originalAnimation.weight / normalizer;
  27187. if (scale_1 !== 1) {
  27188. if (originalAnimation.currentValue.scale) {
  27189. finalValue = originalAnimation.currentValue.scale(scale_1);
  27190. }
  27191. else {
  27192. finalValue = originalAnimation.currentValue * scale_1;
  27193. }
  27194. }
  27195. else {
  27196. finalValue = originalAnimation.currentValue;
  27197. }
  27198. startIndex = 1;
  27199. }
  27200. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27201. var runtimeAnimation = holder.animations[animIndex];
  27202. var scale = runtimeAnimation.weight / normalizer;
  27203. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27204. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27205. }
  27206. else {
  27207. finalValue += runtimeAnimation.currentValue * scale;
  27208. }
  27209. }
  27210. }
  27211. }
  27212. target[path] = finalValue;
  27213. }
  27214. target._lateAnimationHolders = {};
  27215. }
  27216. this._registeredForLateAnimationBindings.reset();
  27217. };
  27218. // Matrix
  27219. /** @hidden */
  27220. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27221. this._useAlternateCameraConfiguration = active;
  27222. };
  27223. /**
  27224. * Gets the current view matrix
  27225. * @returns a Matrix
  27226. */
  27227. Scene.prototype.getViewMatrix = function () {
  27228. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27229. };
  27230. /**
  27231. * Gets the current projection matrix
  27232. * @returns a Matrix
  27233. */
  27234. Scene.prototype.getProjectionMatrix = function () {
  27235. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27236. };
  27237. /**
  27238. * Gets the current transform matrix
  27239. * @returns a Matrix made of View * Projection
  27240. */
  27241. Scene.prototype.getTransformMatrix = function () {
  27242. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27243. };
  27244. /**
  27245. * Sets the current transform matrix
  27246. * @param view defines the View matrix to use
  27247. * @param projection defines the Projection matrix to use
  27248. */
  27249. Scene.prototype.setTransformMatrix = function (view, projection) {
  27250. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27251. return;
  27252. }
  27253. this._viewUpdateFlag = view.updateFlag;
  27254. this._projectionUpdateFlag = projection.updateFlag;
  27255. this._viewMatrix = view;
  27256. this._projectionMatrix = projection;
  27257. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27258. // Update frustum
  27259. if (!this._frustumPlanes) {
  27260. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27261. }
  27262. else {
  27263. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27264. }
  27265. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27266. var otherCamera = this.activeCamera._alternateCamera;
  27267. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27268. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27269. }
  27270. if (this._sceneUbo.useUbo) {
  27271. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27272. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27273. this._sceneUbo.update();
  27274. }
  27275. };
  27276. /** @hidden */
  27277. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27278. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27279. return;
  27280. }
  27281. this._alternateViewUpdateFlag = view.updateFlag;
  27282. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27283. this._alternateViewMatrix = view;
  27284. this._alternateProjectionMatrix = projection;
  27285. if (!this._alternateTransformMatrix) {
  27286. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27287. }
  27288. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27289. if (!this._alternateSceneUbo) {
  27290. this._createAlternateUbo();
  27291. }
  27292. if (this._alternateSceneUbo.useUbo) {
  27293. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27294. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27295. this._alternateSceneUbo.update();
  27296. }
  27297. };
  27298. /**
  27299. * Gets the uniform buffer used to store scene data
  27300. * @returns a UniformBuffer
  27301. */
  27302. Scene.prototype.getSceneUniformBuffer = function () {
  27303. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27304. };
  27305. /**
  27306. * Gets an unique (relatively to the current scene) Id
  27307. * @returns an unique number for the scene
  27308. */
  27309. Scene.prototype.getUniqueId = function () {
  27310. var result = Scene._uniqueIdCounter;
  27311. Scene._uniqueIdCounter++;
  27312. return result;
  27313. };
  27314. /**
  27315. * Add a mesh to the list of scene's meshes
  27316. * @param newMesh defines the mesh to add
  27317. * @param recursive if all child meshes should also be added to the scene
  27318. */
  27319. Scene.prototype.addMesh = function (newMesh, recursive) {
  27320. var _this = this;
  27321. if (recursive === void 0) { recursive = false; }
  27322. this.meshes.push(newMesh);
  27323. //notify the collision coordinator
  27324. if (this.collisionCoordinator) {
  27325. this.collisionCoordinator.onMeshAdded(newMesh);
  27326. }
  27327. newMesh._resyncLightSources();
  27328. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27329. if (recursive) {
  27330. newMesh.getChildMeshes().forEach(function (m) {
  27331. _this.addMesh(m);
  27332. });
  27333. }
  27334. };
  27335. /**
  27336. * Remove a mesh for the list of scene's meshes
  27337. * @param toRemove defines the mesh to remove
  27338. * @param recursive if all child meshes should also be removed from the scene
  27339. * @returns the index where the mesh was in the mesh list
  27340. */
  27341. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27342. var _this = this;
  27343. if (recursive === void 0) { recursive = false; }
  27344. var index = this.meshes.indexOf(toRemove);
  27345. if (index !== -1) {
  27346. // Remove from the scene if mesh found
  27347. this.meshes.splice(index, 1);
  27348. }
  27349. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27350. if (recursive) {
  27351. toRemove.getChildMeshes().forEach(function (m) {
  27352. _this.removeMesh(m);
  27353. });
  27354. }
  27355. return index;
  27356. };
  27357. /**
  27358. * Add a transform node to the list of scene's transform nodes
  27359. * @param newTransformNode defines the transform node to add
  27360. */
  27361. Scene.prototype.addTransformNode = function (newTransformNode) {
  27362. this.transformNodes.push(newTransformNode);
  27363. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27364. };
  27365. /**
  27366. * Remove a transform node for the list of scene's transform nodes
  27367. * @param toRemove defines the transform node to remove
  27368. * @returns the index where the transform node was in the transform node list
  27369. */
  27370. Scene.prototype.removeTransformNode = function (toRemove) {
  27371. var index = this.transformNodes.indexOf(toRemove);
  27372. if (index !== -1) {
  27373. // Remove from the scene if found
  27374. this.transformNodes.splice(index, 1);
  27375. }
  27376. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27377. return index;
  27378. };
  27379. /**
  27380. * Remove a skeleton for the list of scene's skeletons
  27381. * @param toRemove defines the skeleton to remove
  27382. * @returns the index where the skeleton was in the skeleton list
  27383. */
  27384. Scene.prototype.removeSkeleton = function (toRemove) {
  27385. var index = this.skeletons.indexOf(toRemove);
  27386. if (index !== -1) {
  27387. // Remove from the scene if found
  27388. this.skeletons.splice(index, 1);
  27389. }
  27390. return index;
  27391. };
  27392. /**
  27393. * Remove a morph target for the list of scene's morph targets
  27394. * @param toRemove defines the morph target to remove
  27395. * @returns the index where the morph target was in the morph target list
  27396. */
  27397. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27398. var index = this.morphTargetManagers.indexOf(toRemove);
  27399. if (index !== -1) {
  27400. // Remove from the scene if found
  27401. this.morphTargetManagers.splice(index, 1);
  27402. }
  27403. return index;
  27404. };
  27405. /**
  27406. * Remove a light for the list of scene's lights
  27407. * @param toRemove defines the light to remove
  27408. * @returns the index where the light was in the light list
  27409. */
  27410. Scene.prototype.removeLight = function (toRemove) {
  27411. var index = this.lights.indexOf(toRemove);
  27412. if (index !== -1) {
  27413. // Remove from meshes
  27414. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27415. var mesh = _a[_i];
  27416. mesh._removeLightSource(toRemove);
  27417. }
  27418. // Remove from the scene if mesh found
  27419. this.lights.splice(index, 1);
  27420. this.sortLightsByPriority();
  27421. }
  27422. this.onLightRemovedObservable.notifyObservers(toRemove);
  27423. return index;
  27424. };
  27425. /**
  27426. * Remove a camera for the list of scene's cameras
  27427. * @param toRemove defines the camera to remove
  27428. * @returns the index where the camera was in the camera list
  27429. */
  27430. Scene.prototype.removeCamera = function (toRemove) {
  27431. var index = this.cameras.indexOf(toRemove);
  27432. if (index !== -1) {
  27433. // Remove from the scene if mesh found
  27434. this.cameras.splice(index, 1);
  27435. }
  27436. // Remove from activeCameras
  27437. var index2 = this.activeCameras.indexOf(toRemove);
  27438. if (index2 !== -1) {
  27439. // Remove from the scene if mesh found
  27440. this.activeCameras.splice(index2, 1);
  27441. }
  27442. // Reset the activeCamera
  27443. if (this.activeCamera === toRemove) {
  27444. if (this.cameras.length > 0) {
  27445. this.activeCamera = this.cameras[0];
  27446. }
  27447. else {
  27448. this.activeCamera = null;
  27449. }
  27450. }
  27451. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27452. return index;
  27453. };
  27454. /**
  27455. * Remove a particle system for the list of scene's particle systems
  27456. * @param toRemove defines the particle system to remove
  27457. * @returns the index where the particle system was in the particle system list
  27458. */
  27459. Scene.prototype.removeParticleSystem = function (toRemove) {
  27460. var index = this.particleSystems.indexOf(toRemove);
  27461. if (index !== -1) {
  27462. this.particleSystems.splice(index, 1);
  27463. }
  27464. return index;
  27465. };
  27466. /**
  27467. * Remove a animation for the list of scene's animations
  27468. * @param toRemove defines the animation to remove
  27469. * @returns the index where the animation was in the animation list
  27470. */
  27471. Scene.prototype.removeAnimation = function (toRemove) {
  27472. var index = this.animations.indexOf(toRemove);
  27473. if (index !== -1) {
  27474. this.animations.splice(index, 1);
  27475. }
  27476. return index;
  27477. };
  27478. /**
  27479. * Removes the given animation group from this scene.
  27480. * @param toRemove The animation group to remove
  27481. * @returns The index of the removed animation group
  27482. */
  27483. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27484. var index = this.animationGroups.indexOf(toRemove);
  27485. if (index !== -1) {
  27486. this.animationGroups.splice(index, 1);
  27487. }
  27488. return index;
  27489. };
  27490. /**
  27491. * Removes the given multi-material from this scene.
  27492. * @param toRemove The multi-material to remove
  27493. * @returns The index of the removed multi-material
  27494. */
  27495. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27496. var index = this.multiMaterials.indexOf(toRemove);
  27497. if (index !== -1) {
  27498. this.multiMaterials.splice(index, 1);
  27499. }
  27500. return index;
  27501. };
  27502. /**
  27503. * Removes the given material from this scene.
  27504. * @param toRemove The material to remove
  27505. * @returns The index of the removed material
  27506. */
  27507. Scene.prototype.removeMaterial = function (toRemove) {
  27508. var index = this.materials.indexOf(toRemove);
  27509. if (index !== -1) {
  27510. this.materials.splice(index, 1);
  27511. }
  27512. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27513. return index;
  27514. };
  27515. /**
  27516. * Removes the given action manager from this scene.
  27517. * @param toRemove The action manager to remove
  27518. * @returns The index of the removed action manager
  27519. */
  27520. Scene.prototype.removeActionManager = function (toRemove) {
  27521. var index = this.actionManagers.indexOf(toRemove);
  27522. if (index !== -1) {
  27523. this.actionManagers.splice(index, 1);
  27524. }
  27525. return index;
  27526. };
  27527. /**
  27528. * Removes the given texture from this scene.
  27529. * @param toRemove The texture to remove
  27530. * @returns The index of the removed texture
  27531. */
  27532. Scene.prototype.removeTexture = function (toRemove) {
  27533. var index = this.textures.indexOf(toRemove);
  27534. if (index !== -1) {
  27535. this.textures.splice(index, 1);
  27536. }
  27537. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27538. return index;
  27539. };
  27540. /**
  27541. * Adds the given light to this scene
  27542. * @param newLight The light to add
  27543. */
  27544. Scene.prototype.addLight = function (newLight) {
  27545. this.lights.push(newLight);
  27546. this.sortLightsByPriority();
  27547. // Add light to all meshes (To support if the light is removed and then readded)
  27548. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27549. var mesh = _a[_i];
  27550. if (mesh._lightSources.indexOf(newLight) === -1) {
  27551. mesh._lightSources.push(newLight);
  27552. mesh._resyncLightSources();
  27553. }
  27554. }
  27555. this.onNewLightAddedObservable.notifyObservers(newLight);
  27556. };
  27557. /**
  27558. * Sorts the list list based on light priorities
  27559. */
  27560. Scene.prototype.sortLightsByPriority = function () {
  27561. if (this.requireLightSorting) {
  27562. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27563. }
  27564. };
  27565. /**
  27566. * Adds the given camera to this scene
  27567. * @param newCamera The camera to add
  27568. */
  27569. Scene.prototype.addCamera = function (newCamera) {
  27570. this.cameras.push(newCamera);
  27571. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27572. };
  27573. /**
  27574. * Adds the given skeleton to this scene
  27575. * @param newSkeleton The skeleton to add
  27576. */
  27577. Scene.prototype.addSkeleton = function (newSkeleton) {
  27578. this.skeletons.push(newSkeleton);
  27579. };
  27580. /**
  27581. * Adds the given particle system to this scene
  27582. * @param newParticleSystem The particle system to add
  27583. */
  27584. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27585. this.particleSystems.push(newParticleSystem);
  27586. };
  27587. /**
  27588. * Adds the given animation to this scene
  27589. * @param newAnimation The animation to add
  27590. */
  27591. Scene.prototype.addAnimation = function (newAnimation) {
  27592. this.animations.push(newAnimation);
  27593. };
  27594. /**
  27595. * Adds the given animation group to this scene.
  27596. * @param newAnimationGroup The animation group to add
  27597. */
  27598. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27599. this.animationGroups.push(newAnimationGroup);
  27600. };
  27601. /**
  27602. * Adds the given multi-material to this scene
  27603. * @param newMultiMaterial The multi-material to add
  27604. */
  27605. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27606. this.multiMaterials.push(newMultiMaterial);
  27607. };
  27608. /**
  27609. * Adds the given material to this scene
  27610. * @param newMaterial The material to add
  27611. */
  27612. Scene.prototype.addMaterial = function (newMaterial) {
  27613. this.materials.push(newMaterial);
  27614. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27615. };
  27616. /**
  27617. * Adds the given morph target to this scene
  27618. * @param newMorphTargetManager The morph target to add
  27619. */
  27620. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27621. this.morphTargetManagers.push(newMorphTargetManager);
  27622. };
  27623. /**
  27624. * Adds the given geometry to this scene
  27625. * @param newGeometry The geometry to add
  27626. */
  27627. Scene.prototype.addGeometry = function (newGeometry) {
  27628. this.geometries.push(newGeometry);
  27629. };
  27630. /**
  27631. * Adds the given action manager to this scene
  27632. * @param newActionManager The action manager to add
  27633. */
  27634. Scene.prototype.addActionManager = function (newActionManager) {
  27635. this.actionManagers.push(newActionManager);
  27636. };
  27637. /**
  27638. * Adds the given texture to this scene.
  27639. * @param newTexture The texture to add
  27640. */
  27641. Scene.prototype.addTexture = function (newTexture) {
  27642. this.textures.push(newTexture);
  27643. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27644. };
  27645. /**
  27646. * Switch active camera
  27647. * @param newCamera defines the new active camera
  27648. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27649. */
  27650. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27651. if (attachControl === void 0) { attachControl = true; }
  27652. var canvas = this._engine.getRenderingCanvas();
  27653. if (!canvas) {
  27654. return;
  27655. }
  27656. if (this.activeCamera) {
  27657. this.activeCamera.detachControl(canvas);
  27658. }
  27659. this.activeCamera = newCamera;
  27660. if (attachControl) {
  27661. newCamera.attachControl(canvas);
  27662. }
  27663. };
  27664. /**
  27665. * sets the active camera of the scene using its ID
  27666. * @param id defines the camera's ID
  27667. * @return the new active camera or null if none found.
  27668. */
  27669. Scene.prototype.setActiveCameraByID = function (id) {
  27670. var camera = this.getCameraByID(id);
  27671. if (camera) {
  27672. this.activeCamera = camera;
  27673. return camera;
  27674. }
  27675. return null;
  27676. };
  27677. /**
  27678. * sets the active camera of the scene using its name
  27679. * @param name defines the camera's name
  27680. * @returns the new active camera or null if none found.
  27681. */
  27682. Scene.prototype.setActiveCameraByName = function (name) {
  27683. var camera = this.getCameraByName(name);
  27684. if (camera) {
  27685. this.activeCamera = camera;
  27686. return camera;
  27687. }
  27688. return null;
  27689. };
  27690. /**
  27691. * get an animation group using its name
  27692. * @param name defines the material's name
  27693. * @return the animation group or null if none found.
  27694. */
  27695. Scene.prototype.getAnimationGroupByName = function (name) {
  27696. for (var index = 0; index < this.animationGroups.length; index++) {
  27697. if (this.animationGroups[index].name === name) {
  27698. return this.animationGroups[index];
  27699. }
  27700. }
  27701. return null;
  27702. };
  27703. /**
  27704. * get a material using its id
  27705. * @param id defines the material's ID
  27706. * @return the material or null if none found.
  27707. */
  27708. Scene.prototype.getMaterialByID = function (id) {
  27709. for (var index = 0; index < this.materials.length; index++) {
  27710. if (this.materials[index].id === id) {
  27711. return this.materials[index];
  27712. }
  27713. }
  27714. return null;
  27715. };
  27716. /**
  27717. * Gets a material using its name
  27718. * @param name defines the material's name
  27719. * @return the material or null if none found.
  27720. */
  27721. Scene.prototype.getMaterialByName = function (name) {
  27722. for (var index = 0; index < this.materials.length; index++) {
  27723. if (this.materials[index].name === name) {
  27724. return this.materials[index];
  27725. }
  27726. }
  27727. return null;
  27728. };
  27729. /**
  27730. * Gets a camera using its id
  27731. * @param id defines the id to look for
  27732. * @returns the camera or null if not found
  27733. */
  27734. Scene.prototype.getCameraByID = function (id) {
  27735. for (var index = 0; index < this.cameras.length; index++) {
  27736. if (this.cameras[index].id === id) {
  27737. return this.cameras[index];
  27738. }
  27739. }
  27740. return null;
  27741. };
  27742. /**
  27743. * Gets a camera using its unique id
  27744. * @param uniqueId defines the unique id to look for
  27745. * @returns the camera or null if not found
  27746. */
  27747. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27748. for (var index = 0; index < this.cameras.length; index++) {
  27749. if (this.cameras[index].uniqueId === uniqueId) {
  27750. return this.cameras[index];
  27751. }
  27752. }
  27753. return null;
  27754. };
  27755. /**
  27756. * Gets a camera using its name
  27757. * @param name defines the camera's name
  27758. * @return the camera or null if none found.
  27759. */
  27760. Scene.prototype.getCameraByName = function (name) {
  27761. for (var index = 0; index < this.cameras.length; index++) {
  27762. if (this.cameras[index].name === name) {
  27763. return this.cameras[index];
  27764. }
  27765. }
  27766. return null;
  27767. };
  27768. /**
  27769. * Gets a bone using its id
  27770. * @param id defines the bone's id
  27771. * @return the bone or null if not found
  27772. */
  27773. Scene.prototype.getBoneByID = function (id) {
  27774. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27775. var skeleton = this.skeletons[skeletonIndex];
  27776. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27777. if (skeleton.bones[boneIndex].id === id) {
  27778. return skeleton.bones[boneIndex];
  27779. }
  27780. }
  27781. }
  27782. return null;
  27783. };
  27784. /**
  27785. * Gets a bone using its id
  27786. * @param name defines the bone's name
  27787. * @return the bone or null if not found
  27788. */
  27789. Scene.prototype.getBoneByName = function (name) {
  27790. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27791. var skeleton = this.skeletons[skeletonIndex];
  27792. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27793. if (skeleton.bones[boneIndex].name === name) {
  27794. return skeleton.bones[boneIndex];
  27795. }
  27796. }
  27797. }
  27798. return null;
  27799. };
  27800. /**
  27801. * Gets a light node using its name
  27802. * @param name defines the the light's name
  27803. * @return the light or null if none found.
  27804. */
  27805. Scene.prototype.getLightByName = function (name) {
  27806. for (var index = 0; index < this.lights.length; index++) {
  27807. if (this.lights[index].name === name) {
  27808. return this.lights[index];
  27809. }
  27810. }
  27811. return null;
  27812. };
  27813. /**
  27814. * Gets a light node using its id
  27815. * @param id defines the light's id
  27816. * @return the light or null if none found.
  27817. */
  27818. Scene.prototype.getLightByID = function (id) {
  27819. for (var index = 0; index < this.lights.length; index++) {
  27820. if (this.lights[index].id === id) {
  27821. return this.lights[index];
  27822. }
  27823. }
  27824. return null;
  27825. };
  27826. /**
  27827. * Gets a light node using its scene-generated unique ID
  27828. * @param uniqueId defines the light's unique id
  27829. * @return the light or null if none found.
  27830. */
  27831. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27832. for (var index = 0; index < this.lights.length; index++) {
  27833. if (this.lights[index].uniqueId === uniqueId) {
  27834. return this.lights[index];
  27835. }
  27836. }
  27837. return null;
  27838. };
  27839. /**
  27840. * Gets a particle system by id
  27841. * @param id defines the particle system id
  27842. * @return the corresponding system or null if none found
  27843. */
  27844. Scene.prototype.getParticleSystemByID = function (id) {
  27845. for (var index = 0; index < this.particleSystems.length; index++) {
  27846. if (this.particleSystems[index].id === id) {
  27847. return this.particleSystems[index];
  27848. }
  27849. }
  27850. return null;
  27851. };
  27852. /**
  27853. * Gets a geometry using its ID
  27854. * @param id defines the geometry's id
  27855. * @return the geometry or null if none found.
  27856. */
  27857. Scene.prototype.getGeometryByID = function (id) {
  27858. for (var index = 0; index < this.geometries.length; index++) {
  27859. if (this.geometries[index].id === id) {
  27860. return this.geometries[index];
  27861. }
  27862. }
  27863. return null;
  27864. };
  27865. /**
  27866. * Add a new geometry to this scene
  27867. * @param geometry defines the geometry to be added to the scene.
  27868. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27869. * @return a boolean defining if the geometry was added or not
  27870. */
  27871. Scene.prototype.pushGeometry = function (geometry, force) {
  27872. if (!force && this.getGeometryByID(geometry.id)) {
  27873. return false;
  27874. }
  27875. this.geometries.push(geometry);
  27876. //notify the collision coordinator
  27877. if (this.collisionCoordinator) {
  27878. this.collisionCoordinator.onGeometryAdded(geometry);
  27879. }
  27880. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27881. return true;
  27882. };
  27883. /**
  27884. * Removes an existing geometry
  27885. * @param geometry defines the geometry to be removed from the scene
  27886. * @return a boolean defining if the geometry was removed or not
  27887. */
  27888. Scene.prototype.removeGeometry = function (geometry) {
  27889. var index = this.geometries.indexOf(geometry);
  27890. if (index > -1) {
  27891. this.geometries.splice(index, 1);
  27892. //notify the collision coordinator
  27893. if (this.collisionCoordinator) {
  27894. this.collisionCoordinator.onGeometryDeleted(geometry);
  27895. }
  27896. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27897. return true;
  27898. }
  27899. return false;
  27900. };
  27901. /**
  27902. * Gets the list of geometries attached to the scene
  27903. * @returns an array of Geometry
  27904. */
  27905. Scene.prototype.getGeometries = function () {
  27906. return this.geometries;
  27907. };
  27908. /**
  27909. * Gets the first added mesh found of a given ID
  27910. * @param id defines the id to search for
  27911. * @return the mesh found or null if not found at all
  27912. */
  27913. Scene.prototype.getMeshByID = function (id) {
  27914. for (var index = 0; index < this.meshes.length; index++) {
  27915. if (this.meshes[index].id === id) {
  27916. return this.meshes[index];
  27917. }
  27918. }
  27919. return null;
  27920. };
  27921. /**
  27922. * Gets a list of meshes using their id
  27923. * @param id defines the id to search for
  27924. * @returns a list of meshes
  27925. */
  27926. Scene.prototype.getMeshesByID = function (id) {
  27927. return this.meshes.filter(function (m) {
  27928. return m.id === id;
  27929. });
  27930. };
  27931. /**
  27932. * Gets the first added transform node found of a given ID
  27933. * @param id defines the id to search for
  27934. * @return the found transform node or null if not found at all.
  27935. */
  27936. Scene.prototype.getTransformNodeByID = function (id) {
  27937. for (var index = 0; index < this.transformNodes.length; index++) {
  27938. if (this.transformNodes[index].id === id) {
  27939. return this.transformNodes[index];
  27940. }
  27941. }
  27942. return null;
  27943. };
  27944. /**
  27945. * Gets a list of transform nodes using their id
  27946. * @param id defines the id to search for
  27947. * @returns a list of transform nodes
  27948. */
  27949. Scene.prototype.getTransformNodesByID = function (id) {
  27950. return this.transformNodes.filter(function (m) {
  27951. return m.id === id;
  27952. });
  27953. };
  27954. /**
  27955. * Gets a mesh with its auto-generated unique id
  27956. * @param uniqueId defines the unique id to search for
  27957. * @return the found mesh or null if not found at all.
  27958. */
  27959. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27960. for (var index = 0; index < this.meshes.length; index++) {
  27961. if (this.meshes[index].uniqueId === uniqueId) {
  27962. return this.meshes[index];
  27963. }
  27964. }
  27965. return null;
  27966. };
  27967. /**
  27968. * Gets a the last added mesh using a given id
  27969. * @param id defines the id to search for
  27970. * @return the found mesh or null if not found at all.
  27971. */
  27972. Scene.prototype.getLastMeshByID = function (id) {
  27973. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27974. if (this.meshes[index].id === id) {
  27975. return this.meshes[index];
  27976. }
  27977. }
  27978. return null;
  27979. };
  27980. /**
  27981. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27982. * @param id defines the id to search for
  27983. * @return the found node or null if not found at all
  27984. */
  27985. Scene.prototype.getLastEntryByID = function (id) {
  27986. var index;
  27987. for (index = this.meshes.length - 1; index >= 0; index--) {
  27988. if (this.meshes[index].id === id) {
  27989. return this.meshes[index];
  27990. }
  27991. }
  27992. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27993. if (this.transformNodes[index].id === id) {
  27994. return this.transformNodes[index];
  27995. }
  27996. }
  27997. for (index = this.cameras.length - 1; index >= 0; index--) {
  27998. if (this.cameras[index].id === id) {
  27999. return this.cameras[index];
  28000. }
  28001. }
  28002. for (index = this.lights.length - 1; index >= 0; index--) {
  28003. if (this.lights[index].id === id) {
  28004. return this.lights[index];
  28005. }
  28006. }
  28007. return null;
  28008. };
  28009. /**
  28010. * Gets a node (Mesh, Camera, Light) using a given id
  28011. * @param id defines the id to search for
  28012. * @return the found node or null if not found at all
  28013. */
  28014. Scene.prototype.getNodeByID = function (id) {
  28015. var mesh = this.getMeshByID(id);
  28016. if (mesh) {
  28017. return mesh;
  28018. }
  28019. var light = this.getLightByID(id);
  28020. if (light) {
  28021. return light;
  28022. }
  28023. var camera = this.getCameraByID(id);
  28024. if (camera) {
  28025. return camera;
  28026. }
  28027. var bone = this.getBoneByID(id);
  28028. return bone;
  28029. };
  28030. /**
  28031. * Gets a node (Mesh, Camera, Light) using a given name
  28032. * @param name defines the name to search for
  28033. * @return the found node or null if not found at all.
  28034. */
  28035. Scene.prototype.getNodeByName = function (name) {
  28036. var mesh = this.getMeshByName(name);
  28037. if (mesh) {
  28038. return mesh;
  28039. }
  28040. var light = this.getLightByName(name);
  28041. if (light) {
  28042. return light;
  28043. }
  28044. var camera = this.getCameraByName(name);
  28045. if (camera) {
  28046. return camera;
  28047. }
  28048. var bone = this.getBoneByName(name);
  28049. return bone;
  28050. };
  28051. /**
  28052. * Gets a mesh using a given name
  28053. * @param name defines the name to search for
  28054. * @return the found mesh or null if not found at all.
  28055. */
  28056. Scene.prototype.getMeshByName = function (name) {
  28057. for (var index = 0; index < this.meshes.length; index++) {
  28058. if (this.meshes[index].name === name) {
  28059. return this.meshes[index];
  28060. }
  28061. }
  28062. return null;
  28063. };
  28064. /**
  28065. * Gets a transform node using a given name
  28066. * @param name defines the name to search for
  28067. * @return the found transform node or null if not found at all.
  28068. */
  28069. Scene.prototype.getTransformNodeByName = function (name) {
  28070. for (var index = 0; index < this.transformNodes.length; index++) {
  28071. if (this.transformNodes[index].name === name) {
  28072. return this.transformNodes[index];
  28073. }
  28074. }
  28075. return null;
  28076. };
  28077. /**
  28078. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28079. * @param id defines the id to search for
  28080. * @return the found skeleton or null if not found at all.
  28081. */
  28082. Scene.prototype.getLastSkeletonByID = function (id) {
  28083. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28084. if (this.skeletons[index].id === id) {
  28085. return this.skeletons[index];
  28086. }
  28087. }
  28088. return null;
  28089. };
  28090. /**
  28091. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28092. * @param id defines the id to search for
  28093. * @return the found skeleton or null if not found at all.
  28094. */
  28095. Scene.prototype.getSkeletonById = function (id) {
  28096. for (var index = 0; index < this.skeletons.length; index++) {
  28097. if (this.skeletons[index].id === id) {
  28098. return this.skeletons[index];
  28099. }
  28100. }
  28101. return null;
  28102. };
  28103. /**
  28104. * Gets a skeleton using a given name
  28105. * @param name defines the name to search for
  28106. * @return the found skeleton or null if not found at all.
  28107. */
  28108. Scene.prototype.getSkeletonByName = function (name) {
  28109. for (var index = 0; index < this.skeletons.length; index++) {
  28110. if (this.skeletons[index].name === name) {
  28111. return this.skeletons[index];
  28112. }
  28113. }
  28114. return null;
  28115. };
  28116. /**
  28117. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28118. * @param id defines the id to search for
  28119. * @return the found morph target manager or null if not found at all.
  28120. */
  28121. Scene.prototype.getMorphTargetManagerById = function (id) {
  28122. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28123. if (this.morphTargetManagers[index].uniqueId === id) {
  28124. return this.morphTargetManagers[index];
  28125. }
  28126. }
  28127. return null;
  28128. };
  28129. /**
  28130. * Gets a boolean indicating if the given mesh is active
  28131. * @param mesh defines the mesh to look for
  28132. * @returns true if the mesh is in the active list
  28133. */
  28134. Scene.prototype.isActiveMesh = function (mesh) {
  28135. return (this._activeMeshes.indexOf(mesh) !== -1);
  28136. };
  28137. Object.defineProperty(Scene.prototype, "uid", {
  28138. /**
  28139. * Return a unique id as a string which can serve as an identifier for the scene
  28140. */
  28141. get: function () {
  28142. if (!this._uid) {
  28143. this._uid = BABYLON.Tools.RandomId();
  28144. }
  28145. return this._uid;
  28146. },
  28147. enumerable: true,
  28148. configurable: true
  28149. });
  28150. /**
  28151. * Add an externaly attached data from its key.
  28152. * This method call will fail and return false, if such key already exists.
  28153. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28154. * @param key the unique key that identifies the data
  28155. * @param data the data object to associate to the key for this Engine instance
  28156. * @return true if no such key were already present and the data was added successfully, false otherwise
  28157. */
  28158. Scene.prototype.addExternalData = function (key, data) {
  28159. if (!this._externalData) {
  28160. this._externalData = new BABYLON.StringDictionary();
  28161. }
  28162. return this._externalData.add(key, data);
  28163. };
  28164. /**
  28165. * Get an externaly attached data from its key
  28166. * @param key the unique key that identifies the data
  28167. * @return the associated data, if present (can be null), or undefined if not present
  28168. */
  28169. Scene.prototype.getExternalData = function (key) {
  28170. if (!this._externalData) {
  28171. return null;
  28172. }
  28173. return this._externalData.get(key);
  28174. };
  28175. /**
  28176. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28177. * @param key the unique key that identifies the data
  28178. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28179. * @return the associated data, can be null if the factory returned null.
  28180. */
  28181. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28182. if (!this._externalData) {
  28183. this._externalData = new BABYLON.StringDictionary();
  28184. }
  28185. return this._externalData.getOrAddWithFactory(key, factory);
  28186. };
  28187. /**
  28188. * Remove an externaly attached data from the Engine instance
  28189. * @param key the unique key that identifies the data
  28190. * @return true if the data was successfully removed, false if it doesn't exist
  28191. */
  28192. Scene.prototype.removeExternalData = function (key) {
  28193. return this._externalData.remove(key);
  28194. };
  28195. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28196. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28197. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28198. var step = _a[_i];
  28199. step.action(mesh, subMesh);
  28200. }
  28201. var material = subMesh.getMaterial();
  28202. if (material !== null && material !== undefined) {
  28203. // Render targets
  28204. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28205. if (this._processedMaterials.indexOf(material) === -1) {
  28206. this._processedMaterials.push(material);
  28207. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28208. }
  28209. }
  28210. // Dispatch
  28211. this._activeIndices.addCount(subMesh.indexCount, false);
  28212. this._renderingManager.dispatch(subMesh, mesh, material);
  28213. }
  28214. }
  28215. };
  28216. /**
  28217. * Clear the processed materials smart array preventing retention point in material dispose.
  28218. */
  28219. Scene.prototype.freeProcessedMaterials = function () {
  28220. this._processedMaterials.dispose();
  28221. };
  28222. /**
  28223. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28224. */
  28225. Scene.prototype.freeActiveMeshes = function () {
  28226. this._activeMeshes.dispose();
  28227. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28228. this.activeCamera._activeMeshes.dispose();
  28229. }
  28230. if (this.activeCameras) {
  28231. for (var i = 0; i < this.activeCameras.length; i++) {
  28232. var activeCamera = this.activeCameras[i];
  28233. if (activeCamera && activeCamera._activeMeshes) {
  28234. activeCamera._activeMeshes.dispose();
  28235. }
  28236. }
  28237. }
  28238. };
  28239. /**
  28240. * Clear the info related to rendering groups preventing retention points during dispose.
  28241. */
  28242. Scene.prototype.freeRenderingGroups = function () {
  28243. if (this._renderingManager) {
  28244. this._renderingManager.freeRenderingGroups();
  28245. }
  28246. if (this.textures) {
  28247. for (var i = 0; i < this.textures.length; i++) {
  28248. var texture = this.textures[i];
  28249. if (texture && texture.renderList) {
  28250. texture.freeRenderingGroups();
  28251. }
  28252. }
  28253. }
  28254. };
  28255. /** @hidden */
  28256. Scene.prototype._isInIntermediateRendering = function () {
  28257. return this._intermediateRendering;
  28258. };
  28259. /**
  28260. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28261. * @returns the current scene
  28262. */
  28263. Scene.prototype.freezeActiveMeshes = function () {
  28264. if (!this.activeCamera) {
  28265. return this;
  28266. }
  28267. if (!this._frustumPlanes) {
  28268. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28269. }
  28270. this._evaluateActiveMeshes();
  28271. this._activeMeshesFrozen = true;
  28272. return this;
  28273. };
  28274. /**
  28275. * Use this function to restart evaluating active meshes on every frame
  28276. * @returns the current scene
  28277. */
  28278. Scene.prototype.unfreezeActiveMeshes = function () {
  28279. this._activeMeshesFrozen = false;
  28280. return this;
  28281. };
  28282. Scene.prototype._evaluateActiveMeshes = function () {
  28283. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28284. return;
  28285. }
  28286. if (!this.activeCamera) {
  28287. return;
  28288. }
  28289. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28290. this.activeCamera._activeMeshes.reset();
  28291. this._activeMeshes.reset();
  28292. this._renderingManager.reset();
  28293. this._processedMaterials.reset();
  28294. this._activeParticleSystems.reset();
  28295. this._activeSkeletons.reset();
  28296. this._softwareSkinnedMeshes.reset();
  28297. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28298. var step = _a[_i];
  28299. step.action();
  28300. }
  28301. // Determine mesh candidates
  28302. var meshes = this.getActiveMeshCandidates();
  28303. // Check each mesh
  28304. var len = meshes.length;
  28305. for (var i = 0; i < len; i++) {
  28306. var mesh = meshes.data[i];
  28307. if (mesh.isBlocked) {
  28308. continue;
  28309. }
  28310. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28311. if (!mesh.isReady() || !mesh.isEnabled()) {
  28312. continue;
  28313. }
  28314. mesh.computeWorldMatrix();
  28315. // Intersections
  28316. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28317. this._meshesForIntersections.pushNoDuplicate(mesh);
  28318. }
  28319. // Switch to current LOD
  28320. var meshLOD = mesh.getLOD(this.activeCamera);
  28321. if (meshLOD === undefined || meshLOD === null) {
  28322. continue;
  28323. }
  28324. mesh._preActivate();
  28325. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28326. this._activeMeshes.push(mesh);
  28327. this.activeCamera._activeMeshes.push(mesh);
  28328. mesh._activate(this._renderId);
  28329. if (meshLOD !== mesh) {
  28330. meshLOD._activate(this._renderId);
  28331. }
  28332. this._activeMesh(mesh, meshLOD);
  28333. }
  28334. }
  28335. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28336. // Particle systems
  28337. if (this.particlesEnabled) {
  28338. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28339. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28340. var particleSystem = this.particleSystems[particleIndex];
  28341. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28342. continue;
  28343. }
  28344. var emitter = particleSystem.emitter;
  28345. if (!emitter.position || emitter.isEnabled()) {
  28346. this._activeParticleSystems.push(particleSystem);
  28347. particleSystem.animate();
  28348. this._renderingManager.dispatchParticles(particleSystem);
  28349. }
  28350. }
  28351. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28352. }
  28353. };
  28354. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28355. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28356. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28357. mesh.skeleton.prepare();
  28358. }
  28359. if (!mesh.computeBonesUsingShaders) {
  28360. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28361. }
  28362. }
  28363. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28364. var step = _a[_i];
  28365. step.action(sourceMesh, mesh);
  28366. }
  28367. if (mesh !== undefined && mesh !== null
  28368. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28369. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28370. var len = subMeshes.length;
  28371. for (var i = 0; i < len; i++) {
  28372. var subMesh = subMeshes.data[i];
  28373. this._evaluateSubMesh(subMesh, mesh);
  28374. }
  28375. }
  28376. };
  28377. /**
  28378. * Update the transform matrix to update from the current active camera
  28379. * @param force defines a boolean used to force the update even if cache is up to date
  28380. */
  28381. Scene.prototype.updateTransformMatrix = function (force) {
  28382. if (!this.activeCamera) {
  28383. return;
  28384. }
  28385. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28386. };
  28387. /**
  28388. * 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)
  28389. * @param alternateCamera defines the camera to use
  28390. */
  28391. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28392. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28393. };
  28394. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28395. if (camera && camera._skipRendering) {
  28396. return;
  28397. }
  28398. var engine = this._engine;
  28399. this.activeCamera = camera;
  28400. if (!this.activeCamera)
  28401. throw new Error("Active camera not set");
  28402. // Viewport
  28403. engine.setViewport(this.activeCamera.viewport);
  28404. // Camera
  28405. this.resetCachedMaterial();
  28406. this._renderId++;
  28407. this.updateTransformMatrix();
  28408. if (camera._alternateCamera) {
  28409. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28410. this._alternateRendering = true;
  28411. }
  28412. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28413. // Meshes
  28414. this._evaluateActiveMeshes();
  28415. // Software skinning
  28416. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28417. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28418. mesh.applySkeleton(mesh.skeleton);
  28419. }
  28420. // Render targets
  28421. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28422. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28423. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28424. }
  28425. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28426. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28427. }
  28428. // Collects render targets from external components.
  28429. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28430. var step = _a[_i];
  28431. step.action(this._renderTargets);
  28432. }
  28433. if (this.renderTargetsEnabled) {
  28434. this._intermediateRendering = true;
  28435. if (this._renderTargets.length > 0) {
  28436. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28437. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28438. var renderTarget = this._renderTargets.data[renderIndex];
  28439. if (renderTarget._shouldRender()) {
  28440. this._renderId++;
  28441. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28442. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28443. }
  28444. }
  28445. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28446. this._renderId++;
  28447. }
  28448. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28449. var step = _c[_b];
  28450. step.action(this.activeCamera);
  28451. }
  28452. this._intermediateRendering = false;
  28453. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28454. }
  28455. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28456. // Prepare Frame
  28457. if (this.postProcessManager) {
  28458. this.postProcessManager._prepareFrame();
  28459. }
  28460. // Before Camera Draw
  28461. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28462. var step = _e[_d];
  28463. step.action(this.activeCamera);
  28464. }
  28465. // Render
  28466. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28467. this._renderingManager.render(null, null, true, true);
  28468. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28469. // After Camera Draw
  28470. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28471. var step = _g[_f];
  28472. step.action(this.activeCamera);
  28473. }
  28474. // Finalize frame
  28475. if (this.postProcessManager) {
  28476. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28477. }
  28478. // Reset some special arrays
  28479. this._renderTargets.reset();
  28480. this._alternateRendering = false;
  28481. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28482. };
  28483. Scene.prototype._processSubCameras = function (camera) {
  28484. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28485. this._renderForCamera(camera);
  28486. return;
  28487. }
  28488. // rig cameras
  28489. for (var index = 0; index < camera._rigCameras.length; index++) {
  28490. this._renderForCamera(camera._rigCameras[index], camera);
  28491. }
  28492. this.activeCamera = camera;
  28493. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28494. };
  28495. Scene.prototype._checkIntersections = function () {
  28496. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28497. var sourceMesh = this._meshesForIntersections.data[index];
  28498. if (!sourceMesh.actionManager) {
  28499. continue;
  28500. }
  28501. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28502. var action = sourceMesh.actionManager.actions[actionIndex];
  28503. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28504. var parameters = action.getTriggerParameter();
  28505. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28506. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28507. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28508. if (areIntersecting && currentIntersectionInProgress === -1) {
  28509. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28510. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28511. sourceMesh._intersectionsInProgress.push(otherMesh);
  28512. }
  28513. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28514. sourceMesh._intersectionsInProgress.push(otherMesh);
  28515. }
  28516. }
  28517. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28518. //They intersected, and now they don't.
  28519. //is this trigger an exit trigger? execute an event.
  28520. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28521. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28522. }
  28523. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28524. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28525. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28526. return otherMesh === parameterMesh;
  28527. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28528. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28529. }
  28530. }
  28531. }
  28532. }
  28533. }
  28534. };
  28535. /** @hidden */
  28536. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28537. // Do nothing. Code will be replaced if physics engine component is referenced
  28538. };
  28539. /**
  28540. * Render the scene
  28541. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28542. */
  28543. Scene.prototype.render = function (updateCameras) {
  28544. if (updateCameras === void 0) { updateCameras = true; }
  28545. if (this.isDisposed) {
  28546. return;
  28547. }
  28548. this._frameId++;
  28549. // Register components that have been associated lately to the scene.
  28550. this._registerTransientComponents();
  28551. this._activeParticles.fetchNewFrame();
  28552. this._totalVertices.fetchNewFrame();
  28553. this._activeIndices.fetchNewFrame();
  28554. this._activeBones.fetchNewFrame();
  28555. this._meshesForIntersections.reset();
  28556. this.resetCachedMaterial();
  28557. this.onBeforeAnimationsObservable.notifyObservers(this);
  28558. // Actions
  28559. if (this.actionManager) {
  28560. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28561. }
  28562. if (this._engine.isDeterministicLockStep()) {
  28563. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28564. var defaultFPS = (60.0 / 1000.0);
  28565. var defaultFrameTime = this.getDeterministicFrameTime();
  28566. var stepsTaken = 0;
  28567. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28568. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28569. internalSteps = Math.min(internalSteps, maxSubSteps);
  28570. do {
  28571. this.onBeforeStepObservable.notifyObservers(this);
  28572. // Animations
  28573. this._animationRatio = defaultFrameTime * defaultFPS;
  28574. this._animate();
  28575. this.onAfterAnimationsObservable.notifyObservers(this);
  28576. // Physics
  28577. this._advancePhysicsEngineStep(defaultFrameTime);
  28578. this.onAfterStepObservable.notifyObservers(this);
  28579. this._currentStepId++;
  28580. stepsTaken++;
  28581. deltaTime -= defaultFrameTime;
  28582. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28583. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28584. }
  28585. else {
  28586. // Animations
  28587. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28588. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28589. this._animate();
  28590. this.onAfterAnimationsObservable.notifyObservers(this);
  28591. // Physics
  28592. this._advancePhysicsEngineStep(deltaTime);
  28593. }
  28594. // Before camera update steps
  28595. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28596. var step = _a[_i];
  28597. step.action();
  28598. }
  28599. // Update Cameras
  28600. if (updateCameras) {
  28601. if (this.activeCameras.length > 0) {
  28602. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28603. var camera = this.activeCameras[cameraIndex];
  28604. camera.update();
  28605. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28606. // rig cameras
  28607. for (var index = 0; index < camera._rigCameras.length; index++) {
  28608. camera._rigCameras[index].update();
  28609. }
  28610. }
  28611. }
  28612. }
  28613. else if (this.activeCamera) {
  28614. this.activeCamera.update();
  28615. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28616. // rig cameras
  28617. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28618. this.activeCamera._rigCameras[index].update();
  28619. }
  28620. }
  28621. }
  28622. }
  28623. // Before render
  28624. this.onBeforeRenderObservable.notifyObservers(this);
  28625. // Customs render targets
  28626. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28627. var engine = this.getEngine();
  28628. var currentActiveCamera = this.activeCamera;
  28629. if (this.renderTargetsEnabled) {
  28630. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28631. this._intermediateRendering = true;
  28632. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28633. var renderTarget = this.customRenderTargets[customIndex];
  28634. if (renderTarget._shouldRender()) {
  28635. this._renderId++;
  28636. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28637. if (!this.activeCamera)
  28638. throw new Error("Active camera not set");
  28639. // Viewport
  28640. engine.setViewport(this.activeCamera.viewport);
  28641. // Camera
  28642. this.updateTransformMatrix();
  28643. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28644. }
  28645. }
  28646. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28647. this._intermediateRendering = false;
  28648. this._renderId++;
  28649. }
  28650. // Restore back buffer
  28651. if (this.customRenderTargets.length > 0) {
  28652. engine.restoreDefaultFramebuffer();
  28653. }
  28654. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28655. this.activeCamera = currentActiveCamera;
  28656. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28657. var step = _c[_b];
  28658. step.action();
  28659. }
  28660. // Clear
  28661. if (this.autoClearDepthAndStencil || this.autoClear) {
  28662. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28663. }
  28664. // Collects render targets from external components.
  28665. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28666. var step = _e[_d];
  28667. step.action(this._renderTargets);
  28668. }
  28669. // Multi-cameras?
  28670. if (this.activeCameras.length > 0) {
  28671. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28672. if (cameraIndex > 0) {
  28673. this._engine.clear(null, false, true, true);
  28674. }
  28675. this._processSubCameras(this.activeCameras[cameraIndex]);
  28676. }
  28677. }
  28678. else {
  28679. if (!this.activeCamera) {
  28680. throw new Error("No camera defined");
  28681. }
  28682. this._processSubCameras(this.activeCamera);
  28683. }
  28684. // Intersection checks
  28685. this._checkIntersections();
  28686. // Executes the after render stage actions.
  28687. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28688. var step = _g[_f];
  28689. step.action();
  28690. }
  28691. // After render
  28692. if (this.afterRender) {
  28693. this.afterRender();
  28694. }
  28695. this.onAfterRenderObservable.notifyObservers(this);
  28696. // Cleaning
  28697. if (this._toBeDisposed.length) {
  28698. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28699. var data = this._toBeDisposed[index];
  28700. if (data) {
  28701. data.dispose();
  28702. }
  28703. }
  28704. this._toBeDisposed = [];
  28705. }
  28706. if (this.dumpNextRenderTargets) {
  28707. this.dumpNextRenderTargets = false;
  28708. }
  28709. this._activeBones.addCount(0, true);
  28710. this._activeIndices.addCount(0, true);
  28711. this._activeParticles.addCount(0, true);
  28712. };
  28713. /**
  28714. * Freeze all materials
  28715. * A frozen material will not be updatable but should be faster to render
  28716. */
  28717. Scene.prototype.freezeMaterials = function () {
  28718. for (var i = 0; i < this.materials.length; i++) {
  28719. this.materials[i].freeze();
  28720. }
  28721. };
  28722. /**
  28723. * Unfreeze all materials
  28724. * A frozen material will not be updatable but should be faster to render
  28725. */
  28726. Scene.prototype.unfreezeMaterials = function () {
  28727. for (var i = 0; i < this.materials.length; i++) {
  28728. this.materials[i].unfreeze();
  28729. }
  28730. };
  28731. /**
  28732. * Releases all held ressources
  28733. */
  28734. Scene.prototype.dispose = function () {
  28735. this.beforeRender = null;
  28736. this.afterRender = null;
  28737. this.skeletons = [];
  28738. this.morphTargetManagers = [];
  28739. this._transientComponents = [];
  28740. this._isReadyForMeshStage.clear();
  28741. this._beforeEvaluateActiveMeshStage.clear();
  28742. this._evaluateSubMeshStage.clear();
  28743. this._activeMeshStage.clear();
  28744. this._cameraDrawRenderTargetStage.clear();
  28745. this._beforeCameraDrawStage.clear();
  28746. this._beforeRenderingGroupDrawStage.clear();
  28747. this._beforeRenderingMeshStage.clear();
  28748. this._afterRenderingMeshStage.clear();
  28749. this._afterRenderingGroupDrawStage.clear();
  28750. this._afterCameraDrawStage.clear();
  28751. this._afterRenderStage.clear();
  28752. this._beforeCameraUpdateStage.clear();
  28753. this._beforeClearStage.clear();
  28754. this._gatherRenderTargetsStage.clear();
  28755. this._gatherActiveCameraRenderTargetsStage.clear();
  28756. this._pointerMoveStage.clear();
  28757. this._pointerDownStage.clear();
  28758. this._pointerUpStage.clear();
  28759. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28760. var component = _a[_i];
  28761. component.dispose();
  28762. }
  28763. this.importedMeshesFiles = new Array();
  28764. this.stopAllAnimations();
  28765. this.resetCachedMaterial();
  28766. // Smart arrays
  28767. if (this.activeCamera) {
  28768. this.activeCamera._activeMeshes.dispose();
  28769. this.activeCamera = null;
  28770. }
  28771. this._activeMeshes.dispose();
  28772. this._renderingManager.dispose();
  28773. this._processedMaterials.dispose();
  28774. this._activeParticleSystems.dispose();
  28775. this._activeSkeletons.dispose();
  28776. this._softwareSkinnedMeshes.dispose();
  28777. this._renderTargets.dispose();
  28778. this._registeredForLateAnimationBindings.dispose();
  28779. this._meshesForIntersections.dispose();
  28780. this._toBeDisposed = [];
  28781. // Abort active requests
  28782. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28783. var request = _c[_b];
  28784. request.abort();
  28785. }
  28786. // Events
  28787. this.onDisposeObservable.notifyObservers(this);
  28788. this.onDisposeObservable.clear();
  28789. this.onBeforeRenderObservable.clear();
  28790. this.onAfterRenderObservable.clear();
  28791. this.onBeforeRenderTargetsRenderObservable.clear();
  28792. this.onAfterRenderTargetsRenderObservable.clear();
  28793. this.onAfterStepObservable.clear();
  28794. this.onBeforeStepObservable.clear();
  28795. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28796. this.onAfterActiveMeshesEvaluationObservable.clear();
  28797. this.onBeforeParticlesRenderingObservable.clear();
  28798. this.onAfterParticlesRenderingObservable.clear();
  28799. this.onBeforeDrawPhaseObservable.clear();
  28800. this.onAfterDrawPhaseObservable.clear();
  28801. this.onBeforeAnimationsObservable.clear();
  28802. this.onAfterAnimationsObservable.clear();
  28803. this.onDataLoadedObservable.clear();
  28804. this.onBeforeRenderingGroupObservable.clear();
  28805. this.onAfterRenderingGroupObservable.clear();
  28806. this.onMeshImportedObservable.clear();
  28807. this.onBeforeCameraRenderObservable.clear();
  28808. this.onAfterCameraRenderObservable.clear();
  28809. this.onReadyObservable.clear();
  28810. this.onNewCameraAddedObservable.clear();
  28811. this.onCameraRemovedObservable.clear();
  28812. this.onNewLightAddedObservable.clear();
  28813. this.onLightRemovedObservable.clear();
  28814. this.onNewGeometryAddedObservable.clear();
  28815. this.onGeometryRemovedObservable.clear();
  28816. this.onNewTransformNodeAddedObservable.clear();
  28817. this.onTransformNodeRemovedObservable.clear();
  28818. this.onNewMeshAddedObservable.clear();
  28819. this.onMeshRemovedObservable.clear();
  28820. this.onNewMaterialAddedObservable.clear();
  28821. this.onMaterialRemovedObservable.clear();
  28822. this.onNewTextureAddedObservable.clear();
  28823. this.onTextureRemovedObservable.clear();
  28824. this.onPrePointerObservable.clear();
  28825. this.onPointerObservable.clear();
  28826. this.onPreKeyboardObservable.clear();
  28827. this.onKeyboardObservable.clear();
  28828. this.detachControl();
  28829. // Detach cameras
  28830. var canvas = this._engine.getRenderingCanvas();
  28831. if (canvas) {
  28832. var index;
  28833. for (index = 0; index < this.cameras.length; index++) {
  28834. this.cameras[index].detachControl(canvas);
  28835. }
  28836. }
  28837. // Release animation groups
  28838. while (this.animationGroups.length) {
  28839. this.animationGroups[0].dispose();
  28840. }
  28841. // Release lights
  28842. while (this.lights.length) {
  28843. this.lights[0].dispose();
  28844. }
  28845. // Release meshes
  28846. while (this.meshes.length) {
  28847. this.meshes[0].dispose(true);
  28848. }
  28849. while (this.transformNodes.length) {
  28850. this.removeTransformNode(this.transformNodes[0]);
  28851. }
  28852. // Release cameras
  28853. while (this.cameras.length) {
  28854. this.cameras[0].dispose();
  28855. }
  28856. // Release materials
  28857. if (this.defaultMaterial) {
  28858. this.defaultMaterial.dispose();
  28859. }
  28860. while (this.multiMaterials.length) {
  28861. this.multiMaterials[0].dispose();
  28862. }
  28863. while (this.materials.length) {
  28864. this.materials[0].dispose();
  28865. }
  28866. // Release particles
  28867. while (this.particleSystems.length) {
  28868. this.particleSystems[0].dispose();
  28869. }
  28870. // Release postProcesses
  28871. while (this.postProcesses.length) {
  28872. this.postProcesses[0].dispose();
  28873. }
  28874. // Release textures
  28875. while (this.textures.length) {
  28876. this.textures[0].dispose();
  28877. }
  28878. // Release UBO
  28879. this._sceneUbo.dispose();
  28880. if (this._alternateSceneUbo) {
  28881. this._alternateSceneUbo.dispose();
  28882. }
  28883. // Post-processes
  28884. this.postProcessManager.dispose();
  28885. // Remove from engine
  28886. index = this._engine.scenes.indexOf(this);
  28887. if (index > -1) {
  28888. this._engine.scenes.splice(index, 1);
  28889. }
  28890. this._engine.wipeCaches(true);
  28891. this._isDisposed = true;
  28892. };
  28893. Object.defineProperty(Scene.prototype, "isDisposed", {
  28894. /**
  28895. * Gets if the scene is already disposed
  28896. */
  28897. get: function () {
  28898. return this._isDisposed;
  28899. },
  28900. enumerable: true,
  28901. configurable: true
  28902. });
  28903. /**
  28904. * Call this function to reduce memory footprint of the scene.
  28905. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28906. */
  28907. Scene.prototype.clearCachedVertexData = function () {
  28908. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28909. var mesh = this.meshes[meshIndex];
  28910. var geometry = mesh.geometry;
  28911. if (geometry) {
  28912. geometry._indices = [];
  28913. for (var vbName in geometry._vertexBuffers) {
  28914. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28915. continue;
  28916. }
  28917. geometry._vertexBuffers[vbName]._buffer._data = null;
  28918. }
  28919. }
  28920. }
  28921. };
  28922. /**
  28923. * This function will remove the local cached buffer data from texture.
  28924. * It will save memory but will prevent the texture from being rebuilt
  28925. */
  28926. Scene.prototype.cleanCachedTextureBuffer = function () {
  28927. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28928. var baseTexture = _a[_i];
  28929. var buffer = baseTexture._buffer;
  28930. if (buffer) {
  28931. baseTexture._buffer = null;
  28932. }
  28933. }
  28934. };
  28935. /**
  28936. * Get the world extend vectors with an optional filter
  28937. *
  28938. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28939. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28940. */
  28941. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28942. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28943. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28944. filterPredicate = filterPredicate || (function () { return true; });
  28945. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28946. mesh.computeWorldMatrix(true);
  28947. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28948. return;
  28949. }
  28950. var boundingInfo = mesh.getBoundingInfo();
  28951. var minBox = boundingInfo.boundingBox.minimumWorld;
  28952. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28953. BABYLON.Tools.CheckExtends(minBox, min, max);
  28954. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28955. });
  28956. return {
  28957. min: min,
  28958. max: max
  28959. };
  28960. };
  28961. // Picking
  28962. /**
  28963. * Creates a ray that can be used to pick in the scene
  28964. * @param x defines the x coordinate of the origin (on-screen)
  28965. * @param y defines the y coordinate of the origin (on-screen)
  28966. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28967. * @param camera defines the camera to use for the picking
  28968. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28969. * @returns a Ray
  28970. */
  28971. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28972. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28973. var result = BABYLON.Ray.Zero();
  28974. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28975. return result;
  28976. };
  28977. /**
  28978. * Creates a ray that can be used to pick in the scene
  28979. * @param x defines the x coordinate of the origin (on-screen)
  28980. * @param y defines the y coordinate of the origin (on-screen)
  28981. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28982. * @param result defines the ray where to store the picking ray
  28983. * @param camera defines the camera to use for the picking
  28984. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28985. * @returns the current scene
  28986. */
  28987. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28988. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28989. var engine = this._engine;
  28990. if (!camera) {
  28991. if (!this.activeCamera)
  28992. throw new Error("Active camera not set");
  28993. camera = this.activeCamera;
  28994. }
  28995. var cameraViewport = camera.viewport;
  28996. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28997. // Moving coordinates to local viewport world
  28998. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28999. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29000. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29001. return this;
  29002. };
  29003. /**
  29004. * Creates a ray that can be used to pick in the scene
  29005. * @param x defines the x coordinate of the origin (on-screen)
  29006. * @param y defines the y coordinate of the origin (on-screen)
  29007. * @param camera defines the camera to use for the picking
  29008. * @returns a Ray
  29009. */
  29010. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29011. var result = BABYLON.Ray.Zero();
  29012. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29013. return result;
  29014. };
  29015. /**
  29016. * Creates a ray that can be used to pick in the scene
  29017. * @param x defines the x coordinate of the origin (on-screen)
  29018. * @param y defines the y coordinate of the origin (on-screen)
  29019. * @param result defines the ray where to store the picking ray
  29020. * @param camera defines the camera to use for the picking
  29021. * @returns the current scene
  29022. */
  29023. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29024. if (!BABYLON.PickingInfo) {
  29025. return this;
  29026. }
  29027. var engine = this._engine;
  29028. if (!camera) {
  29029. if (!this.activeCamera)
  29030. throw new Error("Active camera not set");
  29031. camera = this.activeCamera;
  29032. }
  29033. var cameraViewport = camera.viewport;
  29034. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29035. var identity = BABYLON.Matrix.Identity();
  29036. // Moving coordinates to local viewport world
  29037. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29038. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29039. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29040. return this;
  29041. };
  29042. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29043. if (!BABYLON.PickingInfo) {
  29044. return null;
  29045. }
  29046. var pickingInfo = null;
  29047. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29048. var mesh = this.meshes[meshIndex];
  29049. if (predicate) {
  29050. if (!predicate(mesh)) {
  29051. continue;
  29052. }
  29053. }
  29054. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29055. continue;
  29056. }
  29057. var world = mesh.getWorldMatrix();
  29058. var ray = rayFunction(world);
  29059. var result = mesh.intersects(ray, fastCheck);
  29060. if (!result || !result.hit)
  29061. continue;
  29062. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29063. continue;
  29064. pickingInfo = result;
  29065. if (fastCheck) {
  29066. break;
  29067. }
  29068. }
  29069. return pickingInfo || new BABYLON.PickingInfo();
  29070. };
  29071. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29072. if (!BABYLON.PickingInfo) {
  29073. return null;
  29074. }
  29075. var pickingInfos = new Array();
  29076. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29077. var mesh = this.meshes[meshIndex];
  29078. if (predicate) {
  29079. if (!predicate(mesh)) {
  29080. continue;
  29081. }
  29082. }
  29083. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29084. continue;
  29085. }
  29086. var world = mesh.getWorldMatrix();
  29087. var ray = rayFunction(world);
  29088. var result = mesh.intersects(ray, false);
  29089. if (!result || !result.hit)
  29090. continue;
  29091. pickingInfos.push(result);
  29092. }
  29093. return pickingInfos;
  29094. };
  29095. /** Launch a ray to try to pick a mesh in the scene
  29096. * @param x position on screen
  29097. * @param y position on screen
  29098. * @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
  29099. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29100. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29101. * @returns a PickingInfo
  29102. */
  29103. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29104. var _this = this;
  29105. if (!BABYLON.PickingInfo) {
  29106. return null;
  29107. }
  29108. var result = this._internalPick(function (world) {
  29109. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29110. return _this._tempPickingRay;
  29111. }, predicate, fastCheck);
  29112. if (result) {
  29113. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29114. }
  29115. return result;
  29116. };
  29117. /** Use the given ray to pick a mesh in the scene
  29118. * @param ray The ray to use to pick meshes
  29119. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  29120. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29121. * @returns a PickingInfo
  29122. */
  29123. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29124. var _this = this;
  29125. var result = this._internalPick(function (world) {
  29126. if (!_this._pickWithRayInverseMatrix) {
  29127. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29128. }
  29129. world.invertToRef(_this._pickWithRayInverseMatrix);
  29130. if (!_this._cachedRayForTransform) {
  29131. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29132. }
  29133. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29134. return _this._cachedRayForTransform;
  29135. }, predicate, fastCheck);
  29136. if (result) {
  29137. result.ray = ray;
  29138. }
  29139. return result;
  29140. };
  29141. /**
  29142. * Launch a ray to try to pick a mesh in the scene
  29143. * @param x X position on screen
  29144. * @param y Y position on screen
  29145. * @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
  29146. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29147. * @returns an array of PickingInfo
  29148. */
  29149. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29150. var _this = this;
  29151. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29152. };
  29153. /**
  29154. * Launch a ray to try to pick a mesh in the scene
  29155. * @param ray Ray to use
  29156. * @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
  29157. * @returns an array of PickingInfo
  29158. */
  29159. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29160. var _this = this;
  29161. return this._internalMultiPick(function (world) {
  29162. if (!_this._pickWithRayInverseMatrix) {
  29163. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29164. }
  29165. world.invertToRef(_this._pickWithRayInverseMatrix);
  29166. if (!_this._cachedRayForTransform) {
  29167. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29168. }
  29169. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29170. return _this._cachedRayForTransform;
  29171. }, predicate);
  29172. };
  29173. /**
  29174. * Force the value of meshUnderPointer
  29175. * @param mesh defines the mesh to use
  29176. */
  29177. Scene.prototype.setPointerOverMesh = function (mesh) {
  29178. if (this._pointerOverMesh === mesh) {
  29179. return;
  29180. }
  29181. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29182. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29183. }
  29184. this._pointerOverMesh = mesh;
  29185. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29186. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29187. }
  29188. };
  29189. /**
  29190. * Gets the mesh under the pointer
  29191. * @returns a Mesh or null if no mesh is under the pointer
  29192. */
  29193. Scene.prototype.getPointerOverMesh = function () {
  29194. return this._pointerOverMesh;
  29195. };
  29196. // Misc.
  29197. /** @hidden */
  29198. Scene.prototype._rebuildGeometries = function () {
  29199. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29200. var geometry = _a[_i];
  29201. geometry._rebuild();
  29202. }
  29203. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29204. var mesh = _c[_b];
  29205. mesh._rebuild();
  29206. }
  29207. if (this.postProcessManager) {
  29208. this.postProcessManager._rebuild();
  29209. }
  29210. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29211. var component = _e[_d];
  29212. component.rebuild();
  29213. }
  29214. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29215. var system = _g[_f];
  29216. system.rebuild();
  29217. }
  29218. };
  29219. /** @hidden */
  29220. Scene.prototype._rebuildTextures = function () {
  29221. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29222. var texture = _a[_i];
  29223. texture._rebuild();
  29224. }
  29225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29226. };
  29227. // Tags
  29228. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29229. if (tagsQuery === undefined) {
  29230. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29231. return list;
  29232. }
  29233. var listByTags = [];
  29234. forEach = forEach || (function (item) { return; });
  29235. for (var i in list) {
  29236. var item = list[i];
  29237. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29238. listByTags.push(item);
  29239. forEach(item);
  29240. }
  29241. }
  29242. return listByTags;
  29243. };
  29244. /**
  29245. * Get a list of meshes by tags
  29246. * @param tagsQuery defines the tags query to use
  29247. * @param forEach defines a predicate used to filter results
  29248. * @returns an array of Mesh
  29249. */
  29250. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29251. return this._getByTags(this.meshes, tagsQuery, forEach);
  29252. };
  29253. /**
  29254. * Get a list of cameras by tags
  29255. * @param tagsQuery defines the tags query to use
  29256. * @param forEach defines a predicate used to filter results
  29257. * @returns an array of Camera
  29258. */
  29259. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29260. return this._getByTags(this.cameras, tagsQuery, forEach);
  29261. };
  29262. /**
  29263. * Get a list of lights by tags
  29264. * @param tagsQuery defines the tags query to use
  29265. * @param forEach defines a predicate used to filter results
  29266. * @returns an array of Light
  29267. */
  29268. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29269. return this._getByTags(this.lights, tagsQuery, forEach);
  29270. };
  29271. /**
  29272. * Get a list of materials by tags
  29273. * @param tagsQuery defines the tags query to use
  29274. * @param forEach defines a predicate used to filter results
  29275. * @returns an array of Material
  29276. */
  29277. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29278. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29279. };
  29280. /**
  29281. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29282. * This allowed control for front to back rendering or reversly depending of the special needs.
  29283. *
  29284. * @param renderingGroupId The rendering group id corresponding to its index
  29285. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29286. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29287. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29288. */
  29289. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29290. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29291. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29292. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29293. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29294. };
  29295. /**
  29296. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29297. *
  29298. * @param renderingGroupId The rendering group id corresponding to its index
  29299. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29300. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29301. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29302. */
  29303. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29304. if (depth === void 0) { depth = true; }
  29305. if (stencil === void 0) { stencil = true; }
  29306. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29307. };
  29308. /**
  29309. * Gets the current auto clear configuration for one rendering group of the rendering
  29310. * manager.
  29311. * @param index the rendering group index to get the information for
  29312. * @returns The auto clear setup for the requested rendering group
  29313. */
  29314. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29315. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29316. };
  29317. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29318. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29319. get: function () {
  29320. return this._blockMaterialDirtyMechanism;
  29321. },
  29322. set: function (value) {
  29323. if (this._blockMaterialDirtyMechanism === value) {
  29324. return;
  29325. }
  29326. this._blockMaterialDirtyMechanism = value;
  29327. if (!value) { // Do a complete update
  29328. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29329. }
  29330. },
  29331. enumerable: true,
  29332. configurable: true
  29333. });
  29334. /**
  29335. * Will flag all materials as dirty to trigger new shader compilation
  29336. * @param flag defines the flag used to specify which material part must be marked as dirty
  29337. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29338. */
  29339. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29340. if (this._blockMaterialDirtyMechanism) {
  29341. return;
  29342. }
  29343. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29344. var material = _a[_i];
  29345. if (predicate && !predicate(material)) {
  29346. continue;
  29347. }
  29348. material.markAsDirty(flag);
  29349. }
  29350. };
  29351. /** @hidden */
  29352. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29353. var _this = this;
  29354. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29355. this._activeRequests.push(request);
  29356. request.onCompleteObservable.add(function (request) {
  29357. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29358. });
  29359. return request;
  29360. };
  29361. /** @hidden */
  29362. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29363. var _this = this;
  29364. return new Promise(function (resolve, reject) {
  29365. _this._loadFile(url, function (data) {
  29366. resolve(data);
  29367. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29368. reject(exception);
  29369. });
  29370. });
  29371. };
  29372. // Statics
  29373. Scene._uniqueIdCounter = 0;
  29374. /** The fog is deactivated */
  29375. Scene.FOGMODE_NONE = 0;
  29376. /** The fog density is following an exponential function */
  29377. Scene.FOGMODE_EXP = 1;
  29378. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29379. Scene.FOGMODE_EXP2 = 2;
  29380. /** The fog density is following a linear function. */
  29381. Scene.FOGMODE_LINEAR = 3;
  29382. /**
  29383. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29384. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29385. */
  29386. Scene.MinDeltaTime = 1.0;
  29387. /**
  29388. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29389. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29390. */
  29391. Scene.MaxDeltaTime = 1000.0;
  29392. /** The distance in pixel that you have to move to prevent some events */
  29393. Scene.DragMovementThreshold = 10; // in pixels
  29394. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29395. Scene.LongPressDelay = 500; // in milliseconds
  29396. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29397. Scene.DoubleClickDelay = 300; // in milliseconds
  29398. /** If you need to check double click without raising a single click at first click, enable this flag */
  29399. Scene.ExclusiveDoubleClickMode = false;
  29400. return Scene;
  29401. }(BABYLON.AbstractScene));
  29402. BABYLON.Scene = Scene;
  29403. })(BABYLON || (BABYLON = {}));
  29404. //# sourceMappingURL=babylon.scene.js.map
  29405. var BABYLON;
  29406. (function (BABYLON) {
  29407. /**
  29408. * Set of assets to keep when moving a scene into an asset container.
  29409. */
  29410. var KeepAssets = /** @class */ (function (_super) {
  29411. __extends(KeepAssets, _super);
  29412. function KeepAssets() {
  29413. return _super !== null && _super.apply(this, arguments) || this;
  29414. }
  29415. return KeepAssets;
  29416. }(BABYLON.AbstractScene));
  29417. BABYLON.KeepAssets = KeepAssets;
  29418. /**
  29419. * Container with a set of assets that can be added or removed from a scene.
  29420. */
  29421. var AssetContainer = /** @class */ (function (_super) {
  29422. __extends(AssetContainer, _super);
  29423. /**
  29424. * Instantiates an AssetContainer.
  29425. * @param scene The scene the AssetContainer belongs to.
  29426. */
  29427. function AssetContainer(scene) {
  29428. var _this = _super.call(this) || this;
  29429. _this.scene = scene;
  29430. return _this;
  29431. }
  29432. /**
  29433. * Adds all the assets from the container to the scene.
  29434. */
  29435. AssetContainer.prototype.addAllToScene = function () {
  29436. var _this = this;
  29437. this.cameras.forEach(function (o) {
  29438. _this.scene.addCamera(o);
  29439. });
  29440. this.lights.forEach(function (o) {
  29441. _this.scene.addLight(o);
  29442. });
  29443. this.meshes.forEach(function (o) {
  29444. _this.scene.addMesh(o);
  29445. });
  29446. this.skeletons.forEach(function (o) {
  29447. _this.scene.addSkeleton(o);
  29448. });
  29449. this.animations.forEach(function (o) {
  29450. _this.scene.addAnimation(o);
  29451. });
  29452. this.animationGroups.forEach(function (o) {
  29453. _this.scene.addAnimationGroup(o);
  29454. });
  29455. this.multiMaterials.forEach(function (o) {
  29456. _this.scene.addMultiMaterial(o);
  29457. });
  29458. this.materials.forEach(function (o) {
  29459. _this.scene.addMaterial(o);
  29460. });
  29461. this.morphTargetManagers.forEach(function (o) {
  29462. _this.scene.addMorphTargetManager(o);
  29463. });
  29464. this.geometries.forEach(function (o) {
  29465. _this.scene.addGeometry(o);
  29466. });
  29467. this.transformNodes.forEach(function (o) {
  29468. _this.scene.addTransformNode(o);
  29469. });
  29470. this.actionManagers.forEach(function (o) {
  29471. _this.scene.addActionManager(o);
  29472. });
  29473. this.textures.forEach(function (o) {
  29474. _this.scene.addTexture(o);
  29475. });
  29476. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29477. var component = _a[_i];
  29478. component.addFromContainer(this.scene);
  29479. }
  29480. };
  29481. /**
  29482. * Removes all the assets in the container from the scene
  29483. */
  29484. AssetContainer.prototype.removeAllFromScene = function () {
  29485. var _this = this;
  29486. this.cameras.forEach(function (o) {
  29487. _this.scene.removeCamera(o);
  29488. });
  29489. this.lights.forEach(function (o) {
  29490. _this.scene.removeLight(o);
  29491. });
  29492. this.meshes.forEach(function (o) {
  29493. _this.scene.removeMesh(o);
  29494. });
  29495. this.skeletons.forEach(function (o) {
  29496. _this.scene.removeSkeleton(o);
  29497. });
  29498. this.animations.forEach(function (o) {
  29499. _this.scene.removeAnimation(o);
  29500. });
  29501. this.animationGroups.forEach(function (o) {
  29502. _this.scene.removeAnimationGroup(o);
  29503. });
  29504. this.multiMaterials.forEach(function (o) {
  29505. _this.scene.removeMultiMaterial(o);
  29506. });
  29507. this.materials.forEach(function (o) {
  29508. _this.scene.removeMaterial(o);
  29509. });
  29510. this.morphTargetManagers.forEach(function (o) {
  29511. _this.scene.removeMorphTargetManager(o);
  29512. });
  29513. this.geometries.forEach(function (o) {
  29514. _this.scene.removeGeometry(o);
  29515. });
  29516. this.transformNodes.forEach(function (o) {
  29517. _this.scene.removeTransformNode(o);
  29518. });
  29519. this.actionManagers.forEach(function (o) {
  29520. _this.scene.removeActionManager(o);
  29521. });
  29522. this.textures.forEach(function (o) {
  29523. _this.scene.removeTexture(o);
  29524. });
  29525. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29526. var component = _a[_i];
  29527. component.removeFromContainer(this.scene);
  29528. }
  29529. };
  29530. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29531. if (!sourceAssets) {
  29532. return;
  29533. }
  29534. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29535. var asset = sourceAssets_1[_i];
  29536. var move = true;
  29537. if (keepAssets) {
  29538. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29539. var keepAsset = keepAssets_1[_a];
  29540. if (asset === keepAsset) {
  29541. move = false;
  29542. break;
  29543. }
  29544. }
  29545. }
  29546. if (move) {
  29547. targetAssets.push(asset);
  29548. }
  29549. }
  29550. };
  29551. /**
  29552. * Removes all the assets contained in the scene and adds them to the container.
  29553. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29554. */
  29555. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29556. if (keepAssets === undefined) {
  29557. keepAssets = new KeepAssets();
  29558. }
  29559. for (var key in this) {
  29560. if (this.hasOwnProperty(key)) {
  29561. this[key] = this[key] || [];
  29562. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29563. }
  29564. }
  29565. this.removeAllFromScene();
  29566. };
  29567. /**
  29568. * 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.
  29569. * @returns the root mesh
  29570. */
  29571. AssetContainer.prototype.createRootMesh = function () {
  29572. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29573. this.meshes.forEach(function (m) {
  29574. if (!m.parent) {
  29575. rootMesh.addChild(m);
  29576. }
  29577. });
  29578. this.meshes.unshift(rootMesh);
  29579. return rootMesh;
  29580. };
  29581. return AssetContainer;
  29582. }(BABYLON.AbstractScene));
  29583. BABYLON.AssetContainer = AssetContainer;
  29584. })(BABYLON || (BABYLON = {}));
  29585. //# sourceMappingURL=babylon.assetContainer.js.map
  29586. var BABYLON;
  29587. (function (BABYLON) {
  29588. /**
  29589. * Class used to store data that will be store in GPU memory
  29590. */
  29591. var Buffer = /** @class */ (function () {
  29592. /**
  29593. * Constructor
  29594. * @param engine the engine
  29595. * @param data the data to use for this buffer
  29596. * @param updatable whether the data is updatable
  29597. * @param stride the stride (optional)
  29598. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29599. * @param instanced whether the buffer is instanced (optional)
  29600. * @param useBytes set to true if the stride in in bytes (optional)
  29601. */
  29602. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29603. if (stride === void 0) { stride = 0; }
  29604. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29605. if (instanced === void 0) { instanced = false; }
  29606. if (useBytes === void 0) { useBytes = false; }
  29607. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29608. this._engine = engine.getScene().getEngine();
  29609. }
  29610. else {
  29611. this._engine = engine;
  29612. }
  29613. this._updatable = updatable;
  29614. this._instanced = instanced;
  29615. this._data = data;
  29616. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29617. if (!postponeInternalCreation) { // by default
  29618. this.create();
  29619. }
  29620. }
  29621. /**
  29622. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29623. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29624. * @param offset defines offset in the buffer (0 by default)
  29625. * @param size defines the size in floats of attributes (position is 3 for instance)
  29626. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29627. * @param instanced defines if the vertex buffer contains indexed data
  29628. * @param useBytes defines if the offset and stride are in bytes
  29629. * @returns the new vertex buffer
  29630. */
  29631. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29632. if (useBytes === void 0) { useBytes = false; }
  29633. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29634. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29635. // a lot of these parameters are ignored as they are overriden by the buffer
  29636. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29637. };
  29638. // Properties
  29639. /**
  29640. * Gets a boolean indicating if the Buffer is updatable?
  29641. * @returns true if the buffer is updatable
  29642. */
  29643. Buffer.prototype.isUpdatable = function () {
  29644. return this._updatable;
  29645. };
  29646. /**
  29647. * Gets current buffer's data
  29648. * @returns a DataArray or null
  29649. */
  29650. Buffer.prototype.getData = function () {
  29651. return this._data;
  29652. };
  29653. /**
  29654. * Gets underlying native buffer
  29655. * @returns underlying native buffer
  29656. */
  29657. Buffer.prototype.getBuffer = function () {
  29658. return this._buffer;
  29659. };
  29660. /**
  29661. * Gets the stride in float32 units (i.e. byte stride / 4).
  29662. * May not be an integer if the byte stride is not divisible by 4.
  29663. * DEPRECATED. Use byteStride instead.
  29664. * @returns the stride in float32 units
  29665. */
  29666. Buffer.prototype.getStrideSize = function () {
  29667. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29668. };
  29669. // Methods
  29670. /**
  29671. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29672. * @param data defines the data to store
  29673. */
  29674. Buffer.prototype.create = function (data) {
  29675. if (data === void 0) { data = null; }
  29676. if (!data && this._buffer) {
  29677. return; // nothing to do
  29678. }
  29679. data = data || this._data;
  29680. if (!data) {
  29681. return;
  29682. }
  29683. if (!this._buffer) { // create buffer
  29684. if (this._updatable) {
  29685. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29686. this._data = data;
  29687. }
  29688. else {
  29689. this._buffer = this._engine.createVertexBuffer(data);
  29690. }
  29691. }
  29692. else if (this._updatable) { // update buffer
  29693. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29694. this._data = data;
  29695. }
  29696. };
  29697. /** @hidden */
  29698. Buffer.prototype._rebuild = function () {
  29699. this._buffer = null;
  29700. this.create(this._data);
  29701. };
  29702. /**
  29703. * Update current buffer data
  29704. * @param data defines the data to store
  29705. */
  29706. Buffer.prototype.update = function (data) {
  29707. this.create(data);
  29708. };
  29709. /**
  29710. * Updates the data directly.
  29711. * @param data the new data
  29712. * @param offset the new offset
  29713. * @param vertexCount the vertex count (optional)
  29714. * @param useBytes set to true if the offset is in bytes
  29715. */
  29716. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29717. if (useBytes === void 0) { useBytes = false; }
  29718. if (!this._buffer) {
  29719. return;
  29720. }
  29721. if (this._updatable) { // update buffer
  29722. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29723. this._data = null;
  29724. }
  29725. };
  29726. /**
  29727. * Release all resources
  29728. */
  29729. Buffer.prototype.dispose = function () {
  29730. if (!this._buffer) {
  29731. return;
  29732. }
  29733. if (this._engine._releaseBuffer(this._buffer)) {
  29734. this._buffer = null;
  29735. }
  29736. };
  29737. return Buffer;
  29738. }());
  29739. BABYLON.Buffer = Buffer;
  29740. })(BABYLON || (BABYLON = {}));
  29741. //# sourceMappingURL=babylon.buffer.js.map
  29742. var BABYLON;
  29743. (function (BABYLON) {
  29744. /**
  29745. * Specialized buffer used to store vertex data
  29746. */
  29747. var VertexBuffer = /** @class */ (function () {
  29748. /**
  29749. * Constructor
  29750. * @param engine the engine
  29751. * @param data the data to use for this vertex buffer
  29752. * @param kind the vertex buffer kind
  29753. * @param updatable whether the data is updatable
  29754. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29755. * @param stride the stride (optional)
  29756. * @param instanced whether the buffer is instanced (optional)
  29757. * @param offset the offset of the data (optional)
  29758. * @param size the number of components (optional)
  29759. * @param type the type of the component (optional)
  29760. * @param normalized whether the data contains normalized data (optional)
  29761. * @param useBytes set to true if stride and offset are in bytes (optional)
  29762. */
  29763. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29764. if (normalized === void 0) { normalized = false; }
  29765. if (useBytes === void 0) { useBytes = false; }
  29766. if (data instanceof BABYLON.Buffer) {
  29767. this._buffer = data;
  29768. this._ownsBuffer = false;
  29769. }
  29770. else {
  29771. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29772. this._ownsBuffer = true;
  29773. }
  29774. this._kind = kind;
  29775. if (type == undefined) {
  29776. var data_1 = this.getData();
  29777. this.type = VertexBuffer.FLOAT;
  29778. if (data_1 instanceof Int8Array)
  29779. this.type = VertexBuffer.BYTE;
  29780. else if (data_1 instanceof Uint8Array)
  29781. this.type = VertexBuffer.UNSIGNED_BYTE;
  29782. else if (data_1 instanceof Int16Array)
  29783. this.type = VertexBuffer.SHORT;
  29784. else if (data_1 instanceof Uint16Array)
  29785. this.type = VertexBuffer.UNSIGNED_SHORT;
  29786. else if (data_1 instanceof Int32Array)
  29787. this.type = VertexBuffer.INT;
  29788. else if (data_1 instanceof Uint32Array)
  29789. this.type = VertexBuffer.UNSIGNED_INT;
  29790. }
  29791. else {
  29792. this.type = type;
  29793. }
  29794. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29795. if (useBytes) {
  29796. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29797. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29798. this.byteOffset = offset || 0;
  29799. }
  29800. else {
  29801. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29802. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29803. this.byteOffset = (offset || 0) * typeByteLength;
  29804. }
  29805. this.normalized = normalized;
  29806. this._instanced = instanced !== undefined ? instanced : false;
  29807. this._instanceDivisor = instanced ? 1 : 0;
  29808. }
  29809. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29810. /**
  29811. * Gets or sets the instance divisor when in instanced mode
  29812. */
  29813. get: function () {
  29814. return this._instanceDivisor;
  29815. },
  29816. set: function (value) {
  29817. this._instanceDivisor = value;
  29818. if (value == 0) {
  29819. this._instanced = false;
  29820. }
  29821. else {
  29822. this._instanced = true;
  29823. }
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. /** @hidden */
  29829. VertexBuffer.prototype._rebuild = function () {
  29830. if (!this._buffer) {
  29831. return;
  29832. }
  29833. this._buffer._rebuild();
  29834. };
  29835. /**
  29836. * Returns the kind of the VertexBuffer (string)
  29837. * @returns a string
  29838. */
  29839. VertexBuffer.prototype.getKind = function () {
  29840. return this._kind;
  29841. };
  29842. // Properties
  29843. /**
  29844. * Gets a boolean indicating if the VertexBuffer is updatable?
  29845. * @returns true if the buffer is updatable
  29846. */
  29847. VertexBuffer.prototype.isUpdatable = function () {
  29848. return this._buffer.isUpdatable();
  29849. };
  29850. /**
  29851. * Gets current buffer's data
  29852. * @returns a DataArray or null
  29853. */
  29854. VertexBuffer.prototype.getData = function () {
  29855. return this._buffer.getData();
  29856. };
  29857. /**
  29858. * Gets underlying native buffer
  29859. * @returns underlying native buffer
  29860. */
  29861. VertexBuffer.prototype.getBuffer = function () {
  29862. return this._buffer.getBuffer();
  29863. };
  29864. /**
  29865. * Gets the stride in float32 units (i.e. byte stride / 4).
  29866. * May not be an integer if the byte stride is not divisible by 4.
  29867. * DEPRECATED. Use byteStride instead.
  29868. * @returns the stride in float32 units
  29869. */
  29870. VertexBuffer.prototype.getStrideSize = function () {
  29871. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29872. };
  29873. /**
  29874. * Returns the offset as a multiple of the type byte length.
  29875. * DEPRECATED. Use byteOffset instead.
  29876. * @returns the offset in bytes
  29877. */
  29878. VertexBuffer.prototype.getOffset = function () {
  29879. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29880. };
  29881. /**
  29882. * Returns the number of components per vertex attribute (integer)
  29883. * @returns the size in float
  29884. */
  29885. VertexBuffer.prototype.getSize = function () {
  29886. return this._size;
  29887. };
  29888. /**
  29889. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29890. * @returns true if this buffer is instanced
  29891. */
  29892. VertexBuffer.prototype.getIsInstanced = function () {
  29893. return this._instanced;
  29894. };
  29895. /**
  29896. * Returns the instancing divisor, zero for non-instanced (integer).
  29897. * @returns a number
  29898. */
  29899. VertexBuffer.prototype.getInstanceDivisor = function () {
  29900. return this._instanceDivisor;
  29901. };
  29902. // Methods
  29903. /**
  29904. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29905. * @param data defines the data to store
  29906. */
  29907. VertexBuffer.prototype.create = function (data) {
  29908. this._buffer.create(data);
  29909. };
  29910. /**
  29911. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29912. * This function will create a new buffer if the current one is not updatable
  29913. * @param data defines the data to store
  29914. */
  29915. VertexBuffer.prototype.update = function (data) {
  29916. this._buffer.update(data);
  29917. };
  29918. /**
  29919. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29920. * Returns the directly updated WebGLBuffer.
  29921. * @param data the new data
  29922. * @param offset the new offset
  29923. * @param useBytes set to true if the offset is in bytes
  29924. */
  29925. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29926. if (useBytes === void 0) { useBytes = false; }
  29927. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29928. };
  29929. /**
  29930. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29931. */
  29932. VertexBuffer.prototype.dispose = function () {
  29933. if (this._ownsBuffer) {
  29934. this._buffer.dispose();
  29935. }
  29936. };
  29937. /**
  29938. * Enumerates each value of this vertex buffer as numbers.
  29939. * @param count the number of values to enumerate
  29940. * @param callback the callback function called for each value
  29941. */
  29942. VertexBuffer.prototype.forEach = function (count, callback) {
  29943. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29944. };
  29945. /**
  29946. * Deduces the stride given a kind.
  29947. * @param kind The kind string to deduce
  29948. * @returns The deduced stride
  29949. */
  29950. VertexBuffer.DeduceStride = function (kind) {
  29951. switch (kind) {
  29952. case VertexBuffer.UVKind:
  29953. case VertexBuffer.UV2Kind:
  29954. case VertexBuffer.UV3Kind:
  29955. case VertexBuffer.UV4Kind:
  29956. case VertexBuffer.UV5Kind:
  29957. case VertexBuffer.UV6Kind:
  29958. return 2;
  29959. case VertexBuffer.NormalKind:
  29960. case VertexBuffer.PositionKind:
  29961. return 3;
  29962. case VertexBuffer.ColorKind:
  29963. case VertexBuffer.MatricesIndicesKind:
  29964. case VertexBuffer.MatricesIndicesExtraKind:
  29965. case VertexBuffer.MatricesWeightsKind:
  29966. case VertexBuffer.MatricesWeightsExtraKind:
  29967. case VertexBuffer.TangentKind:
  29968. return 4;
  29969. default:
  29970. throw new Error("Invalid kind '" + kind + "'");
  29971. }
  29972. };
  29973. /**
  29974. * Gets the byte length of the given type.
  29975. * @param type the type
  29976. * @returns the number of bytes
  29977. */
  29978. VertexBuffer.GetTypeByteLength = function (type) {
  29979. switch (type) {
  29980. case VertexBuffer.BYTE:
  29981. case VertexBuffer.UNSIGNED_BYTE:
  29982. return 1;
  29983. case VertexBuffer.SHORT:
  29984. case VertexBuffer.UNSIGNED_SHORT:
  29985. return 2;
  29986. case VertexBuffer.INT:
  29987. case VertexBuffer.FLOAT:
  29988. return 4;
  29989. default:
  29990. throw new Error("Invalid type '" + type + "'");
  29991. }
  29992. };
  29993. /**
  29994. * Enumerates each value of the given parameters as numbers.
  29995. * @param data the data to enumerate
  29996. * @param byteOffset the byte offset of the data
  29997. * @param byteStride the byte stride of the data
  29998. * @param componentCount the number of components per element
  29999. * @param componentType the type of the component
  30000. * @param count the total number of components
  30001. * @param normalized whether the data is normalized
  30002. * @param callback the callback function called for each value
  30003. */
  30004. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30005. if (data instanceof Array) {
  30006. var offset = byteOffset / 4;
  30007. var stride = byteStride / 4;
  30008. for (var index = 0; index < count; index += componentCount) {
  30009. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30010. callback(data[offset + componentIndex], index + componentIndex);
  30011. }
  30012. offset += stride;
  30013. }
  30014. }
  30015. else {
  30016. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30017. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30018. for (var index = 0; index < count; index += componentCount) {
  30019. var componentByteOffset = byteOffset;
  30020. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30021. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30022. callback(value, index + componentIndex);
  30023. componentByteOffset += componentByteLength;
  30024. }
  30025. byteOffset += byteStride;
  30026. }
  30027. }
  30028. };
  30029. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30030. switch (type) {
  30031. case VertexBuffer.BYTE: {
  30032. var value = dataView.getInt8(byteOffset);
  30033. if (normalized) {
  30034. value = Math.max(value / 127, -1);
  30035. }
  30036. return value;
  30037. }
  30038. case VertexBuffer.UNSIGNED_BYTE: {
  30039. var value = dataView.getUint8(byteOffset);
  30040. if (normalized) {
  30041. value = value / 255;
  30042. }
  30043. return value;
  30044. }
  30045. case VertexBuffer.SHORT: {
  30046. var value = dataView.getInt16(byteOffset, true);
  30047. if (normalized) {
  30048. value = Math.max(value / 16383, -1);
  30049. }
  30050. return value;
  30051. }
  30052. case VertexBuffer.UNSIGNED_SHORT: {
  30053. var value = dataView.getUint16(byteOffset, true);
  30054. if (normalized) {
  30055. value = value / 65535;
  30056. }
  30057. return value;
  30058. }
  30059. case VertexBuffer.FLOAT: {
  30060. return dataView.getFloat32(byteOffset, true);
  30061. }
  30062. default: {
  30063. throw new Error("Invalid component type " + type);
  30064. }
  30065. }
  30066. };
  30067. /**
  30068. * The byte type.
  30069. */
  30070. VertexBuffer.BYTE = 5120;
  30071. /**
  30072. * The unsigned byte type.
  30073. */
  30074. VertexBuffer.UNSIGNED_BYTE = 5121;
  30075. /**
  30076. * The short type.
  30077. */
  30078. VertexBuffer.SHORT = 5122;
  30079. /**
  30080. * The unsigned short type.
  30081. */
  30082. VertexBuffer.UNSIGNED_SHORT = 5123;
  30083. /**
  30084. * The integer type.
  30085. */
  30086. VertexBuffer.INT = 5124;
  30087. /**
  30088. * The unsigned integer type.
  30089. */
  30090. VertexBuffer.UNSIGNED_INT = 5125;
  30091. /**
  30092. * The float type.
  30093. */
  30094. VertexBuffer.FLOAT = 5126;
  30095. // Enums
  30096. /**
  30097. * Positions
  30098. */
  30099. VertexBuffer.PositionKind = "position";
  30100. /**
  30101. * Normals
  30102. */
  30103. VertexBuffer.NormalKind = "normal";
  30104. /**
  30105. * Tangents
  30106. */
  30107. VertexBuffer.TangentKind = "tangent";
  30108. /**
  30109. * Texture coordinates
  30110. */
  30111. VertexBuffer.UVKind = "uv";
  30112. /**
  30113. * Texture coordinates 2
  30114. */
  30115. VertexBuffer.UV2Kind = "uv2";
  30116. /**
  30117. * Texture coordinates 3
  30118. */
  30119. VertexBuffer.UV3Kind = "uv3";
  30120. /**
  30121. * Texture coordinates 4
  30122. */
  30123. VertexBuffer.UV4Kind = "uv4";
  30124. /**
  30125. * Texture coordinates 5
  30126. */
  30127. VertexBuffer.UV5Kind = "uv5";
  30128. /**
  30129. * Texture coordinates 6
  30130. */
  30131. VertexBuffer.UV6Kind = "uv6";
  30132. /**
  30133. * Colors
  30134. */
  30135. VertexBuffer.ColorKind = "color";
  30136. /**
  30137. * Matrix indices (for bones)
  30138. */
  30139. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30140. /**
  30141. * Matrix weights (for bones)
  30142. */
  30143. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30144. /**
  30145. * Additional matrix indices (for bones)
  30146. */
  30147. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30148. /**
  30149. * Additional matrix weights (for bones)
  30150. */
  30151. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30152. return VertexBuffer;
  30153. }());
  30154. BABYLON.VertexBuffer = VertexBuffer;
  30155. })(BABYLON || (BABYLON = {}));
  30156. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30157. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30158. var BABYLON;
  30159. (function (BABYLON) {
  30160. /**
  30161. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30162. */
  30163. var DummyInternalTextureTracker = /** @class */ (function () {
  30164. function DummyInternalTextureTracker() {
  30165. /**
  30166. * Gets or set the previous tracker in the list
  30167. */
  30168. this.previous = null;
  30169. /**
  30170. * Gets or set the next tracker in the list
  30171. */
  30172. this.next = null;
  30173. }
  30174. return DummyInternalTextureTracker;
  30175. }());
  30176. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30177. })(BABYLON || (BABYLON = {}));
  30178. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30179. var BABYLON;
  30180. (function (BABYLON) {
  30181. /**
  30182. * Class used to store data associated with WebGL texture data for the engine
  30183. * This class should not be used directly
  30184. */
  30185. var InternalTexture = /** @class */ (function () {
  30186. /**
  30187. * Creates a new InternalTexture
  30188. * @param engine defines the engine to use
  30189. * @param dataSource defines the type of data that will be used
  30190. */
  30191. function InternalTexture(engine, dataSource) {
  30192. /**
  30193. * Observable called when the texture is loaded
  30194. */
  30195. this.onLoadedObservable = new BABYLON.Observable();
  30196. /**
  30197. * Gets or set the previous tracker in the list
  30198. */
  30199. this.previous = null;
  30200. /**
  30201. * Gets or set the next tracker in the list
  30202. */
  30203. this.next = null;
  30204. // Private
  30205. /** @hidden */
  30206. this._initialSlot = -1;
  30207. /** @hidden */
  30208. this._designatedSlot = -1;
  30209. /** @hidden */
  30210. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30211. /** @hidden */
  30212. this._comparisonFunction = 0;
  30213. /** @hidden */
  30214. this._sphericalPolynomial = null;
  30215. /** @hidden */
  30216. this._lodGenerationScale = 0;
  30217. /** @hidden */
  30218. this._lodGenerationOffset = 0;
  30219. /** @hidden */
  30220. this._isRGBD = false;
  30221. /** @hidden */
  30222. this._references = 1;
  30223. this._engine = engine;
  30224. this._dataSource = dataSource;
  30225. this._webGLTexture = engine._createTexture();
  30226. }
  30227. /**
  30228. * Gets the Engine the texture belongs to.
  30229. * @returns The babylon engine
  30230. */
  30231. InternalTexture.prototype.getEngine = function () {
  30232. return this._engine;
  30233. };
  30234. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30235. /**
  30236. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30237. */
  30238. get: function () {
  30239. return this._dataSource;
  30240. },
  30241. enumerable: true,
  30242. configurable: true
  30243. });
  30244. /**
  30245. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30246. */
  30247. InternalTexture.prototype.incrementReferences = function () {
  30248. this._references++;
  30249. };
  30250. /**
  30251. * Change the size of the texture (not the size of the content)
  30252. * @param width defines the new width
  30253. * @param height defines the new height
  30254. * @param depth defines the new depth (1 by default)
  30255. */
  30256. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30257. if (depth === void 0) { depth = 1; }
  30258. this.width = width;
  30259. this.height = height;
  30260. this.depth = depth;
  30261. this.baseWidth = width;
  30262. this.baseHeight = height;
  30263. this.baseDepth = depth;
  30264. this._size = width * height * depth;
  30265. };
  30266. /** @hidden */
  30267. InternalTexture.prototype._rebuild = function () {
  30268. var _this = this;
  30269. var proxy;
  30270. this.isReady = false;
  30271. this._cachedCoordinatesMode = null;
  30272. this._cachedWrapU = null;
  30273. this._cachedWrapV = null;
  30274. this._cachedAnisotropicFilteringLevel = null;
  30275. switch (this._dataSource) {
  30276. case InternalTexture.DATASOURCE_TEMP:
  30277. return;
  30278. case InternalTexture.DATASOURCE_URL:
  30279. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30280. _this.isReady = true;
  30281. }, null, this._buffer, undefined, this.format);
  30282. proxy._swapAndDie(this);
  30283. return;
  30284. case InternalTexture.DATASOURCE_RAW:
  30285. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30286. proxy._swapAndDie(this);
  30287. this.isReady = true;
  30288. return;
  30289. case InternalTexture.DATASOURCE_RAW3D:
  30290. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30291. proxy._swapAndDie(this);
  30292. this.isReady = true;
  30293. return;
  30294. case InternalTexture.DATASOURCE_DYNAMIC:
  30295. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30296. proxy._swapAndDie(this);
  30297. // The engine will make sure to update content so no need to flag it as isReady = true
  30298. return;
  30299. case InternalTexture.DATASOURCE_RENDERTARGET:
  30300. var options = new BABYLON.RenderTargetCreationOptions();
  30301. options.generateDepthBuffer = this._generateDepthBuffer;
  30302. options.generateMipMaps = this.generateMipMaps;
  30303. options.generateStencilBuffer = this._generateStencilBuffer;
  30304. options.samplingMode = this.samplingMode;
  30305. options.type = this.type;
  30306. if (this.isCube) {
  30307. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30308. }
  30309. else {
  30310. var size = {
  30311. width: this.width,
  30312. height: this.height
  30313. };
  30314. proxy = this._engine.createRenderTargetTexture(size, options);
  30315. }
  30316. proxy._swapAndDie(this);
  30317. this.isReady = true;
  30318. return;
  30319. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30320. var depthTextureOptions = {
  30321. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30322. comparisonFunction: this._comparisonFunction,
  30323. generateStencil: this._generateStencilBuffer,
  30324. isCube: this.isCube
  30325. };
  30326. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30327. proxy._swapAndDie(this);
  30328. this.isReady = true;
  30329. return;
  30330. case InternalTexture.DATASOURCE_CUBE:
  30331. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30332. _this.isReady = true;
  30333. }, null, this.format, this._extension);
  30334. proxy._swapAndDie(this);
  30335. return;
  30336. case InternalTexture.DATASOURCE_CUBERAW:
  30337. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30338. proxy._swapAndDie(this);
  30339. this.isReady = true;
  30340. return;
  30341. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30342. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30343. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30344. _this.isReady = true;
  30345. });
  30346. proxy._swapAndDie(this);
  30347. return;
  30348. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30349. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30350. if (proxy) {
  30351. proxy._swapAndDie(_this);
  30352. }
  30353. _this.isReady = true;
  30354. }, null, this.format, this._extension);
  30355. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30356. return;
  30357. }
  30358. };
  30359. /** @hidden */
  30360. InternalTexture.prototype._swapAndDie = function (target) {
  30361. target._webGLTexture = this._webGLTexture;
  30362. if (this._framebuffer) {
  30363. target._framebuffer = this._framebuffer;
  30364. }
  30365. if (this._depthStencilBuffer) {
  30366. target._depthStencilBuffer = this._depthStencilBuffer;
  30367. }
  30368. if (this._lodTextureHigh) {
  30369. if (target._lodTextureHigh) {
  30370. target._lodTextureHigh.dispose();
  30371. }
  30372. target._lodTextureHigh = this._lodTextureHigh;
  30373. }
  30374. if (this._lodTextureMid) {
  30375. if (target._lodTextureMid) {
  30376. target._lodTextureMid.dispose();
  30377. }
  30378. target._lodTextureMid = this._lodTextureMid;
  30379. }
  30380. if (this._lodTextureLow) {
  30381. if (target._lodTextureLow) {
  30382. target._lodTextureLow.dispose();
  30383. }
  30384. target._lodTextureLow = this._lodTextureLow;
  30385. }
  30386. var cache = this._engine.getLoadedTexturesCache();
  30387. var index = cache.indexOf(this);
  30388. if (index !== -1) {
  30389. cache.splice(index, 1);
  30390. }
  30391. };
  30392. /**
  30393. * Dispose the current allocated resources
  30394. */
  30395. InternalTexture.prototype.dispose = function () {
  30396. if (!this._webGLTexture) {
  30397. return;
  30398. }
  30399. this._references--;
  30400. if (this._references === 0) {
  30401. this._engine._releaseTexture(this);
  30402. this._webGLTexture = null;
  30403. this.previous = null;
  30404. this.next = null;
  30405. }
  30406. };
  30407. /**
  30408. * The source of the texture data is unknown
  30409. */
  30410. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30411. /**
  30412. * Texture data comes from an URL
  30413. */
  30414. InternalTexture.DATASOURCE_URL = 1;
  30415. /**
  30416. * Texture data is only used for temporary storage
  30417. */
  30418. InternalTexture.DATASOURCE_TEMP = 2;
  30419. /**
  30420. * Texture data comes from raw data (ArrayBuffer)
  30421. */
  30422. InternalTexture.DATASOURCE_RAW = 3;
  30423. /**
  30424. * Texture content is dynamic (video or dynamic texture)
  30425. */
  30426. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30427. /**
  30428. * Texture content is generated by rendering to it
  30429. */
  30430. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30431. /**
  30432. * Texture content is part of a multi render target process
  30433. */
  30434. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30435. /**
  30436. * Texture data comes from a cube data file
  30437. */
  30438. InternalTexture.DATASOURCE_CUBE = 7;
  30439. /**
  30440. * Texture data comes from a raw cube data
  30441. */
  30442. InternalTexture.DATASOURCE_CUBERAW = 8;
  30443. /**
  30444. * Texture data come from a prefiltered cube data file
  30445. */
  30446. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30447. /**
  30448. * Texture content is raw 3D data
  30449. */
  30450. InternalTexture.DATASOURCE_RAW3D = 10;
  30451. /**
  30452. * Texture content is a depth texture
  30453. */
  30454. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30455. /**
  30456. * Texture data comes from a raw cube data encoded with RGBD
  30457. */
  30458. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30459. return InternalTexture;
  30460. }());
  30461. BABYLON.InternalTexture = InternalTexture;
  30462. })(BABYLON || (BABYLON = {}));
  30463. //# sourceMappingURL=babylon.internalTexture.js.map
  30464. var BABYLON;
  30465. (function (BABYLON) {
  30466. var BaseTexture = /** @class */ (function () {
  30467. function BaseTexture(scene) {
  30468. this._hasAlpha = false;
  30469. this.getAlphaFromRGB = false;
  30470. this.level = 1;
  30471. this.coordinatesIndex = 0;
  30472. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30473. /**
  30474. * | Value | Type | Description |
  30475. * | ----- | ------------------ | ----------- |
  30476. * | 0 | CLAMP_ADDRESSMODE | |
  30477. * | 1 | WRAP_ADDRESSMODE | |
  30478. * | 2 | MIRROR_ADDRESSMODE | |
  30479. */
  30480. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30481. /**
  30482. * | Value | Type | Description |
  30483. * | ----- | ------------------ | ----------- |
  30484. * | 0 | CLAMP_ADDRESSMODE | |
  30485. * | 1 | WRAP_ADDRESSMODE | |
  30486. * | 2 | MIRROR_ADDRESSMODE | |
  30487. */
  30488. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30489. /**
  30490. * | Value | Type | Description |
  30491. * | ----- | ------------------ | ----------- |
  30492. * | 0 | CLAMP_ADDRESSMODE | |
  30493. * | 1 | WRAP_ADDRESSMODE | |
  30494. * | 2 | MIRROR_ADDRESSMODE | |
  30495. */
  30496. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30497. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30498. this.isCube = false;
  30499. this.is3D = false;
  30500. this.gammaSpace = true;
  30501. this.invertZ = false;
  30502. this.lodLevelInAlpha = false;
  30503. this.isRenderTarget = false;
  30504. this.animations = new Array();
  30505. /**
  30506. * An event triggered when the texture is disposed.
  30507. */
  30508. this.onDisposeObservable = new BABYLON.Observable();
  30509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30510. this._cachedSize = BABYLON.Size.Zero();
  30511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30512. if (this._scene) {
  30513. this._scene.textures.push(this);
  30514. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30515. }
  30516. this._uid = null;
  30517. }
  30518. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30519. get: function () {
  30520. return this._hasAlpha;
  30521. },
  30522. set: function (value) {
  30523. if (this._hasAlpha === value) {
  30524. return;
  30525. }
  30526. this._hasAlpha = value;
  30527. if (this._scene) {
  30528. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30529. }
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30535. get: function () {
  30536. return this._coordinatesMode;
  30537. },
  30538. /**
  30539. * How a texture is mapped.
  30540. *
  30541. * | Value | Type | Description |
  30542. * | ----- | ----------------------------------- | ----------- |
  30543. * | 0 | EXPLICIT_MODE | |
  30544. * | 1 | SPHERICAL_MODE | |
  30545. * | 2 | PLANAR_MODE | |
  30546. * | 3 | CUBIC_MODE | |
  30547. * | 4 | PROJECTION_MODE | |
  30548. * | 5 | SKYBOX_MODE | |
  30549. * | 6 | INVCUBIC_MODE | |
  30550. * | 7 | EQUIRECTANGULAR_MODE | |
  30551. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30552. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30553. */
  30554. set: function (value) {
  30555. if (this._coordinatesMode === value) {
  30556. return;
  30557. }
  30558. this._coordinatesMode = value;
  30559. if (this._scene) {
  30560. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30561. }
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30567. /**
  30568. * Gets whether or not the texture contains RGBD data.
  30569. */
  30570. get: function () {
  30571. return this._texture != null && this._texture._isRGBD;
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30577. get: function () {
  30578. if (this._texture)
  30579. return this._texture._lodGenerationOffset;
  30580. return 0.0;
  30581. },
  30582. set: function (value) {
  30583. if (this._texture)
  30584. this._texture._lodGenerationOffset = value;
  30585. },
  30586. enumerable: true,
  30587. configurable: true
  30588. });
  30589. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30590. get: function () {
  30591. if (this._texture)
  30592. return this._texture._lodGenerationScale;
  30593. return 0.0;
  30594. },
  30595. set: function (value) {
  30596. if (this._texture)
  30597. this._texture._lodGenerationScale = value;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(BaseTexture.prototype, "uid", {
  30603. get: function () {
  30604. if (!this._uid) {
  30605. this._uid = BABYLON.Tools.RandomId();
  30606. }
  30607. return this._uid;
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. BaseTexture.prototype.toString = function () {
  30613. return this.name;
  30614. };
  30615. BaseTexture.prototype.getClassName = function () {
  30616. return "BaseTexture";
  30617. };
  30618. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30619. set: function (callback) {
  30620. if (this._onDisposeObserver) {
  30621. this.onDisposeObservable.remove(this._onDisposeObserver);
  30622. }
  30623. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30624. },
  30625. enumerable: true,
  30626. configurable: true
  30627. });
  30628. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30629. get: function () {
  30630. return true;
  30631. },
  30632. enumerable: true,
  30633. configurable: true
  30634. });
  30635. BaseTexture.prototype.getScene = function () {
  30636. return this._scene;
  30637. };
  30638. BaseTexture.prototype.getTextureMatrix = function () {
  30639. return BABYLON.Matrix.IdentityReadOnly;
  30640. };
  30641. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30642. return BABYLON.Matrix.IdentityReadOnly;
  30643. };
  30644. BaseTexture.prototype.getInternalTexture = function () {
  30645. return this._texture;
  30646. };
  30647. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30648. return !this.isBlocking || this.isReady();
  30649. };
  30650. BaseTexture.prototype.isReady = function () {
  30651. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30652. this.delayLoad();
  30653. return false;
  30654. }
  30655. if (this._texture) {
  30656. return this._texture.isReady;
  30657. }
  30658. return false;
  30659. };
  30660. BaseTexture.prototype.getSize = function () {
  30661. if (this._texture) {
  30662. if (this._texture.width) {
  30663. this._cachedSize.width = this._texture.width;
  30664. this._cachedSize.height = this._texture.height;
  30665. return this._cachedSize;
  30666. }
  30667. if (this._texture._size) {
  30668. this._cachedSize.width = this._texture._size;
  30669. this._cachedSize.height = this._texture._size;
  30670. return this._cachedSize;
  30671. }
  30672. }
  30673. return this._cachedSize;
  30674. };
  30675. BaseTexture.prototype.getBaseSize = function () {
  30676. if (!this.isReady() || !this._texture)
  30677. return BABYLON.Size.Zero();
  30678. if (this._texture._size) {
  30679. return new BABYLON.Size(this._texture._size, this._texture._size);
  30680. }
  30681. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30682. };
  30683. BaseTexture.prototype.scale = function (ratio) {
  30684. };
  30685. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30686. get: function () {
  30687. return false;
  30688. },
  30689. enumerable: true,
  30690. configurable: true
  30691. });
  30692. /** @hidden */
  30693. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30694. if (!this._scene) {
  30695. return null;
  30696. }
  30697. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30698. for (var index = 0; index < texturesCache.length; index++) {
  30699. var texturesCacheEntry = texturesCache[index];
  30700. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30701. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30702. texturesCacheEntry.incrementReferences();
  30703. return texturesCacheEntry;
  30704. }
  30705. }
  30706. }
  30707. return null;
  30708. };
  30709. /** @hidden */
  30710. BaseTexture.prototype._rebuild = function () {
  30711. };
  30712. BaseTexture.prototype.delayLoad = function () {
  30713. };
  30714. BaseTexture.prototype.clone = function () {
  30715. return null;
  30716. };
  30717. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30718. get: function () {
  30719. if (!this._texture) {
  30720. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30721. }
  30722. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30728. get: function () {
  30729. if (!this._texture) {
  30730. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30731. }
  30732. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30733. },
  30734. enumerable: true,
  30735. configurable: true
  30736. });
  30737. /**
  30738. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30739. * This will returns an RGBA array buffer containing either in values (0-255) or
  30740. * float values (0-1) depending of the underlying buffer type.
  30741. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30742. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30743. * @param buffer defines a user defined buffer to fill with data (can be null)
  30744. * @returns The Array buffer containing the pixels data.
  30745. */
  30746. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30747. if (faceIndex === void 0) { faceIndex = 0; }
  30748. if (level === void 0) { level = 0; }
  30749. if (buffer === void 0) { buffer = null; }
  30750. if (!this._texture) {
  30751. return null;
  30752. }
  30753. var size = this.getSize();
  30754. var width = size.width;
  30755. var height = size.height;
  30756. var scene = this.getScene();
  30757. if (!scene) {
  30758. return null;
  30759. }
  30760. var engine = scene.getEngine();
  30761. if (level != 0) {
  30762. width = width / Math.pow(2, level);
  30763. height = height / Math.pow(2, level);
  30764. width = Math.round(width);
  30765. height = Math.round(height);
  30766. }
  30767. if (this._texture.isCube) {
  30768. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30769. }
  30770. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30771. };
  30772. BaseTexture.prototype.releaseInternalTexture = function () {
  30773. if (this._texture) {
  30774. this._texture.dispose();
  30775. this._texture = null;
  30776. }
  30777. };
  30778. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30779. get: function () {
  30780. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30781. return null;
  30782. }
  30783. if (!this._texture._sphericalPolynomial) {
  30784. this._texture._sphericalPolynomial =
  30785. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30786. }
  30787. return this._texture._sphericalPolynomial;
  30788. },
  30789. set: function (value) {
  30790. if (this._texture) {
  30791. this._texture._sphericalPolynomial = value;
  30792. }
  30793. },
  30794. enumerable: true,
  30795. configurable: true
  30796. });
  30797. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30798. get: function () {
  30799. if (this._texture) {
  30800. return this._texture._lodTextureHigh;
  30801. }
  30802. return null;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30808. get: function () {
  30809. if (this._texture) {
  30810. return this._texture._lodTextureMid;
  30811. }
  30812. return null;
  30813. },
  30814. enumerable: true,
  30815. configurable: true
  30816. });
  30817. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30818. get: function () {
  30819. if (this._texture) {
  30820. return this._texture._lodTextureLow;
  30821. }
  30822. return null;
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. BaseTexture.prototype.dispose = function () {
  30828. if (!this._scene) {
  30829. return;
  30830. }
  30831. // Animations
  30832. this._scene.stopAnimation(this);
  30833. // Remove from scene
  30834. this._scene._removePendingData(this);
  30835. var index = this._scene.textures.indexOf(this);
  30836. if (index >= 0) {
  30837. this._scene.textures.splice(index, 1);
  30838. }
  30839. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30840. if (this._texture === undefined) {
  30841. return;
  30842. }
  30843. // Release
  30844. this.releaseInternalTexture();
  30845. // Callback
  30846. this.onDisposeObservable.notifyObservers(this);
  30847. this.onDisposeObservable.clear();
  30848. };
  30849. BaseTexture.prototype.serialize = function () {
  30850. if (!this.name) {
  30851. return null;
  30852. }
  30853. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30854. // Animations
  30855. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30856. return serializationObject;
  30857. };
  30858. BaseTexture.WhenAllReady = function (textures, callback) {
  30859. var numRemaining = textures.length;
  30860. if (numRemaining === 0) {
  30861. callback();
  30862. return;
  30863. }
  30864. var _loop_1 = function () {
  30865. texture = textures[i];
  30866. if (texture.isReady()) {
  30867. if (--numRemaining === 0) {
  30868. callback();
  30869. }
  30870. }
  30871. else {
  30872. onLoadObservable = texture.onLoadObservable;
  30873. var onLoadCallback_1 = function () {
  30874. onLoadObservable.removeCallback(onLoadCallback_1);
  30875. if (--numRemaining === 0) {
  30876. callback();
  30877. }
  30878. };
  30879. onLoadObservable.add(onLoadCallback_1);
  30880. }
  30881. };
  30882. var texture, onLoadObservable;
  30883. for (var i = 0; i < textures.length; i++) {
  30884. _loop_1();
  30885. }
  30886. };
  30887. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], BaseTexture.prototype, "name", void 0);
  30891. __decorate([
  30892. BABYLON.serialize("hasAlpha")
  30893. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], BaseTexture.prototype, "level", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30903. __decorate([
  30904. BABYLON.serialize("coordinatesMode")
  30905. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], BaseTexture.prototype, "wrapU", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], BaseTexture.prototype, "wrapV", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], BaseTexture.prototype, "wrapR", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], BaseTexture.prototype, "isCube", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], BaseTexture.prototype, "is3D", void 0);
  30924. __decorate([
  30925. BABYLON.serialize()
  30926. ], BaseTexture.prototype, "gammaSpace", void 0);
  30927. __decorate([
  30928. BABYLON.serialize()
  30929. ], BaseTexture.prototype, "invertZ", void 0);
  30930. __decorate([
  30931. BABYLON.serialize()
  30932. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], BaseTexture.prototype, "lodGenerationScale", null);
  30939. __decorate([
  30940. BABYLON.serialize()
  30941. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30942. return BaseTexture;
  30943. }());
  30944. BABYLON.BaseTexture = BaseTexture;
  30945. })(BABYLON || (BABYLON = {}));
  30946. //# sourceMappingURL=babylon.baseTexture.js.map
  30947. var BABYLON;
  30948. (function (BABYLON) {
  30949. var Texture = /** @class */ (function (_super) {
  30950. __extends(Texture, _super);
  30951. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30952. if (noMipmap === void 0) { noMipmap = false; }
  30953. if (invertY === void 0) { invertY = true; }
  30954. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30955. if (onLoad === void 0) { onLoad = null; }
  30956. if (onError === void 0) { onError = null; }
  30957. if (buffer === void 0) { buffer = null; }
  30958. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30959. var _this = _super.call(this, scene) || this;
  30960. _this.uOffset = 0;
  30961. _this.vOffset = 0;
  30962. _this.uScale = 1.0;
  30963. _this.vScale = 1.0;
  30964. _this.uAng = 0;
  30965. _this.vAng = 0;
  30966. _this.wAng = 0;
  30967. /**
  30968. * Defines the center of rotation (U)
  30969. */
  30970. _this.uRotationCenter = 0.5;
  30971. /**
  30972. * Defines the center of rotation (V)
  30973. */
  30974. _this.vRotationCenter = 0.5;
  30975. /**
  30976. * Defines the center of rotation (W)
  30977. */
  30978. _this.wRotationCenter = 0.5;
  30979. _this._isBlocking = true;
  30980. _this.name = url || "";
  30981. _this.url = url;
  30982. _this._noMipmap = noMipmap;
  30983. _this._invertY = invertY;
  30984. _this._samplingMode = samplingMode;
  30985. _this._buffer = buffer;
  30986. _this._deleteBuffer = deleteBuffer;
  30987. if (format) {
  30988. _this._format = format;
  30989. }
  30990. scene = _this.getScene();
  30991. if (!scene) {
  30992. return _this;
  30993. }
  30994. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30995. var load = function () {
  30996. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30997. _this.onLoadObservable.notifyObservers(_this);
  30998. }
  30999. if (onLoad) {
  31000. onLoad();
  31001. }
  31002. if (!_this.isBlocking && scene) {
  31003. scene.resetCachedMaterial();
  31004. }
  31005. };
  31006. if (!_this.url) {
  31007. _this._delayedOnLoad = load;
  31008. _this._delayedOnError = onError;
  31009. return _this;
  31010. }
  31011. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31012. if (!_this._texture) {
  31013. if (!scene.useDelayedTextureLoading) {
  31014. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31015. if (deleteBuffer) {
  31016. delete _this._buffer;
  31017. }
  31018. }
  31019. else {
  31020. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31021. _this._delayedOnLoad = load;
  31022. _this._delayedOnError = onError;
  31023. }
  31024. }
  31025. else {
  31026. if (_this._texture.isReady) {
  31027. BABYLON.Tools.SetImmediate(function () { return load(); });
  31028. }
  31029. else {
  31030. _this._texture.onLoadedObservable.add(load);
  31031. }
  31032. }
  31033. return _this;
  31034. }
  31035. Object.defineProperty(Texture.prototype, "noMipmap", {
  31036. get: function () {
  31037. return this._noMipmap;
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(Texture.prototype, "isBlocking", {
  31043. get: function () {
  31044. return this._isBlocking;
  31045. },
  31046. set: function (value) {
  31047. this._isBlocking = value;
  31048. },
  31049. enumerable: true,
  31050. configurable: true
  31051. });
  31052. Object.defineProperty(Texture.prototype, "samplingMode", {
  31053. get: function () {
  31054. return this._samplingMode;
  31055. },
  31056. enumerable: true,
  31057. configurable: true
  31058. });
  31059. /**
  31060. * Update the url (and optional buffer) of this texture if url was null during construction.
  31061. * @param url the url of the texture
  31062. * @param buffer the buffer of the texture (defaults to null)
  31063. */
  31064. Texture.prototype.updateURL = function (url, buffer) {
  31065. if (buffer === void 0) { buffer = null; }
  31066. if (this.url) {
  31067. throw new Error("URL is already set");
  31068. }
  31069. this.url = url;
  31070. this._buffer = buffer;
  31071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31072. this.delayLoad();
  31073. };
  31074. Texture.prototype.delayLoad = function () {
  31075. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31076. return;
  31077. }
  31078. var scene = this.getScene();
  31079. if (!scene) {
  31080. return;
  31081. }
  31082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31083. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31084. if (!this._texture) {
  31085. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31086. if (this._deleteBuffer) {
  31087. delete this._buffer;
  31088. }
  31089. }
  31090. else {
  31091. if (this._delayedOnLoad) {
  31092. if (this._texture.isReady) {
  31093. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31094. }
  31095. else {
  31096. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31097. }
  31098. }
  31099. }
  31100. this._delayedOnLoad = null;
  31101. this._delayedOnError = null;
  31102. };
  31103. /**
  31104. * Default is Trilinear mode.
  31105. *
  31106. * | Value | Type | Description |
  31107. * | ----- | ------------------ | ----------- |
  31108. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31109. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31110. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31111. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31112. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31113. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31114. * | 7 | NEAREST_LINEAR | |
  31115. * | 8 | NEAREST_NEAREST | |
  31116. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31117. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31118. * | 11 | LINEAR_LINEAR | |
  31119. * | 12 | LINEAR_NEAREST | |
  31120. *
  31121. * > _mag_: magnification filter (close to the viewer)
  31122. * > _min_: minification filter (far from the viewer)
  31123. * > _mip_: filter used between mip map levels
  31124. *
  31125. */
  31126. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31127. if (!this._texture) {
  31128. return;
  31129. }
  31130. var scene = this.getScene();
  31131. if (!scene) {
  31132. return;
  31133. }
  31134. this._samplingMode = samplingMode;
  31135. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31136. };
  31137. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31138. x *= this.uScale;
  31139. y *= this.vScale;
  31140. x -= this.uRotationCenter * this.uScale;
  31141. y -= this.vRotationCenter * this.vScale;
  31142. z -= this.wRotationCenter;
  31143. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31144. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31145. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31146. t.z += this.wRotationCenter;
  31147. };
  31148. Texture.prototype.getTextureMatrix = function () {
  31149. var _this = this;
  31150. if (this.uOffset === this._cachedUOffset &&
  31151. this.vOffset === this._cachedVOffset &&
  31152. this.uScale === this._cachedUScale &&
  31153. this.vScale === this._cachedVScale &&
  31154. this.uAng === this._cachedUAng &&
  31155. this.vAng === this._cachedVAng &&
  31156. this.wAng === this._cachedWAng) {
  31157. return this._cachedTextureMatrix;
  31158. }
  31159. this._cachedUOffset = this.uOffset;
  31160. this._cachedVOffset = this.vOffset;
  31161. this._cachedUScale = this.uScale;
  31162. this._cachedVScale = this.vScale;
  31163. this._cachedUAng = this.uAng;
  31164. this._cachedVAng = this.vAng;
  31165. this._cachedWAng = this.wAng;
  31166. if (!this._cachedTextureMatrix) {
  31167. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31168. this._rowGenerationMatrix = new BABYLON.Matrix();
  31169. this._t0 = BABYLON.Vector3.Zero();
  31170. this._t1 = BABYLON.Vector3.Zero();
  31171. this._t2 = BABYLON.Vector3.Zero();
  31172. }
  31173. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31174. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31175. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31176. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31177. this._t1.subtractInPlace(this._t0);
  31178. this._t2.subtractInPlace(this._t0);
  31179. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31180. this._cachedTextureMatrix.m[0] = this._t1.x;
  31181. this._cachedTextureMatrix.m[1] = this._t1.y;
  31182. this._cachedTextureMatrix.m[2] = this._t1.z;
  31183. this._cachedTextureMatrix.m[4] = this._t2.x;
  31184. this._cachedTextureMatrix.m[5] = this._t2.y;
  31185. this._cachedTextureMatrix.m[6] = this._t2.z;
  31186. this._cachedTextureMatrix.m[8] = this._t0.x;
  31187. this._cachedTextureMatrix.m[9] = this._t0.y;
  31188. this._cachedTextureMatrix.m[10] = this._t0.z;
  31189. var scene = this.getScene();
  31190. if (!scene) {
  31191. return this._cachedTextureMatrix;
  31192. }
  31193. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31194. return mat.hasTexture(_this);
  31195. });
  31196. return this._cachedTextureMatrix;
  31197. };
  31198. Texture.prototype.getReflectionTextureMatrix = function () {
  31199. var _this = this;
  31200. var scene = this.getScene();
  31201. if (!scene) {
  31202. return this._cachedTextureMatrix;
  31203. }
  31204. if (this.uOffset === this._cachedUOffset &&
  31205. this.vOffset === this._cachedVOffset &&
  31206. this.uScale === this._cachedUScale &&
  31207. this.vScale === this._cachedVScale &&
  31208. this.coordinatesMode === this._cachedCoordinatesMode) {
  31209. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31210. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31211. return this._cachedTextureMatrix;
  31212. }
  31213. }
  31214. else {
  31215. return this._cachedTextureMatrix;
  31216. }
  31217. }
  31218. if (!this._cachedTextureMatrix) {
  31219. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31220. }
  31221. if (!this._projectionModeMatrix) {
  31222. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31223. }
  31224. this._cachedUOffset = this.uOffset;
  31225. this._cachedVOffset = this.vOffset;
  31226. this._cachedUScale = this.uScale;
  31227. this._cachedVScale = this.vScale;
  31228. this._cachedCoordinatesMode = this.coordinatesMode;
  31229. switch (this.coordinatesMode) {
  31230. case Texture.PLANAR_MODE:
  31231. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31232. this._cachedTextureMatrix[0] = this.uScale;
  31233. this._cachedTextureMatrix[5] = this.vScale;
  31234. this._cachedTextureMatrix[12] = this.uOffset;
  31235. this._cachedTextureMatrix[13] = this.vOffset;
  31236. break;
  31237. case Texture.PROJECTION_MODE:
  31238. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31239. this._projectionModeMatrix.m[0] = 0.5;
  31240. this._projectionModeMatrix.m[5] = -0.5;
  31241. this._projectionModeMatrix.m[10] = 0.0;
  31242. this._projectionModeMatrix.m[12] = 0.5;
  31243. this._projectionModeMatrix.m[13] = 0.5;
  31244. this._projectionModeMatrix.m[14] = 1.0;
  31245. this._projectionModeMatrix.m[15] = 1.0;
  31246. var projectionMatrix = scene.getProjectionMatrix();
  31247. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31248. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31249. break;
  31250. default:
  31251. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31252. break;
  31253. }
  31254. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31255. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31256. });
  31257. return this._cachedTextureMatrix;
  31258. };
  31259. Texture.prototype.clone = function () {
  31260. var _this = this;
  31261. return BABYLON.SerializationHelper.Clone(function () {
  31262. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31263. }, this);
  31264. };
  31265. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31266. get: function () {
  31267. if (!this._onLoadObservable) {
  31268. this._onLoadObservable = new BABYLON.Observable();
  31269. }
  31270. return this._onLoadObservable;
  31271. },
  31272. enumerable: true,
  31273. configurable: true
  31274. });
  31275. Texture.prototype.serialize = function () {
  31276. var serializationObject = _super.prototype.serialize.call(this);
  31277. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31278. serializationObject.base64String = this._buffer;
  31279. serializationObject.name = serializationObject.name.replace("data:", "");
  31280. }
  31281. serializationObject.invertY = this._invertY;
  31282. serializationObject.samplingMode = this.samplingMode;
  31283. return serializationObject;
  31284. };
  31285. Texture.prototype.getClassName = function () {
  31286. return "Texture";
  31287. };
  31288. Texture.prototype.dispose = function () {
  31289. _super.prototype.dispose.call(this);
  31290. if (this._onLoadObservable) {
  31291. this._onLoadObservable.clear();
  31292. this._onLoadObservable = null;
  31293. }
  31294. this._delayedOnLoad = null;
  31295. this._delayedOnError = null;
  31296. };
  31297. // Statics
  31298. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31299. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31300. if (onLoad === void 0) { onLoad = null; }
  31301. if (onError === void 0) { onError = null; }
  31302. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31303. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31304. };
  31305. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31306. if (parsedTexture.customType) {
  31307. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31308. // Update Sampling Mode
  31309. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31310. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31311. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31312. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31313. }
  31314. }
  31315. return parsedCustomTexture;
  31316. }
  31317. if (parsedTexture.isCube) {
  31318. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31319. }
  31320. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31321. return null;
  31322. }
  31323. var texture = BABYLON.SerializationHelper.Parse(function () {
  31324. var generateMipMaps = true;
  31325. if (parsedTexture.noMipmap) {
  31326. generateMipMaps = false;
  31327. }
  31328. if (parsedTexture.mirrorPlane) {
  31329. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31330. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31331. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31332. return mirrorTexture;
  31333. }
  31334. else if (parsedTexture.isRenderTarget) {
  31335. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31336. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31337. return renderTargetTexture;
  31338. }
  31339. else {
  31340. var texture;
  31341. if (parsedTexture.base64String) {
  31342. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31343. }
  31344. else {
  31345. var url = rootUrl + parsedTexture.name;
  31346. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31347. url = parsedTexture.url;
  31348. }
  31349. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31350. }
  31351. return texture;
  31352. }
  31353. }, parsedTexture, scene);
  31354. // Update Sampling Mode
  31355. if (parsedTexture.samplingMode) {
  31356. var sampling = parsedTexture.samplingMode;
  31357. if (texture._samplingMode !== sampling) {
  31358. texture.updateSamplingMode(sampling);
  31359. }
  31360. }
  31361. // Animations
  31362. if (parsedTexture.animations) {
  31363. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31364. var parsedAnimation = parsedTexture.animations[animationIndex];
  31365. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31366. }
  31367. }
  31368. return texture;
  31369. };
  31370. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31371. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31372. if (noMipmap === void 0) { noMipmap = false; }
  31373. if (invertY === void 0) { invertY = true; }
  31374. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31375. if (onLoad === void 0) { onLoad = null; }
  31376. if (onError === void 0) { onError = null; }
  31377. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31378. if (name.substr(0, 5) !== "data:") {
  31379. name = "data:" + name;
  31380. }
  31381. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31382. };
  31383. // Constants
  31384. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31385. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31386. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31387. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31388. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31389. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31390. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31391. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31392. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31393. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31394. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31395. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31396. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31397. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31398. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31399. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31400. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31401. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31402. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31403. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31404. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31405. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31406. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31407. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31408. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31409. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31410. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31411. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31412. /**
  31413. * 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
  31414. */
  31415. Texture.UseSerializedUrlIfAny = false;
  31416. __decorate([
  31417. BABYLON.serialize()
  31418. ], Texture.prototype, "url", void 0);
  31419. __decorate([
  31420. BABYLON.serialize()
  31421. ], Texture.prototype, "uOffset", void 0);
  31422. __decorate([
  31423. BABYLON.serialize()
  31424. ], Texture.prototype, "vOffset", void 0);
  31425. __decorate([
  31426. BABYLON.serialize()
  31427. ], Texture.prototype, "uScale", void 0);
  31428. __decorate([
  31429. BABYLON.serialize()
  31430. ], Texture.prototype, "vScale", void 0);
  31431. __decorate([
  31432. BABYLON.serialize()
  31433. ], Texture.prototype, "uAng", void 0);
  31434. __decorate([
  31435. BABYLON.serialize()
  31436. ], Texture.prototype, "vAng", void 0);
  31437. __decorate([
  31438. BABYLON.serialize()
  31439. ], Texture.prototype, "wAng", void 0);
  31440. __decorate([
  31441. BABYLON.serialize()
  31442. ], Texture.prototype, "uRotationCenter", void 0);
  31443. __decorate([
  31444. BABYLON.serialize()
  31445. ], Texture.prototype, "vRotationCenter", void 0);
  31446. __decorate([
  31447. BABYLON.serialize()
  31448. ], Texture.prototype, "wRotationCenter", void 0);
  31449. __decorate([
  31450. BABYLON.serialize()
  31451. ], Texture.prototype, "isBlocking", null);
  31452. return Texture;
  31453. }(BABYLON.BaseTexture));
  31454. BABYLON.Texture = Texture;
  31455. })(BABYLON || (BABYLON = {}));
  31456. //# sourceMappingURL=babylon.texture.js.map
  31457. var BABYLON;
  31458. (function (BABYLON) {
  31459. /**
  31460. * @hidden
  31461. **/
  31462. var _CreationDataStorage = /** @class */ (function () {
  31463. function _CreationDataStorage() {
  31464. }
  31465. return _CreationDataStorage;
  31466. }());
  31467. BABYLON._CreationDataStorage = _CreationDataStorage;
  31468. /**
  31469. * @hidden
  31470. **/
  31471. var _InstanceDataStorage = /** @class */ (function () {
  31472. function _InstanceDataStorage() {
  31473. this.visibleInstances = {};
  31474. this.renderIdForInstances = new Array();
  31475. this.batchCache = new _InstancesBatch();
  31476. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31477. }
  31478. return _InstanceDataStorage;
  31479. }());
  31480. /**
  31481. * @hidden
  31482. **/
  31483. var _InstancesBatch = /** @class */ (function () {
  31484. function _InstancesBatch() {
  31485. this.mustReturn = false;
  31486. this.visibleInstances = new Array();
  31487. this.renderSelf = new Array();
  31488. }
  31489. return _InstancesBatch;
  31490. }());
  31491. BABYLON._InstancesBatch = _InstancesBatch;
  31492. /**
  31493. * Class used to represent renderable models
  31494. */
  31495. var Mesh = /** @class */ (function (_super) {
  31496. __extends(Mesh, _super);
  31497. /**
  31498. * @constructor
  31499. * @param name The value used by scene.getMeshByName() to do a lookup.
  31500. * @param scene The scene to add this mesh to.
  31501. * @param parent The parent of this mesh, if it has one
  31502. * @param source An optional Mesh from which geometry is shared, cloned.
  31503. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31504. * When false, achieved by calling a clone(), also passing False.
  31505. * This will make creation of children, recursive.
  31506. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31507. */
  31508. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31509. if (scene === void 0) { scene = null; }
  31510. if (parent === void 0) { parent = null; }
  31511. if (source === void 0) { source = null; }
  31512. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31513. var _this = _super.call(this, name, scene) || this;
  31514. // Members
  31515. /**
  31516. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31517. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31518. */
  31519. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31520. /**
  31521. * Gets the list of instances created from this mesh
  31522. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31523. */
  31524. _this.instances = new Array();
  31525. _this._LODLevels = new Array();
  31526. /** @hidden */
  31527. _this._instanceDataStorage = new _InstanceDataStorage();
  31528. // Use by builder only to know what orientation were the mesh build in.
  31529. /** @hidden */
  31530. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31531. /**
  31532. * Use this property to change the original side orientation defined at construction time
  31533. */
  31534. _this.overrideMaterialSideOrientation = null;
  31535. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31536. // Will be used to save a source mesh reference, If any
  31537. _this._source = null;
  31538. scene = _this.getScene();
  31539. if (source) {
  31540. // Geometry
  31541. if (source._geometry) {
  31542. source._geometry.applyToMesh(_this);
  31543. }
  31544. // Deep copy
  31545. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31546. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31547. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31548. ], ["_poseMatrix"]);
  31549. // Source mesh
  31550. _this._source = source;
  31551. // Construction Params
  31552. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31553. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31554. _this._creationDataStorage = source._creationDataStorage;
  31555. // Animation ranges
  31556. if (_this._source._ranges) {
  31557. var ranges = _this._source._ranges;
  31558. for (var name in ranges) {
  31559. if (!ranges.hasOwnProperty(name)) {
  31560. continue;
  31561. }
  31562. if (!ranges[name]) {
  31563. continue;
  31564. }
  31565. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31566. }
  31567. }
  31568. // Metadata
  31569. if (source.metadata && source.metadata.clone) {
  31570. _this.metadata = source.metadata.clone();
  31571. }
  31572. else {
  31573. _this.metadata = source.metadata;
  31574. }
  31575. // Tags
  31576. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31577. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31578. }
  31579. // Parent
  31580. _this.parent = source.parent;
  31581. // Pivot
  31582. _this.setPivotMatrix(source.getPivotMatrix());
  31583. _this.id = name + "." + source.id;
  31584. // Material
  31585. _this.material = source.material;
  31586. var index;
  31587. if (!doNotCloneChildren) {
  31588. // Children
  31589. var directDescendants = source.getDescendants(true);
  31590. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31591. var child = directDescendants[index_1];
  31592. if (child.clone) {
  31593. child.clone(name + "." + child.name, _this);
  31594. }
  31595. }
  31596. }
  31597. // Physics clone
  31598. var physicsEngine = _this.getScene().getPhysicsEngine();
  31599. if (clonePhysicsImpostor && physicsEngine) {
  31600. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31601. if (impostor) {
  31602. _this.physicsImpostor = impostor.clone(_this);
  31603. }
  31604. }
  31605. // Particles
  31606. for (index = 0; index < scene.particleSystems.length; index++) {
  31607. var system = scene.particleSystems[index];
  31608. if (system.emitter === source) {
  31609. system.clone(system.name, _this);
  31610. }
  31611. }
  31612. _this.refreshBoundingInfo();
  31613. _this.computeWorldMatrix(true);
  31614. }
  31615. // Parent
  31616. if (parent !== null) {
  31617. _this.parent = parent;
  31618. }
  31619. return _this;
  31620. }
  31621. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31622. /**
  31623. * An event triggered before rendering the mesh
  31624. */
  31625. get: function () {
  31626. if (!this._onBeforeRenderObservable) {
  31627. this._onBeforeRenderObservable = new BABYLON.Observable();
  31628. }
  31629. return this._onBeforeRenderObservable;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31635. /**
  31636. * An event triggered after rendering the mesh
  31637. */
  31638. get: function () {
  31639. if (!this._onAfterRenderObservable) {
  31640. this._onAfterRenderObservable = new BABYLON.Observable();
  31641. }
  31642. return this._onAfterRenderObservable;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31648. /**
  31649. * An event triggered before drawing the mesh
  31650. */
  31651. get: function () {
  31652. if (!this._onBeforeDrawObservable) {
  31653. this._onBeforeDrawObservable = new BABYLON.Observable();
  31654. }
  31655. return this._onBeforeDrawObservable;
  31656. },
  31657. enumerable: true,
  31658. configurable: true
  31659. });
  31660. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31661. /**
  31662. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31663. */
  31664. set: function (callback) {
  31665. if (this._onBeforeDrawObserver) {
  31666. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31667. }
  31668. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31669. },
  31670. enumerable: true,
  31671. configurable: true
  31672. });
  31673. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31674. /**
  31675. * Gets or sets the morph target manager
  31676. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31677. */
  31678. get: function () {
  31679. return this._morphTargetManager;
  31680. },
  31681. set: function (value) {
  31682. if (this._morphTargetManager === value) {
  31683. return;
  31684. }
  31685. this._morphTargetManager = value;
  31686. this._syncGeometryWithMorphTargetManager();
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. Object.defineProperty(Mesh.prototype, "source", {
  31692. /**
  31693. * Gets the source mesh (the one used to clone this one from)
  31694. */
  31695. get: function () {
  31696. return this._source;
  31697. },
  31698. enumerable: true,
  31699. configurable: true
  31700. });
  31701. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31702. /**
  31703. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31704. */
  31705. get: function () {
  31706. return this._unIndexed;
  31707. },
  31708. set: function (value) {
  31709. if (this._unIndexed !== value) {
  31710. this._unIndexed = value;
  31711. this._markSubMeshesAsAttributesDirty();
  31712. }
  31713. },
  31714. enumerable: true,
  31715. configurable: true
  31716. });
  31717. // Methods
  31718. /**
  31719. * Gets the class name
  31720. * @returns the string "Mesh".
  31721. */
  31722. Mesh.prototype.getClassName = function () {
  31723. return "Mesh";
  31724. };
  31725. /**
  31726. * Returns a description of this mesh
  31727. * @param fullDetails define if full details about this mesh must be used
  31728. * @returns a descriptive string representing this mesh
  31729. */
  31730. Mesh.prototype.toString = function (fullDetails) {
  31731. var ret = _super.prototype.toString.call(this, fullDetails);
  31732. ret += ", n vertices: " + this.getTotalVertices();
  31733. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31734. if (this.animations) {
  31735. for (var i = 0; i < this.animations.length; i++) {
  31736. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31737. }
  31738. }
  31739. if (fullDetails) {
  31740. if (this._geometry) {
  31741. var ib = this.getIndices();
  31742. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31743. if (vb && ib) {
  31744. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31745. }
  31746. }
  31747. else {
  31748. ret += ", flat shading: UNKNOWN";
  31749. }
  31750. }
  31751. return ret;
  31752. };
  31753. /** @hidden */
  31754. Mesh.prototype._unBindEffect = function () {
  31755. _super.prototype._unBindEffect.call(this);
  31756. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31757. var instance = _a[_i];
  31758. instance._unBindEffect();
  31759. }
  31760. };
  31761. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31762. /**
  31763. * Gets a boolean indicating if this mesh has LOD
  31764. */
  31765. get: function () {
  31766. return this._LODLevels.length > 0;
  31767. },
  31768. enumerable: true,
  31769. configurable: true
  31770. });
  31771. /**
  31772. * Gets the list of MeshLODLevel associated with the current mesh
  31773. * @returns an array of MeshLODLevel
  31774. */
  31775. Mesh.prototype.getLODLevels = function () {
  31776. return this._LODLevels;
  31777. };
  31778. Mesh.prototype._sortLODLevels = function () {
  31779. this._LODLevels.sort(function (a, b) {
  31780. if (a.distance < b.distance) {
  31781. return 1;
  31782. }
  31783. if (a.distance > b.distance) {
  31784. return -1;
  31785. }
  31786. return 0;
  31787. });
  31788. };
  31789. /**
  31790. * Add a mesh as LOD level triggered at the given distance.
  31791. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31792. * @param distance The distance from the center of the object to show this level
  31793. * @param mesh The mesh to be added as LOD level (can be null)
  31794. * @return This mesh (for chaining)
  31795. */
  31796. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31797. if (mesh && mesh._masterMesh) {
  31798. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31799. return this;
  31800. }
  31801. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31802. this._LODLevels.push(level);
  31803. if (mesh) {
  31804. mesh._masterMesh = this;
  31805. }
  31806. this._sortLODLevels();
  31807. return this;
  31808. };
  31809. /**
  31810. * Returns the LOD level mesh at the passed distance or null if not found.
  31811. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31812. * @param distance The distance from the center of the object to show this level
  31813. * @returns a Mesh or `null`
  31814. */
  31815. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31816. for (var index = 0; index < this._LODLevels.length; index++) {
  31817. var level = this._LODLevels[index];
  31818. if (level.distance === distance) {
  31819. return level.mesh;
  31820. }
  31821. }
  31822. return null;
  31823. };
  31824. /**
  31825. * Remove a mesh from the LOD array
  31826. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31827. * @param mesh defines the mesh to be removed
  31828. * @return This mesh (for chaining)
  31829. */
  31830. Mesh.prototype.removeLODLevel = function (mesh) {
  31831. for (var index = 0; index < this._LODLevels.length; index++) {
  31832. if (this._LODLevels[index].mesh === mesh) {
  31833. this._LODLevels.splice(index, 1);
  31834. if (mesh) {
  31835. mesh._masterMesh = null;
  31836. }
  31837. }
  31838. }
  31839. this._sortLODLevels();
  31840. return this;
  31841. };
  31842. /**
  31843. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31844. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31845. * @param camera defines the camera to use to compute distance
  31846. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31847. * @return This mesh (for chaining)
  31848. */
  31849. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31850. if (!this._LODLevels || this._LODLevels.length === 0) {
  31851. return this;
  31852. }
  31853. var bSphere;
  31854. if (boundingSphere) {
  31855. bSphere = boundingSphere;
  31856. }
  31857. else {
  31858. var boundingInfo = this.getBoundingInfo();
  31859. bSphere = boundingInfo.boundingSphere;
  31860. }
  31861. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31862. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31863. if (this.onLODLevelSelection) {
  31864. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31865. }
  31866. return this;
  31867. }
  31868. for (var index = 0; index < this._LODLevels.length; index++) {
  31869. var level = this._LODLevels[index];
  31870. if (level.distance < distanceToCamera) {
  31871. if (level.mesh) {
  31872. level.mesh._preActivate();
  31873. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31874. }
  31875. if (this.onLODLevelSelection) {
  31876. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31877. }
  31878. return level.mesh;
  31879. }
  31880. }
  31881. if (this.onLODLevelSelection) {
  31882. this.onLODLevelSelection(distanceToCamera, this, this);
  31883. }
  31884. return this;
  31885. };
  31886. Object.defineProperty(Mesh.prototype, "geometry", {
  31887. /**
  31888. * Gets the mesh internal Geometry object
  31889. */
  31890. get: function () {
  31891. return this._geometry;
  31892. },
  31893. enumerable: true,
  31894. configurable: true
  31895. });
  31896. /**
  31897. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31898. * @returns the total number of vertices
  31899. */
  31900. Mesh.prototype.getTotalVertices = function () {
  31901. if (this._geometry === null || this._geometry === undefined) {
  31902. return 0;
  31903. }
  31904. return this._geometry.getTotalVertices();
  31905. };
  31906. /**
  31907. * Returns the content of an associated vertex buffer
  31908. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31909. * - BABYLON.VertexBuffer.PositionKind
  31910. * - BABYLON.VertexBuffer.UVKind
  31911. * - BABYLON.VertexBuffer.UV2Kind
  31912. * - BABYLON.VertexBuffer.UV3Kind
  31913. * - BABYLON.VertexBuffer.UV4Kind
  31914. * - BABYLON.VertexBuffer.UV5Kind
  31915. * - BABYLON.VertexBuffer.UV6Kind
  31916. * - BABYLON.VertexBuffer.ColorKind
  31917. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31918. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31919. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31920. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31921. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31922. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31923. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31924. */
  31925. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31926. if (!this._geometry) {
  31927. return null;
  31928. }
  31929. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31930. };
  31931. /**
  31932. * Returns the mesh VertexBuffer object from the requested `kind`
  31933. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31934. * - BABYLON.VertexBuffer.PositionKind
  31935. * - BABYLON.VertexBuffer.UVKind
  31936. * - BABYLON.VertexBuffer.UV2Kind
  31937. * - BABYLON.VertexBuffer.UV3Kind
  31938. * - BABYLON.VertexBuffer.UV4Kind
  31939. * - BABYLON.VertexBuffer.UV5Kind
  31940. * - BABYLON.VertexBuffer.UV6Kind
  31941. * - BABYLON.VertexBuffer.ColorKind
  31942. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31943. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31944. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31945. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31946. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31947. */
  31948. Mesh.prototype.getVertexBuffer = function (kind) {
  31949. if (!this._geometry) {
  31950. return null;
  31951. }
  31952. return this._geometry.getVertexBuffer(kind);
  31953. };
  31954. /**
  31955. * Tests if a specific vertex buffer is associated with this mesh
  31956. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31957. * - BABYLON.VertexBuffer.PositionKind
  31958. * - BABYLON.VertexBuffer.UVKind
  31959. * - BABYLON.VertexBuffer.UV2Kind
  31960. * - BABYLON.VertexBuffer.UV3Kind
  31961. * - BABYLON.VertexBuffer.UV4Kind
  31962. * - BABYLON.VertexBuffer.UV5Kind
  31963. * - BABYLON.VertexBuffer.UV6Kind
  31964. * - BABYLON.VertexBuffer.ColorKind
  31965. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31966. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31967. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31968. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31969. * @returns a boolean
  31970. */
  31971. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31972. if (!this._geometry) {
  31973. if (this._delayInfo) {
  31974. return this._delayInfo.indexOf(kind) !== -1;
  31975. }
  31976. return false;
  31977. }
  31978. return this._geometry.isVerticesDataPresent(kind);
  31979. };
  31980. /**
  31981. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31982. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31983. * - BABYLON.VertexBuffer.PositionKind
  31984. * - BABYLON.VertexBuffer.UVKind
  31985. * - BABYLON.VertexBuffer.UV2Kind
  31986. * - BABYLON.VertexBuffer.UV3Kind
  31987. * - BABYLON.VertexBuffer.UV4Kind
  31988. * - BABYLON.VertexBuffer.UV5Kind
  31989. * - BABYLON.VertexBuffer.UV6Kind
  31990. * - BABYLON.VertexBuffer.ColorKind
  31991. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31992. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31993. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31994. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31995. * @returns a boolean
  31996. */
  31997. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31998. if (!this._geometry) {
  31999. if (this._delayInfo) {
  32000. return this._delayInfo.indexOf(kind) !== -1;
  32001. }
  32002. return false;
  32003. }
  32004. return this._geometry.isVertexBufferUpdatable(kind);
  32005. };
  32006. /**
  32007. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32008. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32009. * - BABYLON.VertexBuffer.PositionKind
  32010. * - BABYLON.VertexBuffer.UVKind
  32011. * - BABYLON.VertexBuffer.UV2Kind
  32012. * - BABYLON.VertexBuffer.UV3Kind
  32013. * - BABYLON.VertexBuffer.UV4Kind
  32014. * - BABYLON.VertexBuffer.UV5Kind
  32015. * - BABYLON.VertexBuffer.UV6Kind
  32016. * - BABYLON.VertexBuffer.ColorKind
  32017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32021. * @returns an array of strings
  32022. */
  32023. Mesh.prototype.getVerticesDataKinds = function () {
  32024. if (!this._geometry) {
  32025. var result = new Array();
  32026. if (this._delayInfo) {
  32027. this._delayInfo.forEach(function (kind, index, array) {
  32028. result.push(kind);
  32029. });
  32030. }
  32031. return result;
  32032. }
  32033. return this._geometry.getVerticesDataKinds();
  32034. };
  32035. /**
  32036. * Returns a positive integer : the total number of indices in this mesh geometry.
  32037. * @returns the numner of indices or zero if the mesh has no geometry.
  32038. */
  32039. Mesh.prototype.getTotalIndices = function () {
  32040. if (!this._geometry) {
  32041. return 0;
  32042. }
  32043. return this._geometry.getTotalIndices();
  32044. };
  32045. /**
  32046. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32047. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  32048. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32049. * @returns the indices array or an empty array if the mesh has no geometry
  32050. */
  32051. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32052. if (!this._geometry) {
  32053. return [];
  32054. }
  32055. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32056. };
  32057. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32058. get: function () {
  32059. return this._masterMesh !== null && this._masterMesh !== undefined;
  32060. },
  32061. enumerable: true,
  32062. configurable: true
  32063. });
  32064. /**
  32065. * Determine if the current mesh is ready to be rendered
  32066. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32067. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32068. * @returns true if all associated assets are ready (material, textures, shaders)
  32069. */
  32070. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32071. if (completeCheck === void 0) { completeCheck = false; }
  32072. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32073. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32074. return false;
  32075. }
  32076. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32077. return false;
  32078. }
  32079. if (!this.subMeshes || this.subMeshes.length === 0) {
  32080. return true;
  32081. }
  32082. if (!completeCheck) {
  32083. return true;
  32084. }
  32085. var engine = this.getEngine();
  32086. var scene = this.getScene();
  32087. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32088. this.computeWorldMatrix();
  32089. var mat = this.material || scene.defaultMaterial;
  32090. if (mat) {
  32091. if (mat.storeEffectOnSubMeshes) {
  32092. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32093. var subMesh = _a[_i];
  32094. var effectiveMaterial = subMesh.getMaterial();
  32095. if (effectiveMaterial) {
  32096. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32097. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32098. return false;
  32099. }
  32100. }
  32101. else {
  32102. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32103. return false;
  32104. }
  32105. }
  32106. }
  32107. }
  32108. }
  32109. else {
  32110. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32111. return false;
  32112. }
  32113. }
  32114. }
  32115. // Shadows
  32116. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32117. var light = _c[_b];
  32118. var generator = light.getShadowGenerator();
  32119. if (generator) {
  32120. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32121. var subMesh = _e[_d];
  32122. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32123. return false;
  32124. }
  32125. }
  32126. }
  32127. }
  32128. // LOD
  32129. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32130. var lod = _g[_f];
  32131. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32132. return false;
  32133. }
  32134. }
  32135. return true;
  32136. };
  32137. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32138. /**
  32139. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32140. */
  32141. get: function () {
  32142. return this._areNormalsFrozen;
  32143. },
  32144. enumerable: true,
  32145. configurable: true
  32146. });
  32147. /**
  32148. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32149. * @returns the current mesh
  32150. */
  32151. Mesh.prototype.freezeNormals = function () {
  32152. this._areNormalsFrozen = true;
  32153. return this;
  32154. };
  32155. /**
  32156. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32157. * @returns the current mesh
  32158. */
  32159. Mesh.prototype.unfreezeNormals = function () {
  32160. this._areNormalsFrozen = false;
  32161. return this;
  32162. };
  32163. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32164. /**
  32165. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32166. */
  32167. set: function (count) {
  32168. this._instanceDataStorage.overridenInstanceCount = count;
  32169. },
  32170. enumerable: true,
  32171. configurable: true
  32172. });
  32173. // Methods
  32174. /** @hidden */
  32175. Mesh.prototype._preActivate = function () {
  32176. var sceneRenderId = this.getScene().getRenderId();
  32177. if (this._preActivateId === sceneRenderId) {
  32178. return this;
  32179. }
  32180. this._preActivateId = sceneRenderId;
  32181. this._instanceDataStorage.visibleInstances = null;
  32182. return this;
  32183. };
  32184. /** @hidden */
  32185. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32186. if (this._instanceDataStorage.visibleInstances) {
  32187. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32188. }
  32189. return this;
  32190. };
  32191. /** @hidden */
  32192. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32193. if (!this._instanceDataStorage.visibleInstances) {
  32194. this._instanceDataStorage.visibleInstances = {};
  32195. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32196. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32197. }
  32198. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32199. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32200. }
  32201. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32202. return this;
  32203. };
  32204. /**
  32205. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32206. * This means the mesh underlying bounding box and sphere are recomputed.
  32207. * @returns the current mesh
  32208. */
  32209. Mesh.prototype.refreshBoundingInfo = function () {
  32210. return this._refreshBoundingInfo(false);
  32211. };
  32212. /** @hidden */
  32213. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32214. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32215. return this;
  32216. }
  32217. var data = this._getPositionData(applySkeleton);
  32218. if (data) {
  32219. var bias = this.geometry ? this.geometry.boundingBias : null;
  32220. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32221. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32222. }
  32223. if (this.subMeshes) {
  32224. for (var index = 0; index < this.subMeshes.length; index++) {
  32225. this.subMeshes[index].refreshBoundingInfo();
  32226. }
  32227. }
  32228. this._updateBoundingInfo();
  32229. return this;
  32230. };
  32231. Mesh.prototype._getPositionData = function (applySkeleton) {
  32232. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32233. if (data && applySkeleton && this.skeleton) {
  32234. data = BABYLON.Tools.Slice(data);
  32235. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32236. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32237. if (matricesWeightsData && matricesIndicesData) {
  32238. var needExtras = this.numBoneInfluencers > 4;
  32239. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32240. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32241. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32242. var tempVector = BABYLON.Tmp.Vector3[0];
  32243. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32244. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32245. var matWeightIdx = 0;
  32246. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32247. finalMatrix.reset();
  32248. var inf;
  32249. var weight;
  32250. for (inf = 0; inf < 4; inf++) {
  32251. weight = matricesWeightsData[matWeightIdx + inf];
  32252. if (weight > 0) {
  32253. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32254. finalMatrix.addToSelf(tempMatrix);
  32255. }
  32256. }
  32257. if (needExtras) {
  32258. for (inf = 0; inf < 4; inf++) {
  32259. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32260. if (weight > 0) {
  32261. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32262. finalMatrix.addToSelf(tempMatrix);
  32263. }
  32264. }
  32265. }
  32266. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32267. tempVector.toArray(data, index);
  32268. }
  32269. }
  32270. }
  32271. return data;
  32272. };
  32273. /** @hidden */
  32274. Mesh.prototype._createGlobalSubMesh = function (force) {
  32275. var totalVertices = this.getTotalVertices();
  32276. if (!totalVertices || !this.getIndices()) {
  32277. return null;
  32278. }
  32279. // Check if we need to recreate the submeshes
  32280. if (this.subMeshes && this.subMeshes.length > 0) {
  32281. var ib = this.getIndices();
  32282. if (!ib) {
  32283. return null;
  32284. }
  32285. var totalIndices = ib.length;
  32286. var needToRecreate = false;
  32287. if (force) {
  32288. needToRecreate = true;
  32289. }
  32290. else {
  32291. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32292. var submesh = _a[_i];
  32293. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32294. needToRecreate = true;
  32295. break;
  32296. }
  32297. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32298. needToRecreate = true;
  32299. break;
  32300. }
  32301. }
  32302. }
  32303. if (!needToRecreate) {
  32304. return this.subMeshes[0];
  32305. }
  32306. }
  32307. this.releaseSubMeshes();
  32308. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32309. };
  32310. /**
  32311. * This function will subdivide the mesh into multiple submeshes
  32312. * @param count defines the expected number of submeshes
  32313. */
  32314. Mesh.prototype.subdivide = function (count) {
  32315. if (count < 1) {
  32316. return;
  32317. }
  32318. var totalIndices = this.getTotalIndices();
  32319. var subdivisionSize = (totalIndices / count) | 0;
  32320. var offset = 0;
  32321. // Ensure that subdivisionSize is a multiple of 3
  32322. while (subdivisionSize % 3 !== 0) {
  32323. subdivisionSize++;
  32324. }
  32325. this.releaseSubMeshes();
  32326. for (var index = 0; index < count; index++) {
  32327. if (offset >= totalIndices) {
  32328. break;
  32329. }
  32330. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32331. offset += subdivisionSize;
  32332. }
  32333. this.synchronizeInstances();
  32334. };
  32335. /**
  32336. * Copy a FloatArray into a specific associated vertex buffer
  32337. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32338. * - BABYLON.VertexBuffer.PositionKind
  32339. * - BABYLON.VertexBuffer.UVKind
  32340. * - BABYLON.VertexBuffer.UV2Kind
  32341. * - BABYLON.VertexBuffer.UV3Kind
  32342. * - BABYLON.VertexBuffer.UV4Kind
  32343. * - BABYLON.VertexBuffer.UV5Kind
  32344. * - BABYLON.VertexBuffer.UV6Kind
  32345. * - BABYLON.VertexBuffer.ColorKind
  32346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32350. * @param data defines the data source
  32351. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32352. * @param stride defines the data stride size (can be null)
  32353. * @returns the current mesh
  32354. */
  32355. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32356. if (updatable === void 0) { updatable = false; }
  32357. if (!this._geometry) {
  32358. var vertexData = new BABYLON.VertexData();
  32359. vertexData.set(data, kind);
  32360. var scene = this.getScene();
  32361. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32362. }
  32363. else {
  32364. this._geometry.setVerticesData(kind, data, updatable, stride);
  32365. }
  32366. return this;
  32367. };
  32368. /**
  32369. * Flags an associated vertex buffer as updatable
  32370. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32371. * - BABYLON.VertexBuffer.PositionKind
  32372. * - BABYLON.VertexBuffer.UVKind
  32373. * - BABYLON.VertexBuffer.UV2Kind
  32374. * - BABYLON.VertexBuffer.UV3Kind
  32375. * - BABYLON.VertexBuffer.UV4Kind
  32376. * - BABYLON.VertexBuffer.UV5Kind
  32377. * - BABYLON.VertexBuffer.UV6Kind
  32378. * - BABYLON.VertexBuffer.ColorKind
  32379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32383. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32384. */
  32385. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32386. if (updatable === void 0) { updatable = true; }
  32387. var vb = this.getVertexBuffer(kind);
  32388. if (!vb || vb.isUpdatable() === updatable) {
  32389. return;
  32390. }
  32391. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32392. };
  32393. /**
  32394. * Sets the mesh global Vertex Buffer
  32395. * @param buffer defines the buffer to use
  32396. * @returns the current mesh
  32397. */
  32398. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32399. if (!this._geometry) {
  32400. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32401. }
  32402. this._geometry.setVerticesBuffer(buffer);
  32403. return this;
  32404. };
  32405. /**
  32406. * Update a specific associated vertex buffer
  32407. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32408. * - BABYLON.VertexBuffer.PositionKind
  32409. * - BABYLON.VertexBuffer.UVKind
  32410. * - BABYLON.VertexBuffer.UV2Kind
  32411. * - BABYLON.VertexBuffer.UV3Kind
  32412. * - BABYLON.VertexBuffer.UV4Kind
  32413. * - BABYLON.VertexBuffer.UV5Kind
  32414. * - BABYLON.VertexBuffer.UV6Kind
  32415. * - BABYLON.VertexBuffer.ColorKind
  32416. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32417. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32418. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32419. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32420. * @param data defines the data source
  32421. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32422. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  32423. * @returns the current mesh
  32424. */
  32425. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32426. if (!this._geometry) {
  32427. return this;
  32428. }
  32429. if (!makeItUnique) {
  32430. this._geometry.updateVerticesData(kind, data, updateExtends);
  32431. }
  32432. else {
  32433. this.makeGeometryUnique();
  32434. this.updateVerticesData(kind, data, updateExtends, false);
  32435. }
  32436. return this;
  32437. };
  32438. /**
  32439. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32440. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32441. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32442. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32443. * @returns the current mesh
  32444. */
  32445. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32446. if (computeNormals === void 0) { computeNormals = true; }
  32447. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32448. if (!positions) {
  32449. return this;
  32450. }
  32451. positionFunction(positions);
  32452. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32453. if (computeNormals) {
  32454. var indices = this.getIndices();
  32455. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32456. if (!normals) {
  32457. return this;
  32458. }
  32459. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32460. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32461. }
  32462. return this;
  32463. };
  32464. /**
  32465. * Creates a un-shared specific occurence of the geometry for the mesh.
  32466. * @returns the current mesh
  32467. */
  32468. Mesh.prototype.makeGeometryUnique = function () {
  32469. if (!this._geometry) {
  32470. return this;
  32471. }
  32472. var oldGeometry = this._geometry;
  32473. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32474. oldGeometry.releaseForMesh(this, true);
  32475. geometry.applyToMesh(this);
  32476. return this;
  32477. };
  32478. /**
  32479. * Set the index buffer of this mesh
  32480. * @param indices defines the source data
  32481. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32482. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32483. * @returns the current mesh
  32484. */
  32485. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32486. if (totalVertices === void 0) { totalVertices = null; }
  32487. if (updatable === void 0) { updatable = false; }
  32488. if (!this._geometry) {
  32489. var vertexData = new BABYLON.VertexData();
  32490. vertexData.indices = indices;
  32491. var scene = this.getScene();
  32492. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32493. }
  32494. else {
  32495. this._geometry.setIndices(indices, totalVertices, updatable);
  32496. }
  32497. return this;
  32498. };
  32499. /**
  32500. * Update the current index buffer
  32501. * @param indices defines the source data
  32502. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32503. * @returns the current mesh
  32504. */
  32505. Mesh.prototype.updateIndices = function (indices, offset) {
  32506. if (!this._geometry) {
  32507. return this;
  32508. }
  32509. this._geometry.updateIndices(indices, offset);
  32510. return this;
  32511. };
  32512. /**
  32513. * Invert the geometry to move from a right handed system to a left handed one.
  32514. * @returns the current mesh
  32515. */
  32516. Mesh.prototype.toLeftHanded = function () {
  32517. if (!this._geometry) {
  32518. return this;
  32519. }
  32520. this._geometry.toLeftHanded();
  32521. return this;
  32522. };
  32523. /** @hidden */
  32524. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32525. if (!this._geometry) {
  32526. return this;
  32527. }
  32528. var engine = this.getScene().getEngine();
  32529. // Wireframe
  32530. var indexToBind;
  32531. if (this._unIndexed) {
  32532. indexToBind = null;
  32533. }
  32534. else {
  32535. switch (fillMode) {
  32536. case BABYLON.Material.PointFillMode:
  32537. indexToBind = null;
  32538. break;
  32539. case BABYLON.Material.WireFrameFillMode:
  32540. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32541. break;
  32542. default:
  32543. case BABYLON.Material.TriangleFillMode:
  32544. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32545. break;
  32546. }
  32547. }
  32548. // VBOs
  32549. this._geometry._bind(effect, indexToBind);
  32550. return this;
  32551. };
  32552. /** @hidden */
  32553. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32554. if (alternate === void 0) { alternate = false; }
  32555. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32556. return this;
  32557. }
  32558. if (this._onBeforeDrawObservable) {
  32559. this._onBeforeDrawObservable.notifyObservers(this);
  32560. }
  32561. var scene = this.getScene();
  32562. var engine = scene.getEngine();
  32563. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32564. // or triangles as points
  32565. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32566. }
  32567. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32568. // Triangles as wireframe
  32569. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32570. }
  32571. else {
  32572. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32573. }
  32574. if (scene._isAlternateRenderingEnabled && !alternate) {
  32575. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32576. if (!effect || !scene.activeCamera) {
  32577. return this;
  32578. }
  32579. scene._switchToAlternateCameraConfiguration(true);
  32580. this._effectiveMaterial.bindView(effect);
  32581. this._effectiveMaterial.bindViewProjection(effect);
  32582. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32583. this._draw(subMesh, fillMode, instancesCount, true);
  32584. engine.setViewport(scene.activeCamera.viewport);
  32585. scene._switchToAlternateCameraConfiguration(false);
  32586. this._effectiveMaterial.bindView(effect);
  32587. this._effectiveMaterial.bindViewProjection(effect);
  32588. }
  32589. return this;
  32590. };
  32591. /**
  32592. * Registers for this mesh a javascript function called just before the rendering process
  32593. * @param func defines the function to call before rendering this mesh
  32594. * @returns the current mesh
  32595. */
  32596. Mesh.prototype.registerBeforeRender = function (func) {
  32597. this.onBeforeRenderObservable.add(func);
  32598. return this;
  32599. };
  32600. /**
  32601. * Disposes a previously registered javascript function called before the rendering
  32602. * @param func defines the function to remove
  32603. * @returns the current mesh
  32604. */
  32605. Mesh.prototype.unregisterBeforeRender = function (func) {
  32606. this.onBeforeRenderObservable.removeCallback(func);
  32607. return this;
  32608. };
  32609. /**
  32610. * Registers for this mesh a javascript function called just after the rendering is complete
  32611. * @param func defines the function to call after rendering this mesh
  32612. * @returns the current mesh
  32613. */
  32614. Mesh.prototype.registerAfterRender = function (func) {
  32615. this.onAfterRenderObservable.add(func);
  32616. return this;
  32617. };
  32618. /**
  32619. * Disposes a previously registered javascript function called after the rendering.
  32620. * @param func defines the function to remove
  32621. * @returns the current mesh
  32622. */
  32623. Mesh.prototype.unregisterAfterRender = function (func) {
  32624. this.onAfterRenderObservable.removeCallback(func);
  32625. return this;
  32626. };
  32627. /** @hidden */
  32628. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32629. var scene = this.getScene();
  32630. var batchCache = this._instanceDataStorage.batchCache;
  32631. batchCache.mustReturn = false;
  32632. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32633. batchCache.visibleInstances[subMeshId] = null;
  32634. if (this._instanceDataStorage.visibleInstances) {
  32635. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32636. var currentRenderId = scene.getRenderId();
  32637. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32638. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32639. var selfRenderId = this._renderId;
  32640. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32641. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32642. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32643. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32644. }
  32645. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32646. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32647. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32648. batchCache.mustReturn = true;
  32649. return batchCache;
  32650. }
  32651. if (currentRenderId !== selfRenderId) {
  32652. batchCache.renderSelf[subMeshId] = false;
  32653. }
  32654. }
  32655. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32656. }
  32657. return batchCache;
  32658. };
  32659. /** @hidden */
  32660. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32661. var visibleInstances = batch.visibleInstances[subMesh._id];
  32662. if (!visibleInstances) {
  32663. return this;
  32664. }
  32665. var matricesCount = visibleInstances.length + 1;
  32666. var bufferSize = matricesCount * 16 * 4;
  32667. var instanceStorage = this._instanceDataStorage;
  32668. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32669. var instancesBuffer = instanceStorage.instancesBuffer;
  32670. while (instanceStorage.instancesBufferSize < bufferSize) {
  32671. instanceStorage.instancesBufferSize *= 2;
  32672. }
  32673. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32674. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32675. }
  32676. var offset = 0;
  32677. var instancesCount = 0;
  32678. var world = this.getWorldMatrix();
  32679. if (batch.renderSelf[subMesh._id]) {
  32680. world.copyToArray(instanceStorage.instancesData, offset);
  32681. offset += 16;
  32682. instancesCount++;
  32683. }
  32684. if (visibleInstances) {
  32685. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32686. var instance = visibleInstances[instanceIndex];
  32687. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32688. offset += 16;
  32689. instancesCount++;
  32690. }
  32691. }
  32692. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32693. if (instancesBuffer) {
  32694. instancesBuffer.dispose();
  32695. }
  32696. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32697. instanceStorage.instancesBuffer = instancesBuffer;
  32698. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32699. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32700. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32701. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32702. }
  32703. else {
  32704. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32705. }
  32706. this._bind(subMesh, effect, fillMode);
  32707. this._draw(subMesh, fillMode, instancesCount);
  32708. engine.unbindInstanceAttributes();
  32709. return this;
  32710. };
  32711. /** @hidden */
  32712. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32713. var scene = this.getScene();
  32714. var engine = scene.getEngine();
  32715. if (hardwareInstancedRendering) {
  32716. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32717. }
  32718. else {
  32719. if (batch.renderSelf[subMesh._id]) {
  32720. // Draw
  32721. if (onBeforeDraw) {
  32722. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32723. }
  32724. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32725. }
  32726. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32727. if (visibleInstancesForSubMesh) {
  32728. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32729. var instance = visibleInstancesForSubMesh[instanceIndex];
  32730. // World
  32731. var world = instance.getWorldMatrix();
  32732. if (onBeforeDraw) {
  32733. onBeforeDraw(true, world, effectiveMaterial);
  32734. }
  32735. // Draw
  32736. this._draw(subMesh, fillMode);
  32737. }
  32738. }
  32739. }
  32740. return this;
  32741. };
  32742. /**
  32743. * 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
  32744. * @param subMesh defines the subMesh to render
  32745. * @param enableAlphaMode defines if alpha mode can be changed
  32746. * @returns the current mesh
  32747. */
  32748. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32749. if (this._checkOcclusionQuery()) {
  32750. return this;
  32751. }
  32752. var scene = this.getScene();
  32753. // Managing instances
  32754. var batch = this._getInstancesRenderList(subMesh._id);
  32755. if (batch.mustReturn) {
  32756. return this;
  32757. }
  32758. // Checking geometry state
  32759. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32760. return this;
  32761. }
  32762. if (this._onBeforeRenderObservable) {
  32763. this._onBeforeRenderObservable.notifyObservers(this);
  32764. }
  32765. var engine = scene.getEngine();
  32766. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32767. // Material
  32768. var material = subMesh.getMaterial();
  32769. if (!material) {
  32770. return this;
  32771. }
  32772. this._effectiveMaterial = material;
  32773. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32774. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32775. return this;
  32776. }
  32777. }
  32778. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32779. return this;
  32780. }
  32781. // Alpha mode
  32782. if (enableAlphaMode) {
  32783. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32784. }
  32785. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32786. var step = _a[_i];
  32787. step.action(this, subMesh, batch);
  32788. }
  32789. var effect;
  32790. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32791. effect = subMesh.effect;
  32792. }
  32793. else {
  32794. effect = this._effectiveMaterial.getEffect();
  32795. }
  32796. if (!effect) {
  32797. return this;
  32798. }
  32799. var sideOrientation = this.overrideMaterialSideOrientation;
  32800. if (sideOrientation == null) {
  32801. sideOrientation = this._effectiveMaterial.sideOrientation;
  32802. if (this._getWorldMatrixDeterminant() < 0) {
  32803. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32804. }
  32805. }
  32806. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32807. if (this._effectiveMaterial.forceDepthWrite) {
  32808. engine.setDepthWrite(true);
  32809. }
  32810. // Bind
  32811. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32812. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32813. this._bind(subMesh, effect, fillMode);
  32814. }
  32815. var world = this.getWorldMatrix();
  32816. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32817. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32818. }
  32819. else {
  32820. this._effectiveMaterial.bind(world, this);
  32821. }
  32822. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32823. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32824. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32825. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32826. }
  32827. // Draw
  32828. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32829. // Unbind
  32830. this._effectiveMaterial.unbind();
  32831. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32832. var step = _c[_b];
  32833. step.action(this, subMesh, batch);
  32834. }
  32835. if (this._onAfterRenderObservable) {
  32836. this._onAfterRenderObservable.notifyObservers(this);
  32837. }
  32838. return this;
  32839. };
  32840. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32841. if (isInstance && effectiveMaterial) {
  32842. effectiveMaterial.bindOnlyWorldMatrix(world);
  32843. }
  32844. };
  32845. /**
  32846. * Normalize matrix weights so that all vertices have a total weight set to 1
  32847. */
  32848. Mesh.prototype.cleanMatrixWeights = function () {
  32849. var epsilon = 1e-3;
  32850. var noInfluenceBoneIndex = 0.0;
  32851. if (this.skeleton) {
  32852. noInfluenceBoneIndex = this.skeleton.bones.length;
  32853. }
  32854. else {
  32855. return;
  32856. }
  32857. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32858. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32859. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32860. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32861. var influencers = this.numBoneInfluencers;
  32862. var size = matricesWeights.length;
  32863. for (var i = 0; i < size; i += 4) {
  32864. var weight = 0.0;
  32865. var firstZeroWeight = -1;
  32866. for (var j = 0; j < 4; j++) {
  32867. var w = matricesWeights[i + j];
  32868. weight += w;
  32869. if (w < epsilon && firstZeroWeight < 0) {
  32870. firstZeroWeight = j;
  32871. }
  32872. }
  32873. if (matricesWeightsExtra) {
  32874. for (var j = 0; j < 4; j++) {
  32875. var w = matricesWeightsExtra[i + j];
  32876. weight += w;
  32877. if (w < epsilon && firstZeroWeight < 0) {
  32878. firstZeroWeight = j + 4;
  32879. }
  32880. }
  32881. }
  32882. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32883. firstZeroWeight = influencers - 1;
  32884. }
  32885. if (weight > epsilon) {
  32886. var mweight = 1.0 / weight;
  32887. for (var j = 0; j < 4; j++) {
  32888. matricesWeights[i + j] *= mweight;
  32889. }
  32890. if (matricesWeightsExtra) {
  32891. for (var j = 0; j < 4; j++) {
  32892. matricesWeightsExtra[i + j] *= mweight;
  32893. }
  32894. }
  32895. }
  32896. else {
  32897. if (firstZeroWeight >= 4) {
  32898. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32899. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32900. }
  32901. else {
  32902. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32903. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32904. }
  32905. }
  32906. }
  32907. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32908. if (matricesIndicesExtra) {
  32909. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32910. }
  32911. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32912. if (matricesWeightsExtra) {
  32913. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32914. }
  32915. };
  32916. /** @hidden */
  32917. Mesh.prototype._checkDelayState = function () {
  32918. var scene = this.getScene();
  32919. if (this._geometry) {
  32920. this._geometry.load(scene);
  32921. }
  32922. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32924. this._queueLoad(scene);
  32925. }
  32926. return this;
  32927. };
  32928. Mesh.prototype._queueLoad = function (scene) {
  32929. var _this = this;
  32930. scene._addPendingData(this);
  32931. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32932. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32933. if (data instanceof ArrayBuffer) {
  32934. _this._delayLoadingFunction(data, _this);
  32935. }
  32936. else {
  32937. _this._delayLoadingFunction(JSON.parse(data), _this);
  32938. }
  32939. _this.instances.forEach(function (instance) {
  32940. instance._syncSubMeshes();
  32941. });
  32942. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32943. scene._removePendingData(_this);
  32944. }, function () { }, scene.database, getBinaryData);
  32945. return this;
  32946. };
  32947. /**
  32948. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32949. * A mesh is in the frustum if its bounding box intersects the frustum
  32950. * @param frustumPlanes defines the frustum to test
  32951. * @returns true if the mesh is in the frustum planes
  32952. */
  32953. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32954. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32955. return false;
  32956. }
  32957. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32958. return false;
  32959. }
  32960. this._checkDelayState();
  32961. return true;
  32962. };
  32963. /**
  32964. * Sets the mesh material by the material or multiMaterial `id` property
  32965. * @param id is a string identifying the material or the multiMaterial
  32966. * @returns the current mesh
  32967. */
  32968. Mesh.prototype.setMaterialByID = function (id) {
  32969. var materials = this.getScene().materials;
  32970. var index;
  32971. for (index = materials.length - 1; index > -1; index--) {
  32972. if (materials[index].id === id) {
  32973. this.material = materials[index];
  32974. return this;
  32975. }
  32976. }
  32977. // Multi
  32978. var multiMaterials = this.getScene().multiMaterials;
  32979. for (index = multiMaterials.length - 1; index > -1; index--) {
  32980. if (multiMaterials[index].id === id) {
  32981. this.material = multiMaterials[index];
  32982. return this;
  32983. }
  32984. }
  32985. return this;
  32986. };
  32987. /**
  32988. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32989. * @returns an array of IAnimatable
  32990. */
  32991. Mesh.prototype.getAnimatables = function () {
  32992. var results = new Array();
  32993. if (this.material) {
  32994. results.push(this.material);
  32995. }
  32996. if (this.skeleton) {
  32997. results.push(this.skeleton);
  32998. }
  32999. return results;
  33000. };
  33001. /**
  33002. * Modifies the mesh geometry according to the passed transformation matrix.
  33003. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33004. * The mesh normals are modified using the same transformation.
  33005. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33006. * @param transform defines the transform matrix to use
  33007. * @see http://doc.babylonjs.com/resources/baking_transformations
  33008. * @returns the current mesh
  33009. */
  33010. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33011. // Position
  33012. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33013. return this;
  33014. }
  33015. var submeshes = this.subMeshes.splice(0);
  33016. this._resetPointsArrayCache();
  33017. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33018. var temp = new Array();
  33019. var index;
  33020. for (index = 0; index < data.length; index += 3) {
  33021. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33022. }
  33023. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33024. // Normals
  33025. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33026. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33027. temp = [];
  33028. for (index = 0; index < data.length; index += 3) {
  33029. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33030. }
  33031. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33032. }
  33033. // flip faces?
  33034. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33035. this.flipFaces();
  33036. }
  33037. // Restore submeshes
  33038. this.releaseSubMeshes();
  33039. this.subMeshes = submeshes;
  33040. return this;
  33041. };
  33042. /**
  33043. * Modifies the mesh geometry according to its own current World Matrix.
  33044. * The mesh World Matrix is then reset.
  33045. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33046. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33047. * @see http://doc.babylonjs.com/resources/baking_transformations
  33048. * @returns the current mesh
  33049. */
  33050. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33051. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33052. this.scaling.copyFromFloats(1, 1, 1);
  33053. this.position.copyFromFloats(0, 0, 0);
  33054. this.rotation.copyFromFloats(0, 0, 0);
  33055. //only if quaternion is already set
  33056. if (this.rotationQuaternion) {
  33057. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33058. }
  33059. this._worldMatrix = BABYLON.Matrix.Identity();
  33060. return this;
  33061. };
  33062. Object.defineProperty(Mesh.prototype, "_positions", {
  33063. // Cache
  33064. /** @hidden */
  33065. get: function () {
  33066. if (this._geometry) {
  33067. return this._geometry._positions;
  33068. }
  33069. return null;
  33070. },
  33071. enumerable: true,
  33072. configurable: true
  33073. });
  33074. /** @hidden */
  33075. Mesh.prototype._resetPointsArrayCache = function () {
  33076. if (this._geometry) {
  33077. this._geometry._resetPointsArrayCache();
  33078. }
  33079. return this;
  33080. };
  33081. /** @hidden */
  33082. Mesh.prototype._generatePointsArray = function () {
  33083. if (this._geometry) {
  33084. return this._geometry._generatePointsArray();
  33085. }
  33086. return false;
  33087. };
  33088. /**
  33089. * Returns a new Mesh object generated from the current mesh properties.
  33090. * This method must not get confused with createInstance()
  33091. * @param name is a string, the name given to the new mesh
  33092. * @param newParent can be any Node object (default `null`)
  33093. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33094. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33095. * @returns a new mesh
  33096. */
  33097. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33098. if (name === void 0) { name = ""; }
  33099. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33100. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33101. };
  33102. /**
  33103. * Releases resources associated with this mesh.
  33104. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33105. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33106. */
  33107. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33108. var _this = this;
  33109. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33110. this.morphTargetManager = null;
  33111. if (this._geometry) {
  33112. this._geometry.releaseForMesh(this, true);
  33113. }
  33114. if (this._onBeforeDrawObservable) {
  33115. this._onBeforeDrawObservable.clear();
  33116. }
  33117. if (this._onBeforeRenderObservable) {
  33118. this._onBeforeRenderObservable.clear();
  33119. }
  33120. if (this._onAfterRenderObservable) {
  33121. this._onAfterRenderObservable.clear();
  33122. }
  33123. // Sources
  33124. var meshes = this.getScene().meshes;
  33125. meshes.forEach(function (abstractMesh) {
  33126. var mesh = abstractMesh;
  33127. if (mesh._source && mesh._source === _this) {
  33128. mesh._source = null;
  33129. }
  33130. });
  33131. this._source = null;
  33132. // Instances
  33133. if (this._instanceDataStorage.instancesBuffer) {
  33134. this._instanceDataStorage.instancesBuffer.dispose();
  33135. this._instanceDataStorage.instancesBuffer = null;
  33136. }
  33137. while (this.instances.length) {
  33138. this.instances[0].dispose();
  33139. }
  33140. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33141. };
  33142. /**
  33143. * Modifies the mesh geometry according to a displacement map.
  33144. * 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.
  33145. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33146. * @param url is a string, the URL from the image file is to be downloaded.
  33147. * @param minHeight is the lower limit of the displacement.
  33148. * @param maxHeight is the upper limit of the displacement.
  33149. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33150. * @param uvOffset is an optional vector2 used to offset UV.
  33151. * @param uvScale is an optional vector2 used to scale UV.
  33152. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33153. * @returns the Mesh.
  33154. */
  33155. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33156. var _this = this;
  33157. if (forceUpdate === void 0) { forceUpdate = false; }
  33158. var scene = this.getScene();
  33159. var onload = function (img) {
  33160. // Getting height map data
  33161. var canvas = document.createElement("canvas");
  33162. var context = canvas.getContext("2d");
  33163. var heightMapWidth = img.width;
  33164. var heightMapHeight = img.height;
  33165. canvas.width = heightMapWidth;
  33166. canvas.height = heightMapHeight;
  33167. context.drawImage(img, 0, 0);
  33168. // Create VertexData from map data
  33169. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33170. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33171. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33172. //execute success callback, if set
  33173. if (onSuccess) {
  33174. onSuccess(_this);
  33175. }
  33176. };
  33177. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33178. return this;
  33179. };
  33180. /**
  33181. * Modifies the mesh geometry according to a displacementMap buffer.
  33182. * 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.
  33183. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33184. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33185. * @param heightMapWidth is the width of the buffer image.
  33186. * @param heightMapHeight is the height of the buffer image.
  33187. * @param minHeight is the lower limit of the displacement.
  33188. * @param maxHeight is the upper limit of the displacement.
  33189. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33190. * @param uvOffset is an optional vector2 used to offset UV.
  33191. * @param uvScale is an optional vector2 used to scale UV.
  33192. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  33193. * @returns the Mesh.
  33194. */
  33195. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33196. if (forceUpdate === void 0) { forceUpdate = false; }
  33197. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33198. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33199. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33200. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33201. return this;
  33202. }
  33203. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33204. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33205. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33206. var position = BABYLON.Vector3.Zero();
  33207. var normal = BABYLON.Vector3.Zero();
  33208. var uv = BABYLON.Vector2.Zero();
  33209. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33210. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33211. for (var index = 0; index < positions.length; index += 3) {
  33212. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33213. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33214. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33215. // Compute height
  33216. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33217. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33218. var pos = (u + v * heightMapWidth) * 4;
  33219. var r = buffer[pos] / 255.0;
  33220. var g = buffer[pos + 1] / 255.0;
  33221. var b = buffer[pos + 2] / 255.0;
  33222. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33223. normal.normalize();
  33224. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33225. position = position.add(normal);
  33226. position.toArray(positions, index);
  33227. }
  33228. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33229. if (forceUpdate) {
  33230. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33231. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33232. }
  33233. else {
  33234. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33235. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33236. }
  33237. return this;
  33238. };
  33239. /**
  33240. * Modify the mesh to get a flat shading rendering.
  33241. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33242. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33243. * @returns current mesh
  33244. */
  33245. Mesh.prototype.convertToFlatShadedMesh = function () {
  33246. var kinds = this.getVerticesDataKinds();
  33247. var vbs = {};
  33248. var data = {};
  33249. var newdata = {};
  33250. var updatableNormals = false;
  33251. var kindIndex;
  33252. var kind;
  33253. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33254. kind = kinds[kindIndex];
  33255. var vertexBuffer = this.getVertexBuffer(kind);
  33256. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33257. updatableNormals = vertexBuffer.isUpdatable();
  33258. kinds.splice(kindIndex, 1);
  33259. kindIndex--;
  33260. continue;
  33261. }
  33262. vbs[kind] = vertexBuffer;
  33263. data[kind] = vbs[kind].getData();
  33264. newdata[kind] = [];
  33265. }
  33266. // Save previous submeshes
  33267. var previousSubmeshes = this.subMeshes.slice(0);
  33268. var indices = this.getIndices();
  33269. var totalIndices = this.getTotalIndices();
  33270. // Generating unique vertices per face
  33271. var index;
  33272. for (index = 0; index < totalIndices; index++) {
  33273. var vertexIndex = indices[index];
  33274. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33275. kind = kinds[kindIndex];
  33276. var stride = vbs[kind].getStrideSize();
  33277. for (var offset = 0; offset < stride; offset++) {
  33278. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33279. }
  33280. }
  33281. }
  33282. // Updating faces & normal
  33283. var normals = [];
  33284. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33285. for (index = 0; index < totalIndices; index += 3) {
  33286. indices[index] = index;
  33287. indices[index + 1] = index + 1;
  33288. indices[index + 2] = index + 2;
  33289. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33290. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33291. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33292. var p1p2 = p1.subtract(p2);
  33293. var p3p2 = p3.subtract(p2);
  33294. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33295. // Store same normals for every vertex
  33296. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33297. normals.push(normal.x);
  33298. normals.push(normal.y);
  33299. normals.push(normal.z);
  33300. }
  33301. }
  33302. this.setIndices(indices);
  33303. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33304. // Updating vertex buffers
  33305. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33306. kind = kinds[kindIndex];
  33307. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33308. }
  33309. // Updating submeshes
  33310. this.releaseSubMeshes();
  33311. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33312. var previousOne = previousSubmeshes[submeshIndex];
  33313. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33314. }
  33315. this.synchronizeInstances();
  33316. return this;
  33317. };
  33318. /**
  33319. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33320. * In other words, more vertices, no more indices and a single bigger VBO.
  33321. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33322. * @returns current mesh
  33323. */
  33324. Mesh.prototype.convertToUnIndexedMesh = function () {
  33325. var kinds = this.getVerticesDataKinds();
  33326. var vbs = {};
  33327. var data = {};
  33328. var newdata = {};
  33329. var kindIndex;
  33330. var kind;
  33331. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33332. kind = kinds[kindIndex];
  33333. var vertexBuffer = this.getVertexBuffer(kind);
  33334. vbs[kind] = vertexBuffer;
  33335. data[kind] = vbs[kind].getData();
  33336. newdata[kind] = [];
  33337. }
  33338. // Save previous submeshes
  33339. var previousSubmeshes = this.subMeshes.slice(0);
  33340. var indices = this.getIndices();
  33341. var totalIndices = this.getTotalIndices();
  33342. // Generating unique vertices per face
  33343. var index;
  33344. for (index = 0; index < totalIndices; index++) {
  33345. var vertexIndex = indices[index];
  33346. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33347. kind = kinds[kindIndex];
  33348. var stride = vbs[kind].getStrideSize();
  33349. for (var offset = 0; offset < stride; offset++) {
  33350. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33351. }
  33352. }
  33353. }
  33354. // Updating indices
  33355. for (index = 0; index < totalIndices; index += 3) {
  33356. indices[index] = index;
  33357. indices[index + 1] = index + 1;
  33358. indices[index + 2] = index + 2;
  33359. }
  33360. this.setIndices(indices);
  33361. // Updating vertex buffers
  33362. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33363. kind = kinds[kindIndex];
  33364. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33365. }
  33366. // Updating submeshes
  33367. this.releaseSubMeshes();
  33368. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33369. var previousOne = previousSubmeshes[submeshIndex];
  33370. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33371. }
  33372. this._unIndexed = true;
  33373. this.synchronizeInstances();
  33374. return this;
  33375. };
  33376. /**
  33377. * Inverses facet orientations.
  33378. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33379. * @param flipNormals will also inverts the normals
  33380. * @returns current mesh
  33381. */
  33382. Mesh.prototype.flipFaces = function (flipNormals) {
  33383. if (flipNormals === void 0) { flipNormals = false; }
  33384. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33385. var i;
  33386. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33387. for (i = 0; i < vertex_data.normals.length; i++) {
  33388. vertex_data.normals[i] *= -1;
  33389. }
  33390. }
  33391. if (vertex_data.indices) {
  33392. var temp;
  33393. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33394. // reassign indices
  33395. temp = vertex_data.indices[i + 1];
  33396. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33397. vertex_data.indices[i + 2] = temp;
  33398. }
  33399. }
  33400. vertex_data.applyToMesh(this);
  33401. return this;
  33402. };
  33403. // Instances
  33404. /**
  33405. * Creates a new InstancedMesh object from the mesh model.
  33406. * Warning : this method is not supported for Line mesh and LineSystem
  33407. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33408. * @param name defines the name of the new instance
  33409. * @returns a new InstancedMesh
  33410. */
  33411. Mesh.prototype.createInstance = function (name) {
  33412. return new BABYLON.InstancedMesh(name, this);
  33413. };
  33414. /**
  33415. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33416. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33417. * @returns the current mesh
  33418. */
  33419. Mesh.prototype.synchronizeInstances = function () {
  33420. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33421. var instance = this.instances[instanceIndex];
  33422. instance._syncSubMeshes();
  33423. }
  33424. return this;
  33425. };
  33426. /**
  33427. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33428. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33429. * This should be used together with the simplification to avoid disappearing triangles.
  33430. * @param successCallback an optional success callback to be called after the optimization finished.
  33431. * @returns the current mesh
  33432. */
  33433. Mesh.prototype.optimizeIndices = function (successCallback) {
  33434. var _this = this;
  33435. var indices = this.getIndices();
  33436. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33437. if (!positions || !indices) {
  33438. return this;
  33439. }
  33440. var vectorPositions = new Array();
  33441. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33442. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33443. }
  33444. var dupes = new Array();
  33445. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33446. var realPos = vectorPositions.length - 1 - iteration;
  33447. var testedPosition = vectorPositions[realPos];
  33448. for (var j = 0; j < realPos; ++j) {
  33449. var againstPosition = vectorPositions[j];
  33450. if (testedPosition.equals(againstPosition)) {
  33451. dupes[realPos] = j;
  33452. break;
  33453. }
  33454. }
  33455. }, function () {
  33456. for (var i = 0; i < indices.length; ++i) {
  33457. indices[i] = dupes[indices[i]] || indices[i];
  33458. }
  33459. //indices are now reordered
  33460. var originalSubMeshes = _this.subMeshes.slice(0);
  33461. _this.setIndices(indices);
  33462. _this.subMeshes = originalSubMeshes;
  33463. if (successCallback) {
  33464. successCallback(_this);
  33465. }
  33466. });
  33467. return this;
  33468. };
  33469. /**
  33470. * Serialize current mesh
  33471. * @param serializationObject defines the object which will receive the serialization data
  33472. */
  33473. Mesh.prototype.serialize = function (serializationObject) {
  33474. serializationObject.name = this.name;
  33475. serializationObject.id = this.id;
  33476. serializationObject.type = this.getClassName();
  33477. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33478. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33479. }
  33480. serializationObject.position = this.position.asArray();
  33481. if (this.rotationQuaternion) {
  33482. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33483. }
  33484. else if (this.rotation) {
  33485. serializationObject.rotation = this.rotation.asArray();
  33486. }
  33487. serializationObject.scaling = this.scaling.asArray();
  33488. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33489. serializationObject.isEnabled = this.isEnabled(false);
  33490. serializationObject.isVisible = this.isVisible;
  33491. serializationObject.infiniteDistance = this.infiniteDistance;
  33492. serializationObject.pickable = this.isPickable;
  33493. serializationObject.receiveShadows = this.receiveShadows;
  33494. serializationObject.billboardMode = this.billboardMode;
  33495. serializationObject.visibility = this.visibility;
  33496. serializationObject.checkCollisions = this.checkCollisions;
  33497. serializationObject.isBlocker = this.isBlocker;
  33498. // Parent
  33499. if (this.parent) {
  33500. serializationObject.parentId = this.parent.id;
  33501. }
  33502. // Geometry
  33503. serializationObject.isUnIndexed = this.isUnIndexed;
  33504. var geometry = this._geometry;
  33505. if (geometry) {
  33506. var geometryId = geometry.id;
  33507. serializationObject.geometryId = geometryId;
  33508. // SubMeshes
  33509. serializationObject.subMeshes = [];
  33510. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33511. var subMesh = this.subMeshes[subIndex];
  33512. serializationObject.subMeshes.push({
  33513. materialIndex: subMesh.materialIndex,
  33514. verticesStart: subMesh.verticesStart,
  33515. verticesCount: subMesh.verticesCount,
  33516. indexStart: subMesh.indexStart,
  33517. indexCount: subMesh.indexCount
  33518. });
  33519. }
  33520. }
  33521. // Material
  33522. if (this.material) {
  33523. serializationObject.materialId = this.material.id;
  33524. }
  33525. else {
  33526. this.material = null;
  33527. }
  33528. // Morph targets
  33529. if (this.morphTargetManager) {
  33530. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33531. }
  33532. // Skeleton
  33533. if (this.skeleton) {
  33534. serializationObject.skeletonId = this.skeleton.id;
  33535. }
  33536. // Physics
  33537. //TODO implement correct serialization for physics impostors.
  33538. var impostor = this.getPhysicsImpostor();
  33539. if (impostor) {
  33540. serializationObject.physicsMass = impostor.getParam("mass");
  33541. serializationObject.physicsFriction = impostor.getParam("friction");
  33542. serializationObject.physicsRestitution = impostor.getParam("mass");
  33543. serializationObject.physicsImpostor = impostor.type;
  33544. }
  33545. // Metadata
  33546. if (this.metadata) {
  33547. serializationObject.metadata = this.metadata;
  33548. }
  33549. // Instances
  33550. serializationObject.instances = [];
  33551. for (var index = 0; index < this.instances.length; index++) {
  33552. var instance = this.instances[index];
  33553. if (instance.doNotSerialize) {
  33554. continue;
  33555. }
  33556. var serializationInstance = {
  33557. name: instance.name,
  33558. id: instance.id,
  33559. position: instance.position.asArray(),
  33560. scaling: instance.scaling.asArray()
  33561. };
  33562. if (instance.parent) {
  33563. serializationInstance.parentId = instance.parent.id;
  33564. }
  33565. if (instance.rotationQuaternion) {
  33566. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33567. }
  33568. else if (instance.rotation) {
  33569. serializationInstance.rotation = instance.rotation.asArray();
  33570. }
  33571. serializationObject.instances.push(serializationInstance);
  33572. // Animations
  33573. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33574. serializationInstance.ranges = instance.serializeAnimationRanges();
  33575. }
  33576. //
  33577. // Animations
  33578. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33579. serializationObject.ranges = this.serializeAnimationRanges();
  33580. // Layer mask
  33581. serializationObject.layerMask = this.layerMask;
  33582. // Alpha
  33583. serializationObject.alphaIndex = this.alphaIndex;
  33584. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33585. // Overlay
  33586. serializationObject.overlayAlpha = this.overlayAlpha;
  33587. serializationObject.overlayColor = this.overlayColor.asArray();
  33588. serializationObject.renderOverlay = this.renderOverlay;
  33589. // Fog
  33590. serializationObject.applyFog = this.applyFog;
  33591. // Action Manager
  33592. if (this.actionManager) {
  33593. serializationObject.actions = this.actionManager.serialize(this.name);
  33594. }
  33595. };
  33596. /** @hidden */
  33597. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33598. if (!this.geometry) {
  33599. return;
  33600. }
  33601. this._markSubMeshesAsAttributesDirty();
  33602. var morphTargetManager = this._morphTargetManager;
  33603. if (morphTargetManager && morphTargetManager.vertexCount) {
  33604. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33605. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33606. this.morphTargetManager = null;
  33607. return;
  33608. }
  33609. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33610. var morphTarget = morphTargetManager.getActiveTarget(index);
  33611. var positions = morphTarget.getPositions();
  33612. if (!positions) {
  33613. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33614. return;
  33615. }
  33616. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33617. var normals = morphTarget.getNormals();
  33618. if (normals) {
  33619. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33620. }
  33621. var tangents = morphTarget.getTangents();
  33622. if (tangents) {
  33623. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33624. }
  33625. }
  33626. }
  33627. else {
  33628. var index = 0;
  33629. // Positions
  33630. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33631. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33632. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33633. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33634. }
  33635. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33636. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33637. }
  33638. index++;
  33639. }
  33640. }
  33641. };
  33642. // Statics
  33643. /**
  33644. * Returns a new Mesh object parsed from the source provided.
  33645. * @param parsedMesh is the source
  33646. * @param scene defines the hosting scene
  33647. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33648. * @returns a new Mesh
  33649. */
  33650. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33651. var mesh;
  33652. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33653. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33654. }
  33655. else {
  33656. mesh = new Mesh(parsedMesh.name, scene);
  33657. }
  33658. mesh.id = parsedMesh.id;
  33659. if (BABYLON.Tags) {
  33660. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33661. }
  33662. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33663. if (parsedMesh.metadata !== undefined) {
  33664. mesh.metadata = parsedMesh.metadata;
  33665. }
  33666. if (parsedMesh.rotationQuaternion) {
  33667. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33668. }
  33669. else if (parsedMesh.rotation) {
  33670. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33671. }
  33672. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33673. if (parsedMesh.localMatrix) {
  33674. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33675. }
  33676. else if (parsedMesh.pivotMatrix) {
  33677. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33678. }
  33679. mesh.setEnabled(parsedMesh.isEnabled);
  33680. mesh.isVisible = parsedMesh.isVisible;
  33681. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33682. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33683. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33684. if (parsedMesh.applyFog !== undefined) {
  33685. mesh.applyFog = parsedMesh.applyFog;
  33686. }
  33687. if (parsedMesh.pickable !== undefined) {
  33688. mesh.isPickable = parsedMesh.pickable;
  33689. }
  33690. if (parsedMesh.alphaIndex !== undefined) {
  33691. mesh.alphaIndex = parsedMesh.alphaIndex;
  33692. }
  33693. mesh.receiveShadows = parsedMesh.receiveShadows;
  33694. mesh.billboardMode = parsedMesh.billboardMode;
  33695. if (parsedMesh.visibility !== undefined) {
  33696. mesh.visibility = parsedMesh.visibility;
  33697. }
  33698. mesh.checkCollisions = parsedMesh.checkCollisions;
  33699. if (parsedMesh.isBlocker !== undefined) {
  33700. mesh.isBlocker = parsedMesh.isBlocker;
  33701. }
  33702. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33703. // freezeWorldMatrix
  33704. if (parsedMesh.freezeWorldMatrix) {
  33705. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33706. }
  33707. // Parent
  33708. if (parsedMesh.parentId) {
  33709. mesh._waitingParentId = parsedMesh.parentId;
  33710. }
  33711. // Actions
  33712. if (parsedMesh.actions !== undefined) {
  33713. mesh._waitingActions = parsedMesh.actions;
  33714. }
  33715. // Overlay
  33716. if (parsedMesh.overlayAlpha !== undefined) {
  33717. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33718. }
  33719. if (parsedMesh.overlayColor !== undefined) {
  33720. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33721. }
  33722. if (parsedMesh.renderOverlay !== undefined) {
  33723. mesh.renderOverlay = parsedMesh.renderOverlay;
  33724. }
  33725. // Geometry
  33726. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33727. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33728. if (parsedMesh.delayLoadingFile) {
  33729. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33730. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33731. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33732. if (parsedMesh._binaryInfo) {
  33733. mesh._binaryInfo = parsedMesh._binaryInfo;
  33734. }
  33735. mesh._delayInfo = [];
  33736. if (parsedMesh.hasUVs) {
  33737. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33738. }
  33739. if (parsedMesh.hasUVs2) {
  33740. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33741. }
  33742. if (parsedMesh.hasUVs3) {
  33743. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33744. }
  33745. if (parsedMesh.hasUVs4) {
  33746. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33747. }
  33748. if (parsedMesh.hasUVs5) {
  33749. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33750. }
  33751. if (parsedMesh.hasUVs6) {
  33752. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33753. }
  33754. if (parsedMesh.hasColors) {
  33755. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33756. }
  33757. if (parsedMesh.hasMatricesIndices) {
  33758. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33759. }
  33760. if (parsedMesh.hasMatricesWeights) {
  33761. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33762. }
  33763. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33764. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33765. mesh._checkDelayState();
  33766. }
  33767. }
  33768. else {
  33769. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33770. }
  33771. // Material
  33772. if (parsedMesh.materialId) {
  33773. mesh.setMaterialByID(parsedMesh.materialId);
  33774. }
  33775. else {
  33776. mesh.material = null;
  33777. }
  33778. // Morph targets
  33779. if (parsedMesh.morphTargetManagerId > -1) {
  33780. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33781. }
  33782. // Skeleton
  33783. if (parsedMesh.skeletonId > -1) {
  33784. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33785. if (parsedMesh.numBoneInfluencers) {
  33786. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33787. }
  33788. }
  33789. // Animations
  33790. if (parsedMesh.animations) {
  33791. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33792. var parsedAnimation = parsedMesh.animations[animationIndex];
  33793. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33794. }
  33795. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33796. }
  33797. if (parsedMesh.autoAnimate) {
  33798. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33799. }
  33800. // Layer Mask
  33801. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33802. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33803. }
  33804. else {
  33805. mesh.layerMask = 0x0FFFFFFF;
  33806. }
  33807. // Physics
  33808. if (parsedMesh.physicsImpostor) {
  33809. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33810. mass: parsedMesh.physicsMass,
  33811. friction: parsedMesh.physicsFriction,
  33812. restitution: parsedMesh.physicsRestitution
  33813. }, scene);
  33814. }
  33815. // Instances
  33816. if (parsedMesh.instances) {
  33817. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33818. var parsedInstance = parsedMesh.instances[index];
  33819. var instance = mesh.createInstance(parsedInstance.name);
  33820. if (parsedInstance.id) {
  33821. instance.id = parsedInstance.id;
  33822. }
  33823. if (BABYLON.Tags) {
  33824. if (parsedInstance.tags) {
  33825. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33826. }
  33827. else {
  33828. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33829. }
  33830. }
  33831. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33832. if (parsedInstance.parentId) {
  33833. instance._waitingParentId = parsedInstance.parentId;
  33834. }
  33835. if (parsedInstance.rotationQuaternion) {
  33836. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33837. }
  33838. else if (parsedInstance.rotation) {
  33839. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33840. }
  33841. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33842. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33843. instance.checkCollisions = parsedInstance.checkCollisions;
  33844. }
  33845. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33846. instance.isPickable = parsedInstance.pickable;
  33847. }
  33848. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33849. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33850. }
  33851. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33852. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33853. }
  33854. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33855. instance.alphaIndex = parsedInstance.alphaIndex;
  33856. }
  33857. // Physics
  33858. if (parsedInstance.physicsImpostor) {
  33859. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33860. mass: parsedInstance.physicsMass,
  33861. friction: parsedInstance.physicsFriction,
  33862. restitution: parsedInstance.physicsRestitution
  33863. }, scene);
  33864. }
  33865. // Animation
  33866. if (parsedInstance.animations) {
  33867. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33868. parsedAnimation = parsedInstance.animations[animationIndex];
  33869. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33870. }
  33871. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33872. if (parsedInstance.autoAnimate) {
  33873. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33874. }
  33875. }
  33876. }
  33877. }
  33878. return mesh;
  33879. };
  33880. /**
  33881. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33882. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33883. * @param name defines the name of the mesh to create
  33884. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33885. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33886. * @param closePath creates a seam between the first and the last points of each path of the path array
  33887. * @param offset is taken in account only if the `pathArray` is containing a single path
  33888. * @param scene defines the hosting scene
  33889. * @param updatable defines if the mesh must be flagged as updatable
  33890. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33891. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33892. * @returns a new Mesh
  33893. */
  33894. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33895. if (closeArray === void 0) { closeArray = false; }
  33896. if (updatable === void 0) { updatable = false; }
  33897. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33898. pathArray: pathArray,
  33899. closeArray: closeArray,
  33900. closePath: closePath,
  33901. offset: offset,
  33902. updatable: updatable,
  33903. sideOrientation: sideOrientation,
  33904. instance: instance
  33905. }, scene);
  33906. };
  33907. /**
  33908. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33909. * @param name defines the name of the mesh to create
  33910. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33911. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  33912. * @param scene defines the hosting scene
  33913. * @param updatable defines if the mesh must be flagged as updatable
  33914. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33915. * @returns a new Mesh
  33916. */
  33917. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33918. if (scene === void 0) { scene = null; }
  33919. var options = {
  33920. radius: radius,
  33921. tessellation: tessellation,
  33922. sideOrientation: sideOrientation,
  33923. updatable: updatable
  33924. };
  33925. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33926. };
  33927. /**
  33928. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33929. * @param name defines the name of the mesh to create
  33930. * @param size sets the size (float) of each box side (default 1)
  33931. * @param scene defines the hosting scene
  33932. * @param updatable defines if the mesh must be flagged as updatable
  33933. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33934. * @returns a new Mesh
  33935. */
  33936. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33937. if (scene === void 0) { scene = null; }
  33938. var options = {
  33939. size: size,
  33940. sideOrientation: sideOrientation,
  33941. updatable: updatable
  33942. };
  33943. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33944. };
  33945. /**
  33946. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33947. * @param name defines the name of the mesh to create
  33948. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33949. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33950. * @param scene defines the hosting scene
  33951. * @param updatable defines if the mesh must be flagged as updatable
  33952. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33953. * @returns a new Mesh
  33954. */
  33955. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33956. var options = {
  33957. segments: segments,
  33958. diameterX: diameter,
  33959. diameterY: diameter,
  33960. diameterZ: diameter,
  33961. sideOrientation: sideOrientation,
  33962. updatable: updatable
  33963. };
  33964. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33965. };
  33966. /**
  33967. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33968. * @param name defines the name of the mesh to create
  33969. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33970. * @param diameterTop set the top cap diameter (floats, default 1)
  33971. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33972. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33973. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33974. * @param scene defines the hosting scene
  33975. * @param updatable defines if the mesh must be flagged as updatable
  33976. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33977. * @returns a new Mesh
  33978. */
  33979. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33980. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33981. if (scene !== undefined) {
  33982. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33983. updatable = scene;
  33984. }
  33985. scene = subdivisions;
  33986. subdivisions = 1;
  33987. }
  33988. var options = {
  33989. height: height,
  33990. diameterTop: diameterTop,
  33991. diameterBottom: diameterBottom,
  33992. tessellation: tessellation,
  33993. subdivisions: subdivisions,
  33994. sideOrientation: sideOrientation,
  33995. updatable: updatable
  33996. };
  33997. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33998. };
  33999. // Torus (Code from SharpDX.org)
  34000. /**
  34001. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34002. * @param name defines the name of the mesh to create
  34003. * @param diameter sets the diameter size (float) of the torus (default 1)
  34004. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34005. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34006. * @param scene defines the hosting scene
  34007. * @param updatable defines if the mesh must be flagged as updatable
  34008. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34009. * @returns a new Mesh
  34010. */
  34011. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34012. var options = {
  34013. diameter: diameter,
  34014. thickness: thickness,
  34015. tessellation: tessellation,
  34016. sideOrientation: sideOrientation,
  34017. updatable: updatable
  34018. };
  34019. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34020. };
  34021. /**
  34022. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34023. * @param name defines the name of the mesh to create
  34024. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34025. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34026. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34027. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34028. * @param p the number of windings on X axis (positive integers, default 2)
  34029. * @param q the number of windings on Y axis (positive integers, default 3)
  34030. * @param scene defines the hosting scene
  34031. * @param updatable defines if the mesh must be flagged as updatable
  34032. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34033. * @returns a new Mesh
  34034. */
  34035. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34036. var options = {
  34037. radius: radius,
  34038. tube: tube,
  34039. radialSegments: radialSegments,
  34040. tubularSegments: tubularSegments,
  34041. p: p,
  34042. q: q,
  34043. sideOrientation: sideOrientation,
  34044. updatable: updatable
  34045. };
  34046. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34047. };
  34048. /**
  34049. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34050. * @param name defines the name of the mesh to create
  34051. * @param points is an array successive Vector3
  34052. * @param scene defines the hosting scene
  34053. * @param updatable defines if the mesh must be flagged as updatable
  34054. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34055. * @returns a new Mesh
  34056. */
  34057. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34058. if (scene === void 0) { scene = null; }
  34059. if (updatable === void 0) { updatable = false; }
  34060. if (instance === void 0) { instance = null; }
  34061. var options = {
  34062. points: points,
  34063. updatable: updatable,
  34064. instance: instance
  34065. };
  34066. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34067. };
  34068. /**
  34069. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34070. * @param name defines the name of the mesh to create
  34071. * @param points is an array successive Vector3
  34072. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34073. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34074. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34075. * @param scene defines the hosting scene
  34076. * @param updatable defines if the mesh must be flagged as updatable
  34077. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34078. * @returns a new Mesh
  34079. */
  34080. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34081. if (scene === void 0) { scene = null; }
  34082. var options = {
  34083. points: points,
  34084. dashSize: dashSize,
  34085. gapSize: gapSize,
  34086. dashNb: dashNb,
  34087. updatable: updatable,
  34088. instance: instance
  34089. };
  34090. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34091. };
  34092. /**
  34093. * Creates a polygon mesh.
  34094. * Please consider using the same method from the MeshBuilder class instead.
  34095. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34096. * 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.
  34097. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34099. * Remember you can only change the shape positions, not their number when updating a polygon.
  34100. */
  34101. /**
  34102. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34103. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34104. * @param name defines the name of the mesh to create
  34105. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34106. * @param scene defines the hosting scene
  34107. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34108. * @param updatable defines if the mesh must be flagged as updatable
  34109. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34110. * @returns a new Mesh
  34111. */
  34112. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34113. var options = {
  34114. shape: shape,
  34115. holes: holes,
  34116. updatable: updatable,
  34117. sideOrientation: sideOrientation
  34118. };
  34119. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34120. };
  34121. /**
  34122. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34123. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34124. * @param name defines the name of the mesh to create
  34125. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34126. * @param depth defines the height of extrusion
  34127. * @param scene defines the hosting scene
  34128. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34129. * @param updatable defines if the mesh must be flagged as updatable
  34130. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34131. * @returns a new Mesh
  34132. */
  34133. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34134. var options = {
  34135. shape: shape,
  34136. holes: holes,
  34137. depth: depth,
  34138. updatable: updatable,
  34139. sideOrientation: sideOrientation
  34140. };
  34141. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34142. };
  34143. /**
  34144. * Creates an extruded shape mesh.
  34145. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34146. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34147. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34148. * @param name defines the name of the mesh to create
  34149. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34150. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34151. * @param scale is the value to scale the shape
  34152. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  34153. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34154. * @param scene defines the hosting scene
  34155. * @param updatable defines if the mesh must be flagged as updatable
  34156. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34157. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34158. * @returns a new Mesh
  34159. */
  34160. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34161. if (scene === void 0) { scene = null; }
  34162. var options = {
  34163. shape: shape,
  34164. path: path,
  34165. scale: scale,
  34166. rotation: rotation,
  34167. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34168. sideOrientation: sideOrientation,
  34169. instance: instance,
  34170. updatable: updatable
  34171. };
  34172. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34173. };
  34174. /**
  34175. * Creates an custom extruded shape mesh.
  34176. * The custom extrusion is a parametric shape.
  34177. * It has no predefined shape. Its final shape will depend on the input parameters.
  34178. * Please consider using the same method from the MeshBuilder class instead
  34179. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34180. * @param name defines the name of the mesh to create
  34181. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34182. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34183. * @param scaleFunction is a custom Javascript function called on each path point
  34184. * @param rotationFunction is a custom Javascript function called on each path point
  34185. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34186. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34187. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34188. * @param scene defines the hosting scene
  34189. * @param updatable defines if the mesh must be flagged as updatable
  34190. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34191. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34192. * @returns a new Mesh
  34193. */
  34194. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34195. var options = {
  34196. shape: shape,
  34197. path: path,
  34198. scaleFunction: scaleFunction,
  34199. rotationFunction: rotationFunction,
  34200. ribbonCloseArray: ribbonCloseArray,
  34201. ribbonClosePath: ribbonClosePath,
  34202. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34203. sideOrientation: sideOrientation,
  34204. instance: instance,
  34205. updatable: updatable
  34206. };
  34207. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34208. };
  34209. /**
  34210. * Creates lathe mesh.
  34211. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34212. * Please consider using the same method from the MeshBuilder class instead
  34213. * @param name defines the name of the mesh to create
  34214. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  34215. * @param radius is the radius value of the lathe
  34216. * @param tessellation is the side number of the lathe.
  34217. * @param scene defines the hosting scene
  34218. * @param updatable defines if the mesh must be flagged as updatable
  34219. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34220. * @returns a new Mesh
  34221. */
  34222. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34223. var options = {
  34224. shape: shape,
  34225. radius: radius,
  34226. tessellation: tessellation,
  34227. sideOrientation: sideOrientation,
  34228. updatable: updatable
  34229. };
  34230. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34231. };
  34232. /**
  34233. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34234. * @param name defines the name of the mesh to create
  34235. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34236. * @param scene defines the hosting scene
  34237. * @param updatable defines if the mesh must be flagged as updatable
  34238. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34239. * @returns a new Mesh
  34240. */
  34241. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34242. var options = {
  34243. size: size,
  34244. width: size,
  34245. height: size,
  34246. sideOrientation: sideOrientation,
  34247. updatable: updatable
  34248. };
  34249. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34250. };
  34251. /**
  34252. * Creates a ground mesh.
  34253. * Please consider using the same method from the MeshBuilder class instead
  34254. * @param name defines the name of the mesh to create
  34255. * @param width set the width of the ground
  34256. * @param height set the height of the ground
  34257. * @param subdivisions sets the number of subdivisions per side
  34258. * @param scene defines the hosting scene
  34259. * @param updatable defines if the mesh must be flagged as updatable
  34260. * @returns a new Mesh
  34261. */
  34262. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34263. var options = {
  34264. width: width,
  34265. height: height,
  34266. subdivisions: subdivisions,
  34267. updatable: updatable
  34268. };
  34269. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34270. };
  34271. /**
  34272. * Creates a tiled ground mesh.
  34273. * Please consider using the same method from the MeshBuilder class instead
  34274. * @param name defines the name of the mesh to create
  34275. * @param xmin set the ground minimum X coordinate
  34276. * @param zmin set the ground minimum Y coordinate
  34277. * @param xmax set the ground maximum X coordinate
  34278. * @param zmax set the ground maximum Z coordinate
  34279. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  34280. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  34281. * @param scene defines the hosting scene
  34282. * @param updatable defines if the mesh must be flagged as updatable
  34283. * @returns a new Mesh
  34284. */
  34285. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34286. var options = {
  34287. xmin: xmin,
  34288. zmin: zmin,
  34289. xmax: xmax,
  34290. zmax: zmax,
  34291. subdivisions: subdivisions,
  34292. precision: precision,
  34293. updatable: updatable
  34294. };
  34295. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34296. };
  34297. /**
  34298. * Creates a ground mesh from a height map.
  34299. * Please consider using the same method from the MeshBuilder class instead
  34300. * @see http://doc.babylonjs.com/babylon101/height_map
  34301. * @param name defines the name of the mesh to create
  34302. * @param url sets the URL of the height map image resource
  34303. * @param width set the ground width size
  34304. * @param height set the ground height size
  34305. * @param subdivisions sets the number of subdivision per side
  34306. * @param minHeight is the minimum altitude on the ground
  34307. * @param maxHeight is the maximum altitude on the ground
  34308. * @param scene defines the hosting scene
  34309. * @param updatable defines if the mesh must be flagged as updatable
  34310. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34311. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34312. * @returns a new Mesh
  34313. */
  34314. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34315. var options = {
  34316. width: width,
  34317. height: height,
  34318. subdivisions: subdivisions,
  34319. minHeight: minHeight,
  34320. maxHeight: maxHeight,
  34321. updatable: updatable,
  34322. onReady: onReady,
  34323. alphaFilter: alphaFilter
  34324. };
  34325. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34326. };
  34327. /**
  34328. * Creates a tube mesh.
  34329. * The tube is a parametric shape.
  34330. * It has no predefined shape. Its final shape will depend on the input parameters.
  34331. * Please consider using the same method from the MeshBuilder class instead
  34332. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34333. * @param name defines the name of the mesh to create
  34334. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34335. * @param radius sets the tube radius size
  34336. * @param tessellation is the number of sides on the tubular surface
  34337. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  34338. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34339. * @param scene defines the hosting scene
  34340. * @param updatable defines if the mesh must be flagged as updatable
  34341. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34342. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  34343. * @returns a new Mesh
  34344. */
  34345. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34346. var options = {
  34347. path: path,
  34348. radius: radius,
  34349. tessellation: tessellation,
  34350. radiusFunction: radiusFunction,
  34351. arc: 1,
  34352. cap: cap,
  34353. updatable: updatable,
  34354. sideOrientation: sideOrientation,
  34355. instance: instance
  34356. };
  34357. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34358. };
  34359. /**
  34360. * Creates a polyhedron mesh.
  34361. * Please consider using the same method from the MeshBuilder class instead.
  34362. * * 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
  34363. * * The parameter `size` (positive float, default 1) sets the polygon size
  34364. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34365. * * 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`
  34366. * * 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
  34367. * * 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)`)
  34368. * * 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
  34369. * * 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
  34370. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34371. * * 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
  34372. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34373. * @param name defines the name of the mesh to create
  34374. * @param options defines the options used to create the mesh
  34375. * @param scene defines the hosting scene
  34376. * @returns a new Mesh
  34377. */
  34378. Mesh.CreatePolyhedron = function (name, options, scene) {
  34379. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34380. };
  34381. /**
  34382. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34383. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34384. * * 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`)
  34385. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34386. * * 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
  34387. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34388. * * 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
  34389. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34390. * @param name defines the name of the mesh
  34391. * @param options defines the options used to create the mesh
  34392. * @param scene defines the hosting scene
  34393. * @returns a new Mesh
  34394. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34395. */
  34396. Mesh.CreateIcoSphere = function (name, options, scene) {
  34397. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34398. };
  34399. /**
  34400. * Creates a decal mesh.
  34401. * Please consider using the same method from the MeshBuilder class instead.
  34402. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34403. * @param name defines the name of the mesh
  34404. * @param sourceMesh defines the mesh receiving the decal
  34405. * @param position sets the position of the decal in world coordinates
  34406. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34407. * @param size sets the decal scaling
  34408. * @param angle sets the angle to rotate the decal
  34409. * @returns a new Mesh
  34410. */
  34411. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34412. var options = {
  34413. position: position,
  34414. normal: normal,
  34415. size: size,
  34416. angle: angle
  34417. };
  34418. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34419. };
  34420. // Skeletons
  34421. /**
  34422. * Prepare internal position array for software CPU skinning
  34423. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34424. */
  34425. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34426. if (!this._sourcePositions) {
  34427. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34428. if (!source) {
  34429. return this._sourcePositions;
  34430. }
  34431. this._sourcePositions = new Float32Array(source);
  34432. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34433. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34434. }
  34435. }
  34436. return this._sourcePositions;
  34437. };
  34438. /**
  34439. * Prepare internal normal array for software CPU skinning
  34440. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34441. */
  34442. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34443. if (!this._sourceNormals) {
  34444. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34445. if (!source) {
  34446. return this._sourceNormals;
  34447. }
  34448. this._sourceNormals = new Float32Array(source);
  34449. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34450. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34451. }
  34452. }
  34453. return this._sourceNormals;
  34454. };
  34455. /**
  34456. * Updates the vertex buffer by applying transformation from the bones
  34457. * @param skeleton defines the skeleton to apply to current mesh
  34458. * @returns the current mesh
  34459. */
  34460. Mesh.prototype.applySkeleton = function (skeleton) {
  34461. if (!this.geometry) {
  34462. return this;
  34463. }
  34464. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34465. return this;
  34466. }
  34467. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34468. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34469. return this;
  34470. }
  34471. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34472. return this;
  34473. }
  34474. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34475. return this;
  34476. }
  34477. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34478. return this;
  34479. }
  34480. if (!this._sourcePositions) {
  34481. var submeshes = this.subMeshes.slice();
  34482. this.setPositionsForCPUSkinning();
  34483. this.subMeshes = submeshes;
  34484. }
  34485. if (!this._sourceNormals) {
  34486. this.setNormalsForCPUSkinning();
  34487. }
  34488. // positionsData checks for not being Float32Array will only pass at most once
  34489. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34490. if (!positionsData) {
  34491. return this;
  34492. }
  34493. if (!(positionsData instanceof Float32Array)) {
  34494. positionsData = new Float32Array(positionsData);
  34495. }
  34496. // normalsData checks for not being Float32Array will only pass at most once
  34497. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34498. if (!normalsData) {
  34499. return this;
  34500. }
  34501. if (!(normalsData instanceof Float32Array)) {
  34502. normalsData = new Float32Array(normalsData);
  34503. }
  34504. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34505. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34506. if (!matricesWeightsData || !matricesIndicesData) {
  34507. return this;
  34508. }
  34509. var needExtras = this.numBoneInfluencers > 4;
  34510. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34511. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34512. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34513. var tempVector3 = BABYLON.Vector3.Zero();
  34514. var finalMatrix = new BABYLON.Matrix();
  34515. var tempMatrix = new BABYLON.Matrix();
  34516. var matWeightIdx = 0;
  34517. var inf;
  34518. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34519. var weight;
  34520. for (inf = 0; inf < 4; inf++) {
  34521. weight = matricesWeightsData[matWeightIdx + inf];
  34522. if (weight > 0) {
  34523. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34524. finalMatrix.addToSelf(tempMatrix);
  34525. }
  34526. }
  34527. if (needExtras) {
  34528. for (inf = 0; inf < 4; inf++) {
  34529. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34530. if (weight > 0) {
  34531. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34532. finalMatrix.addToSelf(tempMatrix);
  34533. }
  34534. }
  34535. }
  34536. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34537. tempVector3.toArray(positionsData, index);
  34538. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34539. tempVector3.toArray(normalsData, index);
  34540. finalMatrix.reset();
  34541. }
  34542. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34543. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34544. return this;
  34545. };
  34546. // Tools
  34547. /**
  34548. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  34549. * @param meshes defines the list of meshes to scan
  34550. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34551. */
  34552. Mesh.MinMax = function (meshes) {
  34553. var minVector = null;
  34554. var maxVector = null;
  34555. meshes.forEach(function (mesh, index, array) {
  34556. var boundingInfo = mesh.getBoundingInfo();
  34557. var boundingBox = boundingInfo.boundingBox;
  34558. if (!minVector || !maxVector) {
  34559. minVector = boundingBox.minimumWorld;
  34560. maxVector = boundingBox.maximumWorld;
  34561. }
  34562. else {
  34563. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34564. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34565. }
  34566. });
  34567. if (!minVector || !maxVector) {
  34568. return {
  34569. min: BABYLON.Vector3.Zero(),
  34570. max: BABYLON.Vector3.Zero()
  34571. };
  34572. }
  34573. return {
  34574. min: minVector,
  34575. max: maxVector
  34576. };
  34577. };
  34578. /**
  34579. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34580. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34581. * @returns a vector3
  34582. */
  34583. Mesh.Center = function (meshesOrMinMaxVector) {
  34584. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34585. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34586. };
  34587. /**
  34588. * Merge the array of meshes into a single mesh for performance reasons.
  34589. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34590. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34591. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34592. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34593. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34594. * @returns a new mesh
  34595. */
  34596. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34597. if (disposeSource === void 0) { disposeSource = true; }
  34598. var index;
  34599. if (!allow32BitsIndices) {
  34600. var totalVertices = 0;
  34601. // Counting vertices
  34602. for (index = 0; index < meshes.length; index++) {
  34603. if (meshes[index]) {
  34604. totalVertices += meshes[index].getTotalVertices();
  34605. if (totalVertices > 65536) {
  34606. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34607. return null;
  34608. }
  34609. }
  34610. }
  34611. }
  34612. // Merge
  34613. var vertexData = null;
  34614. var otherVertexData;
  34615. var indiceArray = new Array();
  34616. var source = null;
  34617. for (index = 0; index < meshes.length; index++) {
  34618. if (meshes[index]) {
  34619. var wm = meshes[index].computeWorldMatrix(true);
  34620. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34621. otherVertexData.transform(wm);
  34622. if (vertexData) {
  34623. vertexData.merge(otherVertexData, allow32BitsIndices);
  34624. }
  34625. else {
  34626. vertexData = otherVertexData;
  34627. source = meshes[index];
  34628. }
  34629. if (subdivideWithSubMeshes) {
  34630. indiceArray.push(meshes[index].getTotalIndices());
  34631. }
  34632. }
  34633. }
  34634. source = source;
  34635. if (!meshSubclass) {
  34636. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34637. }
  34638. vertexData.applyToMesh(meshSubclass);
  34639. // Setting properties
  34640. meshSubclass.material = source.material;
  34641. meshSubclass.checkCollisions = source.checkCollisions;
  34642. // Cleaning
  34643. if (disposeSource) {
  34644. for (index = 0; index < meshes.length; index++) {
  34645. if (meshes[index]) {
  34646. meshes[index].dispose();
  34647. }
  34648. }
  34649. }
  34650. // Subdivide
  34651. if (subdivideWithSubMeshes) {
  34652. //-- removal of global submesh
  34653. meshSubclass.releaseSubMeshes();
  34654. index = 0;
  34655. var offset = 0;
  34656. //-- apply subdivision according to index table
  34657. while (index < indiceArray.length) {
  34658. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34659. offset += indiceArray[index];
  34660. index++;
  34661. }
  34662. }
  34663. return meshSubclass;
  34664. };
  34665. // Consts
  34666. /**
  34667. * Mesh side orientation : usually the external or front surface
  34668. */
  34669. Mesh.FRONTSIDE = 0;
  34670. /**
  34671. * Mesh side orientation : usually the internal or back surface
  34672. */
  34673. Mesh.BACKSIDE = 1;
  34674. /**
  34675. * Mesh side orientation : both internal and external or front and back surfaces
  34676. */
  34677. Mesh.DOUBLESIDE = 2;
  34678. /**
  34679. * Mesh side orientation : by default, `FRONTSIDE`
  34680. */
  34681. Mesh.DEFAULTSIDE = 0;
  34682. /**
  34683. * Mesh cap setting : no cap
  34684. */
  34685. Mesh.NO_CAP = 0;
  34686. /**
  34687. * Mesh cap setting : one cap at the beginning of the mesh
  34688. */
  34689. Mesh.CAP_START = 1;
  34690. /**
  34691. * Mesh cap setting : one cap at the end of the mesh
  34692. */
  34693. Mesh.CAP_END = 2;
  34694. /**
  34695. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34696. */
  34697. Mesh.CAP_ALL = 3;
  34698. return Mesh;
  34699. }(BABYLON.AbstractMesh));
  34700. BABYLON.Mesh = Mesh;
  34701. })(BABYLON || (BABYLON = {}));
  34702. //# sourceMappingURL=babylon.mesh.js.map
  34703. var BABYLON;
  34704. (function (BABYLON) {
  34705. /**
  34706. * Base class for submeshes
  34707. */
  34708. var BaseSubMesh = /** @class */ (function () {
  34709. function BaseSubMesh() {
  34710. }
  34711. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34712. /**
  34713. * Gets associated effect
  34714. */
  34715. get: function () {
  34716. return this._materialEffect;
  34717. },
  34718. enumerable: true,
  34719. configurable: true
  34720. });
  34721. /**
  34722. * Sets associated effect (effect used to render this submesh)
  34723. * @param effect defines the effect to associate with
  34724. * @param defines defines the set of defines used to compile this effect
  34725. */
  34726. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34727. if (defines === void 0) { defines = null; }
  34728. if (this._materialEffect === effect) {
  34729. if (!effect) {
  34730. this._materialDefines = null;
  34731. }
  34732. return;
  34733. }
  34734. this._materialDefines = defines;
  34735. this._materialEffect = effect;
  34736. };
  34737. return BaseSubMesh;
  34738. }());
  34739. BABYLON.BaseSubMesh = BaseSubMesh;
  34740. /**
  34741. * Defines a subdivision inside a mesh
  34742. */
  34743. var SubMesh = /** @class */ (function (_super) {
  34744. __extends(SubMesh, _super);
  34745. /**
  34746. * Creates a new submesh
  34747. * @param materialIndex defines the material index to use
  34748. * @param verticesStart defines vertex index start
  34749. * @param verticesCount defines vertices count
  34750. * @param indexStart defines index start
  34751. * @param indexCount defines indices count
  34752. * @param mesh defines the parent mesh
  34753. * @param renderingMesh defines an optional rendering mesh
  34754. * @param createBoundingBox defines if bounding box should be created for this submesh
  34755. */
  34756. function SubMesh(
  34757. /** the material index to use */
  34758. materialIndex,
  34759. /** vertex index start */
  34760. verticesStart,
  34761. /** vertices count */
  34762. verticesCount,
  34763. /** index start */
  34764. indexStart,
  34765. /** indices count */
  34766. indexCount, mesh, renderingMesh, createBoundingBox) {
  34767. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34768. var _this = _super.call(this) || this;
  34769. _this.materialIndex = materialIndex;
  34770. _this.verticesStart = verticesStart;
  34771. _this.verticesCount = verticesCount;
  34772. _this.indexStart = indexStart;
  34773. _this.indexCount = indexCount;
  34774. /** @hidden */
  34775. _this._renderId = 0;
  34776. _this._mesh = mesh;
  34777. _this._renderingMesh = renderingMesh || mesh;
  34778. mesh.subMeshes.push(_this);
  34779. _this._trianglePlanes = [];
  34780. _this._id = mesh.subMeshes.length - 1;
  34781. if (createBoundingBox) {
  34782. _this.refreshBoundingInfo();
  34783. mesh.computeWorldMatrix(true);
  34784. }
  34785. return _this;
  34786. }
  34787. /**
  34788. * Add a new submesh to a mesh
  34789. * @param materialIndex defines the material index to use
  34790. * @param verticesStart defines vertex index start
  34791. * @param verticesCount defines vertices count
  34792. * @param indexStart defines index start
  34793. * @param indexCount defines indices count
  34794. * @param mesh defines the parent mesh
  34795. * @param renderingMesh defines an optional rendering mesh
  34796. * @param createBoundingBox defines if bounding box should be created for this submesh
  34797. * @returns the new submesh
  34798. */
  34799. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34800. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34801. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34802. };
  34803. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34804. /**
  34805. * Returns true if this submesh covers the entire parent mesh
  34806. * @ignorenaming
  34807. */
  34808. get: function () {
  34809. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34810. },
  34811. enumerable: true,
  34812. configurable: true
  34813. });
  34814. /**
  34815. * Returns the submesh BoudingInfo object
  34816. * @returns current bounding info (or mesh's one if the submesh is global)
  34817. */
  34818. SubMesh.prototype.getBoundingInfo = function () {
  34819. if (this.IsGlobal) {
  34820. return this._mesh.getBoundingInfo();
  34821. }
  34822. return this._boundingInfo;
  34823. };
  34824. /**
  34825. * Sets the submesh BoundingInfo
  34826. * @param boundingInfo defines the new bounding info to use
  34827. * @returns the SubMesh
  34828. */
  34829. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34830. this._boundingInfo = boundingInfo;
  34831. return this;
  34832. };
  34833. /**
  34834. * Returns the mesh of the current submesh
  34835. * @return the parent mesh
  34836. */
  34837. SubMesh.prototype.getMesh = function () {
  34838. return this._mesh;
  34839. };
  34840. /**
  34841. * Returns the rendering mesh of the submesh
  34842. * @returns the rendering mesh (could be different from parent mesh)
  34843. */
  34844. SubMesh.prototype.getRenderingMesh = function () {
  34845. return this._renderingMesh;
  34846. };
  34847. /**
  34848. * Returns the submesh material
  34849. * @returns null or the current material
  34850. */
  34851. SubMesh.prototype.getMaterial = function () {
  34852. var rootMaterial = this._renderingMesh.material;
  34853. if (rootMaterial === null || rootMaterial === undefined) {
  34854. return this._mesh.getScene().defaultMaterial;
  34855. }
  34856. else if (rootMaterial.getSubMaterial) {
  34857. var multiMaterial = rootMaterial;
  34858. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34859. if (this._currentMaterial !== effectiveMaterial) {
  34860. this._currentMaterial = effectiveMaterial;
  34861. this._materialDefines = null;
  34862. }
  34863. return effectiveMaterial;
  34864. }
  34865. return rootMaterial;
  34866. };
  34867. // Methods
  34868. /**
  34869. * Sets a new updated BoundingInfo object to the submesh
  34870. * @returns the SubMesh
  34871. */
  34872. SubMesh.prototype.refreshBoundingInfo = function () {
  34873. this._lastColliderWorldVertices = null;
  34874. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34875. return this;
  34876. }
  34877. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34878. if (!data) {
  34879. this._boundingInfo = this._mesh.getBoundingInfo();
  34880. return this;
  34881. }
  34882. var indices = this._renderingMesh.getIndices();
  34883. var extend;
  34884. //is this the only submesh?
  34885. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34886. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34887. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34888. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34889. }
  34890. else {
  34891. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34892. }
  34893. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34894. return this;
  34895. };
  34896. /** @hidden */
  34897. SubMesh.prototype._checkCollision = function (collider) {
  34898. var boundingInfo = this.getBoundingInfo();
  34899. return boundingInfo._checkCollision(collider);
  34900. };
  34901. /**
  34902. * Updates the submesh BoundingInfo
  34903. * @param world defines the world matrix to use to update the bounding info
  34904. * @returns the submesh
  34905. */
  34906. SubMesh.prototype.updateBoundingInfo = function (world) {
  34907. var boundingInfo = this.getBoundingInfo();
  34908. if (!boundingInfo) {
  34909. this.refreshBoundingInfo();
  34910. boundingInfo = this.getBoundingInfo();
  34911. }
  34912. boundingInfo.update(world);
  34913. return this;
  34914. };
  34915. /**
  34916. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34917. * @param frustumPlanes defines the frustum planes
  34918. * @returns true if the submesh is intersecting with the frustum
  34919. */
  34920. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34921. var boundingInfo = this.getBoundingInfo();
  34922. if (!boundingInfo) {
  34923. return false;
  34924. }
  34925. return boundingInfo.isInFrustum(frustumPlanes);
  34926. };
  34927. /**
  34928. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  34929. * @param frustumPlanes defines the frustum planes
  34930. * @returns true if the submesh is inside the frustum
  34931. */
  34932. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34933. var boundingInfo = this.getBoundingInfo();
  34934. if (!boundingInfo) {
  34935. return false;
  34936. }
  34937. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34938. };
  34939. /**
  34940. * Renders the submesh
  34941. * @param enableAlphaMode defines if alpha needs to be used
  34942. * @returns the submesh
  34943. */
  34944. SubMesh.prototype.render = function (enableAlphaMode) {
  34945. this._renderingMesh.render(this, enableAlphaMode);
  34946. return this;
  34947. };
  34948. /**
  34949. * @hidden
  34950. */
  34951. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  34952. if (!this._linesIndexBuffer) {
  34953. var linesIndices = [];
  34954. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34955. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34956. }
  34957. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34958. this._linesIndexCount = linesIndices.length;
  34959. }
  34960. return this._linesIndexBuffer;
  34961. };
  34962. /**
  34963. * Checks if the submesh intersects with a ray
  34964. * @param ray defines the ray to test
  34965. * @returns true is the passed ray intersects the submesh bounding box
  34966. */
  34967. SubMesh.prototype.canIntersects = function (ray) {
  34968. var boundingInfo = this.getBoundingInfo();
  34969. if (!boundingInfo) {
  34970. return false;
  34971. }
  34972. return ray.intersectsBox(boundingInfo.boundingBox);
  34973. };
  34974. /**
  34975. * Intersects current submesh with a ray
  34976. * @param ray defines the ray to test
  34977. * @param positions defines mesh's positions array
  34978. * @param indices defines mesh's indices array
  34979. * @param fastCheck defines if only bounding info should be used
  34980. * @returns intersection info or null if no intersection
  34981. */
  34982. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34983. var intersectInfo = null;
  34984. var material = this.getMaterial();
  34985. if (!material) {
  34986. return null;
  34987. }
  34988. switch (material.fillMode) {
  34989. case BABYLON.Material.PointListDrawMode:
  34990. case BABYLON.Material.LineListDrawMode:
  34991. case BABYLON.Material.LineLoopDrawMode:
  34992. case BABYLON.Material.LineStripDrawMode:
  34993. case BABYLON.Material.TriangleFanDrawMode:
  34994. case BABYLON.Material.TriangleStripDrawMode:
  34995. return null;
  34996. }
  34997. // LineMesh first as it's also a Mesh...
  34998. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34999. var lineMesh = this._mesh;
  35000. // Line test
  35001. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35002. var p0 = positions[indices[index]];
  35003. var p1 = positions[indices[index + 1]];
  35004. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35005. if (length < 0) {
  35006. continue;
  35007. }
  35008. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35009. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35010. if (fastCheck) {
  35011. break;
  35012. }
  35013. }
  35014. }
  35015. }
  35016. else {
  35017. // Triangles test
  35018. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35019. var p0 = positions[indices[index]];
  35020. var p1 = positions[indices[index + 1]];
  35021. var p2 = positions[indices[index + 2]];
  35022. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35023. if (currentIntersectInfo) {
  35024. if (currentIntersectInfo.distance < 0) {
  35025. continue;
  35026. }
  35027. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35028. intersectInfo = currentIntersectInfo;
  35029. intersectInfo.faceId = index / 3;
  35030. if (fastCheck) {
  35031. break;
  35032. }
  35033. }
  35034. }
  35035. }
  35036. }
  35037. return intersectInfo;
  35038. };
  35039. /** @hidden */
  35040. SubMesh.prototype._rebuild = function () {
  35041. if (this._linesIndexBuffer) {
  35042. this._linesIndexBuffer = null;
  35043. }
  35044. };
  35045. // Clone
  35046. /**
  35047. * Creates a new submesh from the passed mesh
  35048. * @param newMesh defines the new hosting mesh
  35049. * @param newRenderingMesh defines an optional rendering mesh
  35050. * @returns the new submesh
  35051. */
  35052. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35053. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35054. if (!this.IsGlobal) {
  35055. var boundingInfo = this.getBoundingInfo();
  35056. if (!boundingInfo) {
  35057. return result;
  35058. }
  35059. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35060. }
  35061. return result;
  35062. };
  35063. // Dispose
  35064. /**
  35065. * Release associated resources
  35066. */
  35067. SubMesh.prototype.dispose = function () {
  35068. if (this._linesIndexBuffer) {
  35069. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35070. this._linesIndexBuffer = null;
  35071. }
  35072. // Remove from mesh
  35073. var index = this._mesh.subMeshes.indexOf(this);
  35074. this._mesh.subMeshes.splice(index, 1);
  35075. };
  35076. // Statics
  35077. /**
  35078. * Creates a new submesh from indices data
  35079. * @param materialIndex the index of the main mesh material
  35080. * @param startIndex the index where to start the copy in the mesh indices array
  35081. * @param indexCount the number of indices to copy then from the startIndex
  35082. * @param mesh the main mesh to create the submesh from
  35083. * @param renderingMesh the optional rendering mesh
  35084. * @returns a new submesh
  35085. */
  35086. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35087. var minVertexIndex = Number.MAX_VALUE;
  35088. var maxVertexIndex = -Number.MAX_VALUE;
  35089. renderingMesh = (renderingMesh || mesh);
  35090. var indices = renderingMesh.getIndices();
  35091. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35092. var vertexIndex = indices[index];
  35093. if (vertexIndex < minVertexIndex)
  35094. minVertexIndex = vertexIndex;
  35095. if (vertexIndex > maxVertexIndex)
  35096. maxVertexIndex = vertexIndex;
  35097. }
  35098. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35099. };
  35100. return SubMesh;
  35101. }(BaseSubMesh));
  35102. BABYLON.SubMesh = SubMesh;
  35103. })(BABYLON || (BABYLON = {}));
  35104. //# sourceMappingURL=babylon.subMesh.js.map
  35105. var __assign = (this && this.__assign) || function () {
  35106. __assign = Object.assign || function(t) {
  35107. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35108. s = arguments[i];
  35109. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35110. t[p] = s[p];
  35111. }
  35112. return t;
  35113. };
  35114. return __assign.apply(this, arguments);
  35115. };
  35116. var BABYLON;
  35117. (function (BABYLON) {
  35118. /**
  35119. * Manages the defines for the Material
  35120. */
  35121. var MaterialDefines = /** @class */ (function () {
  35122. function MaterialDefines() {
  35123. this._isDirty = true;
  35124. /** @hidden */
  35125. this._areLightsDirty = true;
  35126. /** @hidden */
  35127. this._areAttributesDirty = true;
  35128. /** @hidden */
  35129. this._areTexturesDirty = true;
  35130. /** @hidden */
  35131. this._areFresnelDirty = true;
  35132. /** @hidden */
  35133. this._areMiscDirty = true;
  35134. /** @hidden */
  35135. this._areImageProcessingDirty = true;
  35136. /** @hidden */
  35137. this._normals = false;
  35138. /** @hidden */
  35139. this._uvs = false;
  35140. /** @hidden */
  35141. this._needNormals = false;
  35142. /** @hidden */
  35143. this._needUVs = false;
  35144. }
  35145. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35146. /**
  35147. * Specifies if the material needs to be re-calculated
  35148. */
  35149. get: function () {
  35150. return this._isDirty;
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. /**
  35156. * Marks the material to indicate that it has been re-calculated
  35157. */
  35158. MaterialDefines.prototype.markAsProcessed = function () {
  35159. this._isDirty = false;
  35160. this._areAttributesDirty = false;
  35161. this._areTexturesDirty = false;
  35162. this._areFresnelDirty = false;
  35163. this._areLightsDirty = false;
  35164. this._areMiscDirty = false;
  35165. this._areImageProcessingDirty = false;
  35166. };
  35167. /**
  35168. * Marks the material to indicate that it needs to be re-calculated
  35169. */
  35170. MaterialDefines.prototype.markAsUnprocessed = function () {
  35171. this._isDirty = true;
  35172. };
  35173. /**
  35174. * Marks the material to indicate all of its defines need to be re-calculated
  35175. */
  35176. MaterialDefines.prototype.markAllAsDirty = function () {
  35177. this._areTexturesDirty = true;
  35178. this._areAttributesDirty = true;
  35179. this._areLightsDirty = true;
  35180. this._areFresnelDirty = true;
  35181. this._areMiscDirty = true;
  35182. this._areImageProcessingDirty = true;
  35183. this._isDirty = true;
  35184. };
  35185. /**
  35186. * Marks the material to indicate that image processing needs to be re-calculated
  35187. */
  35188. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35189. this._areImageProcessingDirty = true;
  35190. this._isDirty = true;
  35191. };
  35192. /**
  35193. * Marks the material to indicate the lights need to be re-calculated
  35194. */
  35195. MaterialDefines.prototype.markAsLightDirty = function () {
  35196. this._areLightsDirty = true;
  35197. this._isDirty = true;
  35198. };
  35199. /**
  35200. * Marks the attribute state as changed
  35201. */
  35202. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35203. this._areAttributesDirty = true;
  35204. this._isDirty = true;
  35205. };
  35206. /**
  35207. * Marks the texture state as changed
  35208. */
  35209. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35210. this._areTexturesDirty = true;
  35211. this._isDirty = true;
  35212. };
  35213. /**
  35214. * Marks the fresnel state as changed
  35215. */
  35216. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35217. this._areFresnelDirty = true;
  35218. this._isDirty = true;
  35219. };
  35220. /**
  35221. * Marks the misc state as changed
  35222. */
  35223. MaterialDefines.prototype.markAsMiscDirty = function () {
  35224. this._areMiscDirty = true;
  35225. this._isDirty = true;
  35226. };
  35227. /**
  35228. * Rebuilds the material defines
  35229. */
  35230. MaterialDefines.prototype.rebuild = function () {
  35231. if (this._keys) {
  35232. delete this._keys;
  35233. }
  35234. this._keys = [];
  35235. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35236. var key = _a[_i];
  35237. if (key[0] === "_") {
  35238. continue;
  35239. }
  35240. this._keys.push(key);
  35241. }
  35242. };
  35243. /**
  35244. * Specifies if two material defines are equal
  35245. * @param other - A material define instance to compare to
  35246. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35247. */
  35248. MaterialDefines.prototype.isEqual = function (other) {
  35249. if (this._keys.length !== other._keys.length) {
  35250. return false;
  35251. }
  35252. for (var index = 0; index < this._keys.length; index++) {
  35253. var prop = this._keys[index];
  35254. if (this[prop] !== other[prop]) {
  35255. return false;
  35256. }
  35257. }
  35258. return true;
  35259. };
  35260. /**
  35261. * Clones this instance's defines to another instance
  35262. * @param other - material defines to clone values to
  35263. */
  35264. MaterialDefines.prototype.cloneTo = function (other) {
  35265. if (this._keys.length !== other._keys.length) {
  35266. other._keys = this._keys.slice(0);
  35267. }
  35268. for (var index = 0; index < this._keys.length; index++) {
  35269. var prop = this._keys[index];
  35270. other[prop] = this[prop];
  35271. }
  35272. };
  35273. /**
  35274. * Resets the material define values
  35275. */
  35276. MaterialDefines.prototype.reset = function () {
  35277. for (var index = 0; index < this._keys.length; index++) {
  35278. var prop = this._keys[index];
  35279. var type = typeof this[prop];
  35280. switch (type) {
  35281. case "number":
  35282. this[prop] = 0;
  35283. break;
  35284. case "string":
  35285. this[prop] = "";
  35286. break;
  35287. default:
  35288. this[prop] = false;
  35289. break;
  35290. }
  35291. }
  35292. };
  35293. /**
  35294. * Converts the material define values to a string
  35295. * @returns - String of material define information
  35296. */
  35297. MaterialDefines.prototype.toString = function () {
  35298. var result = "";
  35299. for (var index = 0; index < this._keys.length; index++) {
  35300. var prop = this._keys[index];
  35301. var value = this[prop];
  35302. var type = typeof value;
  35303. switch (type) {
  35304. case "number":
  35305. case "string":
  35306. result += "#define " + prop + " " + value + "\n";
  35307. break;
  35308. default:
  35309. if (value) {
  35310. result += "#define " + prop + "\n";
  35311. }
  35312. break;
  35313. }
  35314. }
  35315. return result;
  35316. };
  35317. return MaterialDefines;
  35318. }());
  35319. BABYLON.MaterialDefines = MaterialDefines;
  35320. /**
  35321. * Base class for the main features of a material in Babylon.js
  35322. */
  35323. var Material = /** @class */ (function () {
  35324. /**
  35325. * Creates a material instance
  35326. * @param name defines the name of the material
  35327. * @param scene defines the scene to reference
  35328. * @param doNotAdd specifies if the material should be added to the scene
  35329. */
  35330. function Material(name, scene, doNotAdd) {
  35331. /**
  35332. * Specifies if the ready state should be checked on each call
  35333. */
  35334. this.checkReadyOnEveryCall = false;
  35335. /**
  35336. * Specifies if the ready state should be checked once
  35337. */
  35338. this.checkReadyOnlyOnce = false;
  35339. /**
  35340. * The state of the material
  35341. */
  35342. this.state = "";
  35343. /**
  35344. * The alpha value of the material
  35345. */
  35346. this._alpha = 1.0;
  35347. /**
  35348. * Specifies if back face culling is enabled
  35349. */
  35350. this._backFaceCulling = true;
  35351. /**
  35352. * Specifies if the material should be serialized
  35353. */
  35354. this.doNotSerialize = false;
  35355. /**
  35356. * Specifies if the effect should be stored on sub meshes
  35357. */
  35358. this.storeEffectOnSubMeshes = false;
  35359. /**
  35360. * An event triggered when the material is disposed
  35361. */
  35362. this.onDisposeObservable = new BABYLON.Observable();
  35363. /**
  35364. * Stores the value of the alpha mode
  35365. */
  35366. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35367. /**
  35368. * Stores the state of the need depth pre-pass value
  35369. */
  35370. this._needDepthPrePass = false;
  35371. /**
  35372. * Specifies if depth writing should be disabled
  35373. */
  35374. this.disableDepthWrite = false;
  35375. /**
  35376. * Specifies if depth writing should be forced
  35377. */
  35378. this.forceDepthWrite = false;
  35379. /**
  35380. * Specifies if there should be a separate pass for culling
  35381. */
  35382. this.separateCullingPass = false;
  35383. /**
  35384. * Stores the state specifing if fog should be enabled
  35385. */
  35386. this._fogEnabled = true;
  35387. /**
  35388. * Stores the size of points
  35389. */
  35390. this.pointSize = 1.0;
  35391. /**
  35392. * Stores the z offset value
  35393. */
  35394. this.zOffset = 0;
  35395. /**
  35396. * @hidden
  35397. * Specifies if the material was previously ready
  35398. */
  35399. this._wasPreviouslyReady = false;
  35400. /**
  35401. * Stores the fill mode state
  35402. */
  35403. this._fillMode = Material.TriangleFillMode;
  35404. this.name = name;
  35405. this.id = name || BABYLON.Tools.RandomId();
  35406. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35407. this.uniqueId = this._scene.getUniqueId();
  35408. if (this._scene.useRightHandedSystem) {
  35409. this.sideOrientation = Material.ClockWiseSideOrientation;
  35410. }
  35411. else {
  35412. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35413. }
  35414. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35415. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35416. if (!doNotAdd) {
  35417. this._scene.materials.push(this);
  35418. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35419. }
  35420. }
  35421. Object.defineProperty(Material, "TriangleFillMode", {
  35422. /**
  35423. * Returns the triangle fill mode
  35424. */
  35425. get: function () {
  35426. return Material._TriangleFillMode;
  35427. },
  35428. enumerable: true,
  35429. configurable: true
  35430. });
  35431. Object.defineProperty(Material, "WireFrameFillMode", {
  35432. /**
  35433. * Returns the wireframe mode
  35434. */
  35435. get: function () {
  35436. return Material._WireFrameFillMode;
  35437. },
  35438. enumerable: true,
  35439. configurable: true
  35440. });
  35441. Object.defineProperty(Material, "PointFillMode", {
  35442. /**
  35443. * Returns the point fill mode
  35444. */
  35445. get: function () {
  35446. return Material._PointFillMode;
  35447. },
  35448. enumerable: true,
  35449. configurable: true
  35450. });
  35451. Object.defineProperty(Material, "PointListDrawMode", {
  35452. /**
  35453. * Returns the point list draw mode
  35454. */
  35455. get: function () {
  35456. return Material._PointListDrawMode;
  35457. },
  35458. enumerable: true,
  35459. configurable: true
  35460. });
  35461. Object.defineProperty(Material, "LineListDrawMode", {
  35462. /**
  35463. * Returns the line list draw mode
  35464. */
  35465. get: function () {
  35466. return Material._LineListDrawMode;
  35467. },
  35468. enumerable: true,
  35469. configurable: true
  35470. });
  35471. Object.defineProperty(Material, "LineLoopDrawMode", {
  35472. /**
  35473. * Returns the line loop draw mode
  35474. */
  35475. get: function () {
  35476. return Material._LineLoopDrawMode;
  35477. },
  35478. enumerable: true,
  35479. configurable: true
  35480. });
  35481. Object.defineProperty(Material, "LineStripDrawMode", {
  35482. /**
  35483. * Returns the line strip draw mode
  35484. */
  35485. get: function () {
  35486. return Material._LineStripDrawMode;
  35487. },
  35488. enumerable: true,
  35489. configurable: true
  35490. });
  35491. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35492. /**
  35493. * Returns the triangle strip draw mode
  35494. */
  35495. get: function () {
  35496. return Material._TriangleStripDrawMode;
  35497. },
  35498. enumerable: true,
  35499. configurable: true
  35500. });
  35501. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35502. /**
  35503. * Returns the triangle fan draw mode
  35504. */
  35505. get: function () {
  35506. return Material._TriangleFanDrawMode;
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35512. /**
  35513. * Returns the clock-wise side orientation
  35514. */
  35515. get: function () {
  35516. return Material._ClockWiseSideOrientation;
  35517. },
  35518. enumerable: true,
  35519. configurable: true
  35520. });
  35521. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35522. /**
  35523. * Returns the counter clock-wise side orientation
  35524. */
  35525. get: function () {
  35526. return Material._CounterClockWiseSideOrientation;
  35527. },
  35528. enumerable: true,
  35529. configurable: true
  35530. });
  35531. Object.defineProperty(Material.prototype, "alpha", {
  35532. /**
  35533. * Gets the alpha value of the material
  35534. */
  35535. get: function () {
  35536. return this._alpha;
  35537. },
  35538. /**
  35539. * Sets the alpha value of the material
  35540. */
  35541. set: function (value) {
  35542. if (this._alpha === value) {
  35543. return;
  35544. }
  35545. this._alpha = value;
  35546. this.markAsDirty(Material.MiscDirtyFlag);
  35547. },
  35548. enumerable: true,
  35549. configurable: true
  35550. });
  35551. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35552. /**
  35553. * Gets the back-face culling state
  35554. */
  35555. get: function () {
  35556. return this._backFaceCulling;
  35557. },
  35558. /**
  35559. * Sets the back-face culling state
  35560. */
  35561. set: function (value) {
  35562. if (this._backFaceCulling === value) {
  35563. return;
  35564. }
  35565. this._backFaceCulling = value;
  35566. this.markAsDirty(Material.TextureDirtyFlag);
  35567. },
  35568. enumerable: true,
  35569. configurable: true
  35570. });
  35571. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35572. /**
  35573. * Gets a boolean indicating that current material needs to register RTT
  35574. */
  35575. get: function () {
  35576. return false;
  35577. },
  35578. enumerable: true,
  35579. configurable: true
  35580. });
  35581. Object.defineProperty(Material.prototype, "onDispose", {
  35582. /**
  35583. * Called during a dispose event
  35584. */
  35585. set: function (callback) {
  35586. if (this._onDisposeObserver) {
  35587. this.onDisposeObservable.remove(this._onDisposeObserver);
  35588. }
  35589. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35590. },
  35591. enumerable: true,
  35592. configurable: true
  35593. });
  35594. Object.defineProperty(Material.prototype, "onBindObservable", {
  35595. /**
  35596. * An event triggered when the material is bound
  35597. */
  35598. get: function () {
  35599. if (!this._onBindObservable) {
  35600. this._onBindObservable = new BABYLON.Observable();
  35601. }
  35602. return this._onBindObservable;
  35603. },
  35604. enumerable: true,
  35605. configurable: true
  35606. });
  35607. Object.defineProperty(Material.prototype, "onBind", {
  35608. /**
  35609. * Called during a bind event
  35610. */
  35611. set: function (callback) {
  35612. if (this._onBindObserver) {
  35613. this.onBindObservable.remove(this._onBindObserver);
  35614. }
  35615. this._onBindObserver = this.onBindObservable.add(callback);
  35616. },
  35617. enumerable: true,
  35618. configurable: true
  35619. });
  35620. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35621. /**
  35622. * An event triggered when the material is unbound
  35623. */
  35624. get: function () {
  35625. if (!this._onUnBindObservable) {
  35626. this._onUnBindObservable = new BABYLON.Observable();
  35627. }
  35628. return this._onUnBindObservable;
  35629. },
  35630. enumerable: true,
  35631. configurable: true
  35632. });
  35633. Object.defineProperty(Material.prototype, "alphaMode", {
  35634. /**
  35635. * Gets the value of the alpha mode
  35636. */
  35637. get: function () {
  35638. return this._alphaMode;
  35639. },
  35640. /**
  35641. * Sets the value of the alpha mode.
  35642. *
  35643. * | Value | Type | Description |
  35644. * | --- | --- | --- |
  35645. * | 0 | ALPHA_DISABLE | |
  35646. * | 1 | ALPHA_ADD | |
  35647. * | 2 | ALPHA_COMBINE | |
  35648. * | 3 | ALPHA_SUBTRACT | |
  35649. * | 4 | ALPHA_MULTIPLY | |
  35650. * | 5 | ALPHA_MAXIMIZED | |
  35651. * | 6 | ALPHA_ONEONE | |
  35652. * | 7 | ALPHA_PREMULTIPLIED | |
  35653. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35654. * | 9 | ALPHA_INTERPOLATE | |
  35655. * | 10 | ALPHA_SCREENMODE | |
  35656. *
  35657. */
  35658. set: function (value) {
  35659. if (this._alphaMode === value) {
  35660. return;
  35661. }
  35662. this._alphaMode = value;
  35663. this.markAsDirty(Material.TextureDirtyFlag);
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35669. /**
  35670. * Gets the depth pre-pass value
  35671. */
  35672. get: function () {
  35673. return this._needDepthPrePass;
  35674. },
  35675. /**
  35676. * Sets the need depth pre-pass value
  35677. */
  35678. set: function (value) {
  35679. if (this._needDepthPrePass === value) {
  35680. return;
  35681. }
  35682. this._needDepthPrePass = value;
  35683. if (this._needDepthPrePass) {
  35684. this.checkReadyOnEveryCall = true;
  35685. }
  35686. },
  35687. enumerable: true,
  35688. configurable: true
  35689. });
  35690. Object.defineProperty(Material.prototype, "fogEnabled", {
  35691. /**
  35692. * Gets the value of the fog enabled state
  35693. */
  35694. get: function () {
  35695. return this._fogEnabled;
  35696. },
  35697. /**
  35698. * Sets the state for enabling fog
  35699. */
  35700. set: function (value) {
  35701. if (this._fogEnabled === value) {
  35702. return;
  35703. }
  35704. this._fogEnabled = value;
  35705. this.markAsDirty(Material.MiscDirtyFlag);
  35706. },
  35707. enumerable: true,
  35708. configurable: true
  35709. });
  35710. Object.defineProperty(Material.prototype, "wireframe", {
  35711. /**
  35712. * Gets a value specifying if wireframe mode is enabled
  35713. */
  35714. get: function () {
  35715. switch (this._fillMode) {
  35716. case Material.WireFrameFillMode:
  35717. case Material.LineListDrawMode:
  35718. case Material.LineLoopDrawMode:
  35719. case Material.LineStripDrawMode:
  35720. return true;
  35721. }
  35722. return this._scene.forceWireframe;
  35723. },
  35724. /**
  35725. * Sets the state of wireframe mode
  35726. */
  35727. set: function (value) {
  35728. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35729. },
  35730. enumerable: true,
  35731. configurable: true
  35732. });
  35733. Object.defineProperty(Material.prototype, "pointsCloud", {
  35734. /**
  35735. * Gets the value specifying if point clouds are enabled
  35736. */
  35737. get: function () {
  35738. switch (this._fillMode) {
  35739. case Material.PointFillMode:
  35740. case Material.PointListDrawMode:
  35741. return true;
  35742. }
  35743. return this._scene.forcePointsCloud;
  35744. },
  35745. /**
  35746. * Sets the state of point cloud mode
  35747. */
  35748. set: function (value) {
  35749. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35750. },
  35751. enumerable: true,
  35752. configurable: true
  35753. });
  35754. Object.defineProperty(Material.prototype, "fillMode", {
  35755. /**
  35756. * Gets the material fill mode
  35757. */
  35758. get: function () {
  35759. return this._fillMode;
  35760. },
  35761. /**
  35762. * Sets the material fill mode
  35763. */
  35764. set: function (value) {
  35765. if (this._fillMode === value) {
  35766. return;
  35767. }
  35768. this._fillMode = value;
  35769. this.markAsDirty(Material.MiscDirtyFlag);
  35770. },
  35771. enumerable: true,
  35772. configurable: true
  35773. });
  35774. /**
  35775. * Returns a string representation of the current material
  35776. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35777. * @returns a string with material information
  35778. */
  35779. Material.prototype.toString = function (fullDetails) {
  35780. var ret = "Name: " + this.name;
  35781. if (fullDetails) {
  35782. }
  35783. return ret;
  35784. };
  35785. /**
  35786. * Gets the class name of the material
  35787. * @returns a string with the class name of the material
  35788. */
  35789. Material.prototype.getClassName = function () {
  35790. return "Material";
  35791. };
  35792. Object.defineProperty(Material.prototype, "isFrozen", {
  35793. /**
  35794. * Specifies if updates for the material been locked
  35795. */
  35796. get: function () {
  35797. return this.checkReadyOnlyOnce;
  35798. },
  35799. enumerable: true,
  35800. configurable: true
  35801. });
  35802. /**
  35803. * Locks updates for the material
  35804. */
  35805. Material.prototype.freeze = function () {
  35806. this.checkReadyOnlyOnce = true;
  35807. };
  35808. /**
  35809. * Unlocks updates for the material
  35810. */
  35811. Material.prototype.unfreeze = function () {
  35812. this.checkReadyOnlyOnce = false;
  35813. };
  35814. /**
  35815. * Specifies if the material is ready to be used
  35816. * @param mesh defines the mesh to check
  35817. * @param useInstances specifies if instances should be used
  35818. * @returns a boolean indicating if the material is ready to be used
  35819. */
  35820. Material.prototype.isReady = function (mesh, useInstances) {
  35821. return true;
  35822. };
  35823. /**
  35824. * Specifies that the submesh is ready to be used
  35825. * @param mesh defines the mesh to check
  35826. * @param subMesh defines which submesh to check
  35827. * @param useInstances specifies that instances should be used
  35828. * @returns a boolean indicating that the submesh is ready or not
  35829. */
  35830. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35831. return false;
  35832. };
  35833. /**
  35834. * Returns the material effect
  35835. * @returns the effect associated with the material
  35836. */
  35837. Material.prototype.getEffect = function () {
  35838. return this._effect;
  35839. };
  35840. /**
  35841. * Returns the current scene
  35842. * @returns a Scene
  35843. */
  35844. Material.prototype.getScene = function () {
  35845. return this._scene;
  35846. };
  35847. /**
  35848. * Specifies if the material will require alpha blending
  35849. * @returns a boolean specifying if alpha blending is needed
  35850. */
  35851. Material.prototype.needAlphaBlending = function () {
  35852. return (this.alpha < 1.0);
  35853. };
  35854. /**
  35855. * Specifies if the mesh will require alpha blending
  35856. * @param mesh defines the mesh to check
  35857. * @returns a boolean specifying if alpha blending is needed for the mesh
  35858. */
  35859. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35860. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35861. };
  35862. /**
  35863. * Specifies if this material should be rendered in alpha test mode
  35864. * @returns a boolean specifying if an alpha test is needed.
  35865. */
  35866. Material.prototype.needAlphaTesting = function () {
  35867. return false;
  35868. };
  35869. /**
  35870. * Gets the texture used for the alpha test
  35871. * @returns the texture to use for alpha testing
  35872. */
  35873. Material.prototype.getAlphaTestTexture = function () {
  35874. return null;
  35875. };
  35876. /**
  35877. * Marks the material to indicate that it needs to be re-calculated
  35878. */
  35879. Material.prototype.markDirty = function () {
  35880. this._wasPreviouslyReady = false;
  35881. };
  35882. /** @hidden */
  35883. Material.prototype._preBind = function (effect, overrideOrientation) {
  35884. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35885. var engine = this._scene.getEngine();
  35886. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35887. var reverse = orientation === Material.ClockWiseSideOrientation;
  35888. engine.enableEffect(effect ? effect : this._effect);
  35889. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35890. return reverse;
  35891. };
  35892. /**
  35893. * Binds the material to the mesh
  35894. * @param world defines the world transformation matrix
  35895. * @param mesh defines the mesh to bind the material to
  35896. */
  35897. Material.prototype.bind = function (world, mesh) {
  35898. };
  35899. /**
  35900. * Binds the submesh to the material
  35901. * @param world defines the world transformation matrix
  35902. * @param mesh defines the mesh containing the submesh
  35903. * @param subMesh defines the submesh to bind the material to
  35904. */
  35905. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35906. };
  35907. /**
  35908. * Binds the world matrix to the material
  35909. * @param world defines the world transformation matrix
  35910. */
  35911. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35912. };
  35913. /**
  35914. * Binds the scene's uniform buffer to the effect.
  35915. * @param effect defines the effect to bind to the scene uniform buffer
  35916. * @param sceneUbo defines the uniform buffer storing scene data
  35917. */
  35918. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35919. sceneUbo.bindToEffect(effect, "Scene");
  35920. };
  35921. /**
  35922. * Binds the view matrix to the effect
  35923. * @param effect defines the effect to bind the view matrix to
  35924. */
  35925. Material.prototype.bindView = function (effect) {
  35926. if (!this._useUBO) {
  35927. effect.setMatrix("view", this.getScene().getViewMatrix());
  35928. }
  35929. else {
  35930. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35931. }
  35932. };
  35933. /**
  35934. * Binds the view projection matrix to the effect
  35935. * @param effect defines the effect to bind the view projection matrix to
  35936. */
  35937. Material.prototype.bindViewProjection = function (effect) {
  35938. if (!this._useUBO) {
  35939. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35940. }
  35941. else {
  35942. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35943. }
  35944. };
  35945. /**
  35946. * Specifies if material alpha testing should be turned on for the mesh
  35947. * @param mesh defines the mesh to check
  35948. */
  35949. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35950. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35951. };
  35952. /**
  35953. * Processes to execute after binding the material to a mesh
  35954. * @param mesh defines the rendered mesh
  35955. */
  35956. Material.prototype._afterBind = function (mesh) {
  35957. this._scene._cachedMaterial = this;
  35958. if (mesh) {
  35959. this._scene._cachedVisibility = mesh.visibility;
  35960. }
  35961. else {
  35962. this._scene._cachedVisibility = 1;
  35963. }
  35964. if (this._onBindObservable && mesh) {
  35965. this._onBindObservable.notifyObservers(mesh);
  35966. }
  35967. if (this.disableDepthWrite) {
  35968. var engine = this._scene.getEngine();
  35969. this._cachedDepthWriteState = engine.getDepthWrite();
  35970. engine.setDepthWrite(false);
  35971. }
  35972. };
  35973. /**
  35974. * Unbinds the material from the mesh
  35975. */
  35976. Material.prototype.unbind = function () {
  35977. if (this._onUnBindObservable) {
  35978. this._onUnBindObservable.notifyObservers(this);
  35979. }
  35980. if (this.disableDepthWrite) {
  35981. var engine = this._scene.getEngine();
  35982. engine.setDepthWrite(this._cachedDepthWriteState);
  35983. }
  35984. };
  35985. /**
  35986. * Gets the active textures from the material
  35987. * @returns an array of textures
  35988. */
  35989. Material.prototype.getActiveTextures = function () {
  35990. return [];
  35991. };
  35992. /**
  35993. * Specifies if the material uses a texture
  35994. * @param texture defines the texture to check against the material
  35995. * @returns a boolean specifying if the material uses the texture
  35996. */
  35997. Material.prototype.hasTexture = function (texture) {
  35998. return false;
  35999. };
  36000. /**
  36001. * Makes a duplicate of the material, and gives it a new name
  36002. * @param name defines the new name for the duplicated material
  36003. * @returns the cloned material
  36004. */
  36005. Material.prototype.clone = function (name) {
  36006. return null;
  36007. };
  36008. /**
  36009. * Gets the meshes bound to the material
  36010. * @returns an array of meshes bound to the material
  36011. */
  36012. Material.prototype.getBindedMeshes = function () {
  36013. var result = new Array();
  36014. for (var index = 0; index < this._scene.meshes.length; index++) {
  36015. var mesh = this._scene.meshes[index];
  36016. if (mesh.material === this) {
  36017. result.push(mesh);
  36018. }
  36019. }
  36020. return result;
  36021. };
  36022. /**
  36023. * Force shader compilation
  36024. * @param mesh defines the mesh associated with this material
  36025. * @param onCompiled defines a function to execute once the material is compiled
  36026. * @param options defines the options to configure the compilation
  36027. */
  36028. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36029. var _this = this;
  36030. var localOptions = __assign({ clipPlane: false }, options);
  36031. var subMesh = new BABYLON.BaseSubMesh();
  36032. var scene = this.getScene();
  36033. var checkReady = function () {
  36034. if (!_this._scene || !_this._scene.getEngine()) {
  36035. return;
  36036. }
  36037. if (subMesh._materialDefines) {
  36038. subMesh._materialDefines._renderId = -1;
  36039. }
  36040. var clipPlaneState = scene.clipPlane;
  36041. if (localOptions.clipPlane) {
  36042. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36043. }
  36044. if (_this.storeEffectOnSubMeshes) {
  36045. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36046. if (onCompiled) {
  36047. onCompiled(_this);
  36048. }
  36049. }
  36050. else {
  36051. setTimeout(checkReady, 16);
  36052. }
  36053. }
  36054. else {
  36055. if (_this.isReady(mesh)) {
  36056. if (onCompiled) {
  36057. onCompiled(_this);
  36058. }
  36059. }
  36060. else {
  36061. setTimeout(checkReady, 16);
  36062. }
  36063. }
  36064. if (localOptions.clipPlane) {
  36065. scene.clipPlane = clipPlaneState;
  36066. }
  36067. };
  36068. checkReady();
  36069. };
  36070. /**
  36071. * Force shader compilation
  36072. * @param mesh defines the mesh that will use this material
  36073. * @param options defines additional options for compiling the shaders
  36074. * @returns a promise that resolves when the compilation completes
  36075. */
  36076. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36077. var _this = this;
  36078. return new Promise(function (resolve) {
  36079. _this.forceCompilation(mesh, function () {
  36080. resolve();
  36081. }, options);
  36082. });
  36083. };
  36084. /**
  36085. * Marks a define in the material to indicate that it needs to be re-computed
  36086. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36087. */
  36088. Material.prototype.markAsDirty = function (flag) {
  36089. if (flag & Material.TextureDirtyFlag) {
  36090. this._markAllSubMeshesAsTexturesDirty();
  36091. }
  36092. if (flag & Material.LightDirtyFlag) {
  36093. this._markAllSubMeshesAsLightsDirty();
  36094. }
  36095. if (flag & Material.FresnelDirtyFlag) {
  36096. this._markAllSubMeshesAsFresnelDirty();
  36097. }
  36098. if (flag & Material.AttributesDirtyFlag) {
  36099. this._markAllSubMeshesAsAttributesDirty();
  36100. }
  36101. if (flag & Material.MiscDirtyFlag) {
  36102. this._markAllSubMeshesAsMiscDirty();
  36103. }
  36104. this.getScene().resetCachedMaterial();
  36105. };
  36106. /**
  36107. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36108. * @param func defines a function which checks material defines against the submeshes
  36109. */
  36110. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36111. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36112. var mesh = _a[_i];
  36113. if (!mesh.subMeshes) {
  36114. continue;
  36115. }
  36116. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36117. var subMesh = _c[_b];
  36118. if (subMesh.getMaterial() !== this) {
  36119. continue;
  36120. }
  36121. if (!subMesh._materialDefines) {
  36122. continue;
  36123. }
  36124. func(subMesh._materialDefines);
  36125. }
  36126. }
  36127. };
  36128. /**
  36129. * Indicates that image processing needs to be re-calculated for all submeshes
  36130. */
  36131. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36132. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36133. };
  36134. /**
  36135. * Indicates that textures need to be re-calculated for all submeshes
  36136. */
  36137. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36138. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36139. };
  36140. /**
  36141. * Indicates that fresnel needs to be re-calculated for all submeshes
  36142. */
  36143. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36144. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36145. };
  36146. /**
  36147. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36148. */
  36149. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36150. this._markAllSubMeshesAsDirty(function (defines) {
  36151. defines.markAsFresnelDirty();
  36152. defines.markAsMiscDirty();
  36153. });
  36154. };
  36155. /**
  36156. * Indicates that lights need to be re-calculated for all submeshes
  36157. */
  36158. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36159. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36160. };
  36161. /**
  36162. * Indicates that attributes need to be re-calculated for all submeshes
  36163. */
  36164. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36165. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36166. };
  36167. /**
  36168. * Indicates that misc needs to be re-calculated for all submeshes
  36169. */
  36170. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36171. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36172. };
  36173. /**
  36174. * Indicates that textures and misc need to be re-calculated for all submeshes
  36175. */
  36176. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36177. this._markAllSubMeshesAsDirty(function (defines) {
  36178. defines.markAsTexturesDirty();
  36179. defines.markAsMiscDirty();
  36180. });
  36181. };
  36182. /**
  36183. * Disposes the material
  36184. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36185. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36186. */
  36187. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36188. // Animations
  36189. this.getScene().stopAnimation(this);
  36190. this.getScene().freeProcessedMaterials();
  36191. // Remove from scene
  36192. var index = this._scene.materials.indexOf(this);
  36193. if (index >= 0) {
  36194. this._scene.materials.splice(index, 1);
  36195. }
  36196. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36197. // Remove from meshes
  36198. for (index = 0; index < this._scene.meshes.length; index++) {
  36199. var mesh = this._scene.meshes[index];
  36200. if (mesh.material === this) {
  36201. mesh.material = null;
  36202. if (mesh.geometry) {
  36203. var geometry = (mesh.geometry);
  36204. if (this.storeEffectOnSubMeshes) {
  36205. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36206. var subMesh = _a[_i];
  36207. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36208. if (forceDisposeEffect && subMesh._materialEffect) {
  36209. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36210. }
  36211. }
  36212. }
  36213. else {
  36214. geometry._releaseVertexArrayObject(this._effect);
  36215. }
  36216. }
  36217. }
  36218. }
  36219. this._uniformBuffer.dispose();
  36220. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36221. if (forceDisposeEffect && this._effect) {
  36222. if (!this.storeEffectOnSubMeshes) {
  36223. this._scene.getEngine()._releaseEffect(this._effect);
  36224. }
  36225. this._effect = null;
  36226. }
  36227. // Callback
  36228. this.onDisposeObservable.notifyObservers(this);
  36229. this.onDisposeObservable.clear();
  36230. if (this._onBindObservable) {
  36231. this._onBindObservable.clear();
  36232. }
  36233. if (this._onUnBindObservable) {
  36234. this._onUnBindObservable.clear();
  36235. }
  36236. };
  36237. /**
  36238. * Serializes this material
  36239. * @returns the serialized material object
  36240. */
  36241. Material.prototype.serialize = function () {
  36242. return BABYLON.SerializationHelper.Serialize(this);
  36243. };
  36244. /**
  36245. * Creates a MultiMaterial from parsed MultiMaterial data.
  36246. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36247. * @param scene defines the hosting scene
  36248. * @returns a new MultiMaterial
  36249. */
  36250. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36251. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36252. multiMaterial.id = parsedMultiMaterial.id;
  36253. if (BABYLON.Tags) {
  36254. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36255. }
  36256. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36257. var subMatId = parsedMultiMaterial.materials[matIndex];
  36258. if (subMatId) {
  36259. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36260. }
  36261. else {
  36262. multiMaterial.subMaterials.push(null);
  36263. }
  36264. }
  36265. return multiMaterial;
  36266. };
  36267. /**
  36268. * Creates a material from parsed material data
  36269. * @param parsedMaterial defines parsed material data
  36270. * @param scene defines the hosting scene
  36271. * @param rootUrl defines the root URL to use to load textures
  36272. * @returns a new material
  36273. */
  36274. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36275. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36276. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36277. }
  36278. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36279. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36280. if (!BABYLON.LegacyPBRMaterial) {
  36281. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36282. return;
  36283. }
  36284. }
  36285. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36286. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36287. };
  36288. // Triangle views
  36289. Material._TriangleFillMode = 0;
  36290. Material._WireFrameFillMode = 1;
  36291. Material._PointFillMode = 2;
  36292. // Draw modes
  36293. Material._PointListDrawMode = 3;
  36294. Material._LineListDrawMode = 4;
  36295. Material._LineLoopDrawMode = 5;
  36296. Material._LineStripDrawMode = 6;
  36297. Material._TriangleStripDrawMode = 7;
  36298. Material._TriangleFanDrawMode = 8;
  36299. /**
  36300. * Stores the clock-wise side orientation
  36301. */
  36302. Material._ClockWiseSideOrientation = 0;
  36303. /**
  36304. * Stores the counter clock-wise side orientation
  36305. */
  36306. Material._CounterClockWiseSideOrientation = 1;
  36307. /**
  36308. * The dirty texture flag value
  36309. */
  36310. Material.TextureDirtyFlag = 1;
  36311. /**
  36312. * The dirty light flag value
  36313. */
  36314. Material.LightDirtyFlag = 2;
  36315. /**
  36316. * The dirty fresnel flag value
  36317. */
  36318. Material.FresnelDirtyFlag = 4;
  36319. /**
  36320. * The dirty attribute flag value
  36321. */
  36322. Material.AttributesDirtyFlag = 8;
  36323. /**
  36324. * The dirty misc flag value
  36325. */
  36326. Material.MiscDirtyFlag = 16;
  36327. /**
  36328. * The all dirty flag value
  36329. */
  36330. Material.AllDirtyFlag = 31;
  36331. __decorate([
  36332. BABYLON.serialize()
  36333. ], Material.prototype, "id", void 0);
  36334. __decorate([
  36335. BABYLON.serialize()
  36336. ], Material.prototype, "uniqueId", void 0);
  36337. __decorate([
  36338. BABYLON.serialize()
  36339. ], Material.prototype, "name", void 0);
  36340. __decorate([
  36341. BABYLON.serialize()
  36342. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36343. __decorate([
  36344. BABYLON.serialize()
  36345. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36346. __decorate([
  36347. BABYLON.serialize()
  36348. ], Material.prototype, "state", void 0);
  36349. __decorate([
  36350. BABYLON.serialize("alpha")
  36351. ], Material.prototype, "_alpha", void 0);
  36352. __decorate([
  36353. BABYLON.serialize("backFaceCulling")
  36354. ], Material.prototype, "_backFaceCulling", void 0);
  36355. __decorate([
  36356. BABYLON.serialize()
  36357. ], Material.prototype, "sideOrientation", void 0);
  36358. __decorate([
  36359. BABYLON.serialize("alphaMode")
  36360. ], Material.prototype, "_alphaMode", void 0);
  36361. __decorate([
  36362. BABYLON.serialize()
  36363. ], Material.prototype, "_needDepthPrePass", void 0);
  36364. __decorate([
  36365. BABYLON.serialize()
  36366. ], Material.prototype, "disableDepthWrite", void 0);
  36367. __decorate([
  36368. BABYLON.serialize()
  36369. ], Material.prototype, "forceDepthWrite", void 0);
  36370. __decorate([
  36371. BABYLON.serialize()
  36372. ], Material.prototype, "separateCullingPass", void 0);
  36373. __decorate([
  36374. BABYLON.serialize("fogEnabled")
  36375. ], Material.prototype, "_fogEnabled", void 0);
  36376. __decorate([
  36377. BABYLON.serialize()
  36378. ], Material.prototype, "pointSize", void 0);
  36379. __decorate([
  36380. BABYLON.serialize()
  36381. ], Material.prototype, "zOffset", void 0);
  36382. __decorate([
  36383. BABYLON.serialize()
  36384. ], Material.prototype, "wireframe", null);
  36385. __decorate([
  36386. BABYLON.serialize()
  36387. ], Material.prototype, "pointsCloud", null);
  36388. __decorate([
  36389. BABYLON.serialize()
  36390. ], Material.prototype, "fillMode", null);
  36391. return Material;
  36392. }());
  36393. BABYLON.Material = Material;
  36394. })(BABYLON || (BABYLON = {}));
  36395. //# sourceMappingURL=babylon.material.js.map
  36396. var BABYLON;
  36397. (function (BABYLON) {
  36398. /**
  36399. * Uniform buffer objects.
  36400. *
  36401. * Handles blocks of uniform on the GPU.
  36402. *
  36403. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36404. *
  36405. * For more information, please refer to :
  36406. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36407. */
  36408. var UniformBuffer = /** @class */ (function () {
  36409. /**
  36410. * Instantiates a new Uniform buffer objects.
  36411. *
  36412. * Handles blocks of uniform on the GPU.
  36413. *
  36414. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36415. *
  36416. * For more information, please refer to :
  36417. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36418. * @param engine Define the engine the buffer is associated with
  36419. * @param data Define the data contained in the buffer
  36420. * @param dynamic Define if the buffer is updatable
  36421. */
  36422. function UniformBuffer(engine, data, dynamic) {
  36423. this._engine = engine;
  36424. this._noUBO = !engine.supportsUniformBuffers;
  36425. this._dynamic = dynamic;
  36426. this._data = data || [];
  36427. this._uniformLocations = {};
  36428. this._uniformSizes = {};
  36429. this._uniformLocationPointer = 0;
  36430. this._needSync = false;
  36431. if (this._noUBO) {
  36432. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36433. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36434. this.updateFloat = this._updateFloatForEffect;
  36435. this.updateFloat2 = this._updateFloat2ForEffect;
  36436. this.updateFloat3 = this._updateFloat3ForEffect;
  36437. this.updateFloat4 = this._updateFloat4ForEffect;
  36438. this.updateMatrix = this._updateMatrixForEffect;
  36439. this.updateVector3 = this._updateVector3ForEffect;
  36440. this.updateVector4 = this._updateVector4ForEffect;
  36441. this.updateColor3 = this._updateColor3ForEffect;
  36442. this.updateColor4 = this._updateColor4ForEffect;
  36443. }
  36444. else {
  36445. this._engine._uniformBuffers.push(this);
  36446. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36447. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36448. this.updateFloat = this._updateFloatForUniform;
  36449. this.updateFloat2 = this._updateFloat2ForUniform;
  36450. this.updateFloat3 = this._updateFloat3ForUniform;
  36451. this.updateFloat4 = this._updateFloat4ForUniform;
  36452. this.updateMatrix = this._updateMatrixForUniform;
  36453. this.updateVector3 = this._updateVector3ForUniform;
  36454. this.updateVector4 = this._updateVector4ForUniform;
  36455. this.updateColor3 = this._updateColor3ForUniform;
  36456. this.updateColor4 = this._updateColor4ForUniform;
  36457. }
  36458. }
  36459. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36460. /**
  36461. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36462. * or just falling back on setUniformXXX calls.
  36463. */
  36464. get: function () {
  36465. return !this._noUBO;
  36466. },
  36467. enumerable: true,
  36468. configurable: true
  36469. });
  36470. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36471. /**
  36472. * Indicates if the WebGL underlying uniform buffer is in sync
  36473. * with the javascript cache data.
  36474. */
  36475. get: function () {
  36476. return !this._needSync;
  36477. },
  36478. enumerable: true,
  36479. configurable: true
  36480. });
  36481. /**
  36482. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36483. * Also, a dynamic UniformBuffer will disable cache verification and always
  36484. * update the underlying WebGL uniform buffer to the GPU.
  36485. * @returns if Dynamic, otherwise false
  36486. */
  36487. UniformBuffer.prototype.isDynamic = function () {
  36488. return this._dynamic !== undefined;
  36489. };
  36490. /**
  36491. * The data cache on JS side.
  36492. * @returns the underlying data as a float array
  36493. */
  36494. UniformBuffer.prototype.getData = function () {
  36495. return this._bufferData;
  36496. };
  36497. /**
  36498. * The underlying WebGL Uniform buffer.
  36499. * @returns the webgl buffer
  36500. */
  36501. UniformBuffer.prototype.getBuffer = function () {
  36502. return this._buffer;
  36503. };
  36504. /**
  36505. * std140 layout specifies how to align data within an UBO structure.
  36506. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36507. * for specs.
  36508. */
  36509. UniformBuffer.prototype._fillAlignment = function (size) {
  36510. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36511. // and 4x4 matrices
  36512. // TODO : change if other types are used
  36513. var alignment;
  36514. if (size <= 2) {
  36515. alignment = size;
  36516. }
  36517. else {
  36518. alignment = 4;
  36519. }
  36520. if ((this._uniformLocationPointer % alignment) !== 0) {
  36521. var oldPointer = this._uniformLocationPointer;
  36522. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36523. var diff = this._uniformLocationPointer - oldPointer;
  36524. for (var i = 0; i < diff; i++) {
  36525. this._data.push(0);
  36526. }
  36527. }
  36528. };
  36529. /**
  36530. * Adds an uniform in the buffer.
  36531. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36532. * for the layout to be correct !
  36533. * @param name Name of the uniform, as used in the uniform block in the shader.
  36534. * @param size Data size, or data directly.
  36535. */
  36536. UniformBuffer.prototype.addUniform = function (name, size) {
  36537. if (this._noUBO) {
  36538. return;
  36539. }
  36540. if (this._uniformLocations[name] !== undefined) {
  36541. // Already existing uniform
  36542. return;
  36543. }
  36544. // This function must be called in the order of the shader layout !
  36545. // size can be the size of the uniform, or data directly
  36546. var data;
  36547. if (size instanceof Array) {
  36548. data = size;
  36549. size = data.length;
  36550. }
  36551. else {
  36552. size = size;
  36553. data = [];
  36554. // Fill with zeros
  36555. for (var i = 0; i < size; i++) {
  36556. data.push(0);
  36557. }
  36558. }
  36559. this._fillAlignment(size);
  36560. this._uniformSizes[name] = size;
  36561. this._uniformLocations[name] = this._uniformLocationPointer;
  36562. this._uniformLocationPointer += size;
  36563. for (var i = 0; i < size; i++) {
  36564. this._data.push(data[i]);
  36565. }
  36566. this._needSync = true;
  36567. };
  36568. /**
  36569. * Adds a Matrix 4x4 to the uniform buffer.
  36570. * @param name Name of the uniform, as used in the uniform block in the shader.
  36571. * @param mat A 4x4 matrix.
  36572. */
  36573. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36574. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36575. };
  36576. /**
  36577. * Adds a vec2 to the uniform buffer.
  36578. * @param name Name of the uniform, as used in the uniform block in the shader.
  36579. * @param x Define the x component value of the vec2
  36580. * @param y Define the y component value of the vec2
  36581. */
  36582. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36583. var temp = [x, y];
  36584. this.addUniform(name, temp);
  36585. };
  36586. /**
  36587. * Adds a vec3 to the uniform buffer.
  36588. * @param name Name of the uniform, as used in the uniform block in the shader.
  36589. * @param x Define the x component value of the vec3
  36590. * @param y Define the y component value of the vec3
  36591. * @param z Define the z component value of the vec3
  36592. */
  36593. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36594. var temp = [x, y, z];
  36595. this.addUniform(name, temp);
  36596. };
  36597. /**
  36598. * Adds a vec3 to the uniform buffer.
  36599. * @param name Name of the uniform, as used in the uniform block in the shader.
  36600. * @param color Define the vec3 from a Color
  36601. */
  36602. UniformBuffer.prototype.addColor3 = function (name, color) {
  36603. var temp = new Array();
  36604. color.toArray(temp);
  36605. this.addUniform(name, temp);
  36606. };
  36607. /**
  36608. * Adds a vec4 to the uniform buffer.
  36609. * @param name Name of the uniform, as used in the uniform block in the shader.
  36610. * @param color Define the rgb components from a Color
  36611. * @param alpha Define the a component of the vec4
  36612. */
  36613. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36614. var temp = new Array();
  36615. color.toArray(temp);
  36616. temp.push(alpha);
  36617. this.addUniform(name, temp);
  36618. };
  36619. /**
  36620. * Adds a vec3 to the uniform buffer.
  36621. * @param name Name of the uniform, as used in the uniform block in the shader.
  36622. * @param vector Define the vec3 components from a Vector
  36623. */
  36624. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36625. var temp = new Array();
  36626. vector.toArray(temp);
  36627. this.addUniform(name, temp);
  36628. };
  36629. /**
  36630. * Adds a Matrix 3x3 to the uniform buffer.
  36631. * @param name Name of the uniform, as used in the uniform block in the shader.
  36632. */
  36633. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36634. this.addUniform(name, 12);
  36635. };
  36636. /**
  36637. * Adds a Matrix 2x2 to the uniform buffer.
  36638. * @param name Name of the uniform, as used in the uniform block in the shader.
  36639. */
  36640. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36641. this.addUniform(name, 8);
  36642. };
  36643. /**
  36644. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36645. */
  36646. UniformBuffer.prototype.create = function () {
  36647. if (this._noUBO) {
  36648. return;
  36649. }
  36650. if (this._buffer) {
  36651. return; // nothing to do
  36652. }
  36653. // See spec, alignment must be filled as a vec4
  36654. this._fillAlignment(4);
  36655. this._bufferData = new Float32Array(this._data);
  36656. this._rebuild();
  36657. this._needSync = true;
  36658. };
  36659. /** @hidden */
  36660. UniformBuffer.prototype._rebuild = function () {
  36661. if (this._noUBO) {
  36662. return;
  36663. }
  36664. if (this._dynamic) {
  36665. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36666. }
  36667. else {
  36668. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36669. }
  36670. };
  36671. /**
  36672. * Updates the WebGL Uniform Buffer on the GPU.
  36673. * If the `dynamic` flag is set to true, no cache comparison is done.
  36674. * Otherwise, the buffer will be updated only if the cache differs.
  36675. */
  36676. UniformBuffer.prototype.update = function () {
  36677. if (!this._buffer) {
  36678. this.create();
  36679. return;
  36680. }
  36681. if (!this._dynamic && !this._needSync) {
  36682. return;
  36683. }
  36684. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36685. this._needSync = false;
  36686. };
  36687. /**
  36688. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36689. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36690. * @param data Define the flattened data
  36691. * @param size Define the size of the data.
  36692. */
  36693. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36694. var location = this._uniformLocations[uniformName];
  36695. if (location === undefined) {
  36696. if (this._buffer) {
  36697. // Cannot add an uniform if the buffer is already created
  36698. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36699. return;
  36700. }
  36701. this.addUniform(uniformName, size);
  36702. location = this._uniformLocations[uniformName];
  36703. }
  36704. if (!this._buffer) {
  36705. this.create();
  36706. }
  36707. if (!this._dynamic) {
  36708. // Cache for static uniform buffers
  36709. var changed = false;
  36710. for (var i = 0; i < size; i++) {
  36711. if (this._bufferData[location + i] !== data[i]) {
  36712. changed = true;
  36713. this._bufferData[location + i] = data[i];
  36714. }
  36715. }
  36716. this._needSync = this._needSync || changed;
  36717. }
  36718. else {
  36719. // No cache for dynamic
  36720. for (var i = 0; i < size; i++) {
  36721. this._bufferData[location + i] = data[i];
  36722. }
  36723. }
  36724. };
  36725. // Update methods
  36726. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36727. // To match std140, matrix must be realigned
  36728. for (var i = 0; i < 3; i++) {
  36729. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36730. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36731. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36732. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36733. }
  36734. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36735. };
  36736. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36737. this._currentEffect.setMatrix3x3(name, matrix);
  36738. };
  36739. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36740. this._currentEffect.setMatrix2x2(name, matrix);
  36741. };
  36742. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36743. // To match std140, matrix must be realigned
  36744. for (var i = 0; i < 2; i++) {
  36745. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36746. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36747. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36748. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36749. }
  36750. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36751. };
  36752. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36753. this._currentEffect.setFloat(name, x);
  36754. };
  36755. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36756. UniformBuffer._tempBuffer[0] = x;
  36757. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36758. };
  36759. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36760. if (suffix === void 0) { suffix = ""; }
  36761. this._currentEffect.setFloat2(name + suffix, x, y);
  36762. };
  36763. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36764. if (suffix === void 0) { suffix = ""; }
  36765. UniformBuffer._tempBuffer[0] = x;
  36766. UniformBuffer._tempBuffer[1] = y;
  36767. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36768. };
  36769. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36770. if (suffix === void 0) { suffix = ""; }
  36771. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36772. };
  36773. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36774. if (suffix === void 0) { suffix = ""; }
  36775. UniformBuffer._tempBuffer[0] = x;
  36776. UniformBuffer._tempBuffer[1] = y;
  36777. UniformBuffer._tempBuffer[2] = z;
  36778. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36779. };
  36780. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36781. if (suffix === void 0) { suffix = ""; }
  36782. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36783. };
  36784. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36785. if (suffix === void 0) { suffix = ""; }
  36786. UniformBuffer._tempBuffer[0] = x;
  36787. UniformBuffer._tempBuffer[1] = y;
  36788. UniformBuffer._tempBuffer[2] = z;
  36789. UniformBuffer._tempBuffer[3] = w;
  36790. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36791. };
  36792. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36793. this._currentEffect.setMatrix(name, mat);
  36794. };
  36795. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36796. this.updateUniform(name, mat.toArray(), 16);
  36797. };
  36798. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36799. this._currentEffect.setVector3(name, vector);
  36800. };
  36801. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36802. vector.toArray(UniformBuffer._tempBuffer);
  36803. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36804. };
  36805. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36806. this._currentEffect.setVector4(name, vector);
  36807. };
  36808. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36809. vector.toArray(UniformBuffer._tempBuffer);
  36810. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36811. };
  36812. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36813. if (suffix === void 0) { suffix = ""; }
  36814. this._currentEffect.setColor3(name + suffix, color);
  36815. };
  36816. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36817. if (suffix === void 0) { suffix = ""; }
  36818. color.toArray(UniformBuffer._tempBuffer);
  36819. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36820. };
  36821. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36822. if (suffix === void 0) { suffix = ""; }
  36823. this._currentEffect.setColor4(name + suffix, color, alpha);
  36824. };
  36825. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36826. if (suffix === void 0) { suffix = ""; }
  36827. color.toArray(UniformBuffer._tempBuffer);
  36828. UniformBuffer._tempBuffer[3] = alpha;
  36829. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36830. };
  36831. /**
  36832. * Sets a sampler uniform on the effect.
  36833. * @param name Define the name of the sampler.
  36834. * @param texture Define the texture to set in the sampler
  36835. */
  36836. UniformBuffer.prototype.setTexture = function (name, texture) {
  36837. this._currentEffect.setTexture(name, texture);
  36838. };
  36839. /**
  36840. * Directly updates the value of the uniform in the cache AND on the GPU.
  36841. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36842. * @param data Define the flattened data
  36843. */
  36844. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36845. this.updateUniform(uniformName, data, data.length);
  36846. this.update();
  36847. };
  36848. /**
  36849. * Binds this uniform buffer to an effect.
  36850. * @param effect Define the effect to bind the buffer to
  36851. * @param name Name of the uniform block in the shader.
  36852. */
  36853. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36854. this._currentEffect = effect;
  36855. if (this._noUBO || !this._buffer) {
  36856. return;
  36857. }
  36858. effect.bindUniformBuffer(this._buffer, name);
  36859. };
  36860. /**
  36861. * Disposes the uniform buffer.
  36862. */
  36863. UniformBuffer.prototype.dispose = function () {
  36864. if (this._noUBO) {
  36865. return;
  36866. }
  36867. var index = this._engine._uniformBuffers.indexOf(this);
  36868. if (index !== -1) {
  36869. this._engine._uniformBuffers.splice(index, 1);
  36870. }
  36871. if (!this._buffer) {
  36872. return;
  36873. }
  36874. if (this._engine._releaseBuffer(this._buffer)) {
  36875. this._buffer = null;
  36876. }
  36877. };
  36878. // Pool for avoiding memory leaks
  36879. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36880. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36881. return UniformBuffer;
  36882. }());
  36883. BABYLON.UniformBuffer = UniformBuffer;
  36884. })(BABYLON || (BABYLON = {}));
  36885. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36886. var BABYLON;
  36887. (function (BABYLON) {
  36888. /**
  36889. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36890. */
  36891. var VertexData = /** @class */ (function () {
  36892. function VertexData() {
  36893. }
  36894. /**
  36895. * Uses the passed data array to set the set the values for the specified kind of data
  36896. * @param data a linear array of floating numbers
  36897. * @param kind the type of data that is being set, eg positions, colors etc
  36898. */
  36899. VertexData.prototype.set = function (data, kind) {
  36900. switch (kind) {
  36901. case BABYLON.VertexBuffer.PositionKind:
  36902. this.positions = data;
  36903. break;
  36904. case BABYLON.VertexBuffer.NormalKind:
  36905. this.normals = data;
  36906. break;
  36907. case BABYLON.VertexBuffer.TangentKind:
  36908. this.tangents = data;
  36909. break;
  36910. case BABYLON.VertexBuffer.UVKind:
  36911. this.uvs = data;
  36912. break;
  36913. case BABYLON.VertexBuffer.UV2Kind:
  36914. this.uvs2 = data;
  36915. break;
  36916. case BABYLON.VertexBuffer.UV3Kind:
  36917. this.uvs3 = data;
  36918. break;
  36919. case BABYLON.VertexBuffer.UV4Kind:
  36920. this.uvs4 = data;
  36921. break;
  36922. case BABYLON.VertexBuffer.UV5Kind:
  36923. this.uvs5 = data;
  36924. break;
  36925. case BABYLON.VertexBuffer.UV6Kind:
  36926. this.uvs6 = data;
  36927. break;
  36928. case BABYLON.VertexBuffer.ColorKind:
  36929. this.colors = data;
  36930. break;
  36931. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36932. this.matricesIndices = data;
  36933. break;
  36934. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36935. this.matricesWeights = data;
  36936. break;
  36937. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36938. this.matricesIndicesExtra = data;
  36939. break;
  36940. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36941. this.matricesWeightsExtra = data;
  36942. break;
  36943. }
  36944. };
  36945. /**
  36946. * Associates the vertexData to the passed Mesh.
  36947. * Sets it as updatable or not (default `false`)
  36948. * @param mesh the mesh the vertexData is applied to
  36949. * @param updatable when used and having the value true allows new data to update the vertexData
  36950. * @returns the VertexData
  36951. */
  36952. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36953. this._applyTo(mesh, updatable);
  36954. return this;
  36955. };
  36956. /**
  36957. * Associates the vertexData to the passed Geometry.
  36958. * Sets it as updatable or not (default `false`)
  36959. * @param geometry the geometry the vertexData is applied to
  36960. * @param updatable when used and having the value true allows new data to update the vertexData
  36961. * @returns VertexData
  36962. */
  36963. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36964. this._applyTo(geometry, updatable);
  36965. return this;
  36966. };
  36967. /**
  36968. * Updates the associated mesh
  36969. * @param mesh the mesh to be updated
  36970. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36971. * @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
  36972. * @returns VertexData
  36973. */
  36974. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36975. this._update(mesh);
  36976. return this;
  36977. };
  36978. /**
  36979. * Updates the associated geometry
  36980. * @param geometry the geometry to be updated
  36981. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36982. * @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
  36983. * @returns VertexData.
  36984. */
  36985. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36986. this._update(geometry);
  36987. return this;
  36988. };
  36989. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36990. if (updatable === void 0) { updatable = false; }
  36991. if (this.positions) {
  36992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36993. }
  36994. if (this.normals) {
  36995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36996. }
  36997. if (this.tangents) {
  36998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36999. }
  37000. if (this.uvs) {
  37001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37002. }
  37003. if (this.uvs2) {
  37004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37005. }
  37006. if (this.uvs3) {
  37007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37008. }
  37009. if (this.uvs4) {
  37010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37011. }
  37012. if (this.uvs5) {
  37013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37014. }
  37015. if (this.uvs6) {
  37016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37017. }
  37018. if (this.colors) {
  37019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37020. }
  37021. if (this.matricesIndices) {
  37022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37023. }
  37024. if (this.matricesWeights) {
  37025. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37026. }
  37027. if (this.matricesIndicesExtra) {
  37028. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37029. }
  37030. if (this.matricesWeightsExtra) {
  37031. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37032. }
  37033. if (this.indices) {
  37034. meshOrGeometry.setIndices(this.indices, null, updatable);
  37035. }
  37036. else {
  37037. meshOrGeometry.setIndices([], null);
  37038. }
  37039. return this;
  37040. };
  37041. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37042. if (this.positions) {
  37043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37044. }
  37045. if (this.normals) {
  37046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37047. }
  37048. if (this.tangents) {
  37049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37050. }
  37051. if (this.uvs) {
  37052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37053. }
  37054. if (this.uvs2) {
  37055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37056. }
  37057. if (this.uvs3) {
  37058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37059. }
  37060. if (this.uvs4) {
  37061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37062. }
  37063. if (this.uvs5) {
  37064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37065. }
  37066. if (this.uvs6) {
  37067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37068. }
  37069. if (this.colors) {
  37070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37071. }
  37072. if (this.matricesIndices) {
  37073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37074. }
  37075. if (this.matricesWeights) {
  37076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37077. }
  37078. if (this.matricesIndicesExtra) {
  37079. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37080. }
  37081. if (this.matricesWeightsExtra) {
  37082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37083. }
  37084. if (this.indices) {
  37085. meshOrGeometry.setIndices(this.indices, null);
  37086. }
  37087. return this;
  37088. };
  37089. /**
  37090. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37091. * @param matrix the transforming matrix
  37092. * @returns the VertexData
  37093. */
  37094. VertexData.prototype.transform = function (matrix) {
  37095. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37096. var transformed = BABYLON.Vector3.Zero();
  37097. var index;
  37098. if (this.positions) {
  37099. var position = BABYLON.Vector3.Zero();
  37100. for (index = 0; index < this.positions.length; index += 3) {
  37101. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37102. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37103. this.positions[index] = transformed.x;
  37104. this.positions[index + 1] = transformed.y;
  37105. this.positions[index + 2] = transformed.z;
  37106. }
  37107. }
  37108. if (this.normals) {
  37109. var normal = BABYLON.Vector3.Zero();
  37110. for (index = 0; index < this.normals.length; index += 3) {
  37111. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37112. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37113. this.normals[index] = transformed.x;
  37114. this.normals[index + 1] = transformed.y;
  37115. this.normals[index + 2] = transformed.z;
  37116. }
  37117. }
  37118. if (this.tangents) {
  37119. var tangent = BABYLON.Vector4.Zero();
  37120. var tangentTransformed = BABYLON.Vector4.Zero();
  37121. for (index = 0; index < this.tangents.length; index += 4) {
  37122. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37123. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37124. this.tangents[index] = tangentTransformed.x;
  37125. this.tangents[index + 1] = tangentTransformed.y;
  37126. this.tangents[index + 2] = tangentTransformed.z;
  37127. this.tangents[index + 3] = tangentTransformed.w;
  37128. }
  37129. }
  37130. if (flip && this.indices) {
  37131. for (index = 0; index < this.indices.length; index += 3) {
  37132. var tmp = this.indices[index + 1];
  37133. this.indices[index + 1] = this.indices[index + 2];
  37134. this.indices[index + 2] = tmp;
  37135. }
  37136. }
  37137. return this;
  37138. };
  37139. /**
  37140. * Merges the passed VertexData into the current one
  37141. * @param other the VertexData to be merged into the current one
  37142. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37143. * @returns the modified VertexData
  37144. */
  37145. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37146. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37147. this._validate();
  37148. other._validate();
  37149. if (!this.normals !== !other.normals ||
  37150. !this.tangents !== !other.tangents ||
  37151. !this.uvs !== !other.uvs ||
  37152. !this.uvs2 !== !other.uvs2 ||
  37153. !this.uvs3 !== !other.uvs3 ||
  37154. !this.uvs4 !== !other.uvs4 ||
  37155. !this.uvs5 !== !other.uvs5 ||
  37156. !this.uvs6 !== !other.uvs6 ||
  37157. !this.colors !== !other.colors ||
  37158. !this.matricesIndices !== !other.matricesIndices ||
  37159. !this.matricesWeights !== !other.matricesWeights ||
  37160. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37161. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37162. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37163. }
  37164. if (other.indices) {
  37165. if (!this.indices) {
  37166. this.indices = [];
  37167. }
  37168. var offset = this.positions ? this.positions.length / 3 : 0;
  37169. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37170. if (isSrcTypedArray) {
  37171. var len = this.indices.length + other.indices.length;
  37172. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37173. temp.set(this.indices);
  37174. var decal = this.indices.length;
  37175. for (var index = 0; index < other.indices.length; index++) {
  37176. temp[decal + index] = other.indices[index] + offset;
  37177. }
  37178. this.indices = temp;
  37179. }
  37180. else {
  37181. for (var index = 0; index < other.indices.length; index++) {
  37182. this.indices.push(other.indices[index] + offset);
  37183. }
  37184. }
  37185. }
  37186. this.positions = this._mergeElement(this.positions, other.positions);
  37187. this.normals = this._mergeElement(this.normals, other.normals);
  37188. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37189. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37190. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37191. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37192. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37193. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37194. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37195. this.colors = this._mergeElement(this.colors, other.colors);
  37196. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37197. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37198. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37199. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37200. return this;
  37201. };
  37202. VertexData.prototype._mergeElement = function (source, other) {
  37203. if (!source) {
  37204. return other;
  37205. }
  37206. if (!other) {
  37207. return source;
  37208. }
  37209. var len = other.length + source.length;
  37210. var isSrcTypedArray = source instanceof Float32Array;
  37211. var isOthTypedArray = other instanceof Float32Array;
  37212. // use non-loop method when the source is Float32Array
  37213. if (isSrcTypedArray) {
  37214. var ret32 = new Float32Array(len);
  37215. ret32.set(source);
  37216. ret32.set(other, source.length);
  37217. return ret32;
  37218. // source is number[], when other is also use concat
  37219. }
  37220. else if (!isOthTypedArray) {
  37221. return source.concat(other);
  37222. // source is a number[], but other is a Float32Array, loop required
  37223. }
  37224. else {
  37225. var ret = source.slice(0); // copy source to a separate array
  37226. for (var i = 0, len = other.length; i < len; i++) {
  37227. ret.push(other[i]);
  37228. }
  37229. return ret;
  37230. }
  37231. };
  37232. VertexData.prototype._validate = function () {
  37233. if (!this.positions) {
  37234. throw new Error("Positions are required");
  37235. }
  37236. var getElementCount = function (kind, values) {
  37237. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37238. if ((values.length % stride) !== 0) {
  37239. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37240. }
  37241. return values.length / stride;
  37242. };
  37243. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37244. var validateElementCount = function (kind, values) {
  37245. var elementCount = getElementCount(kind, values);
  37246. if (elementCount !== positionsElementCount) {
  37247. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37248. }
  37249. };
  37250. if (this.normals)
  37251. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37252. if (this.tangents)
  37253. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37254. if (this.uvs)
  37255. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37256. if (this.uvs2)
  37257. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37258. if (this.uvs3)
  37259. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37260. if (this.uvs4)
  37261. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37262. if (this.uvs5)
  37263. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37264. if (this.uvs6)
  37265. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37266. if (this.colors)
  37267. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37268. if (this.matricesIndices)
  37269. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37270. if (this.matricesWeights)
  37271. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37272. if (this.matricesIndicesExtra)
  37273. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37274. if (this.matricesWeightsExtra)
  37275. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37276. };
  37277. /**
  37278. * Serializes the VertexData
  37279. * @returns a serialized object
  37280. */
  37281. VertexData.prototype.serialize = function () {
  37282. var serializationObject = this.serialize();
  37283. if (this.positions) {
  37284. serializationObject.positions = this.positions;
  37285. }
  37286. if (this.normals) {
  37287. serializationObject.normals = this.normals;
  37288. }
  37289. if (this.tangents) {
  37290. serializationObject.tangents = this.tangents;
  37291. }
  37292. if (this.uvs) {
  37293. serializationObject.uvs = this.uvs;
  37294. }
  37295. if (this.uvs2) {
  37296. serializationObject.uvs2 = this.uvs2;
  37297. }
  37298. if (this.uvs3) {
  37299. serializationObject.uvs3 = this.uvs3;
  37300. }
  37301. if (this.uvs4) {
  37302. serializationObject.uvs4 = this.uvs4;
  37303. }
  37304. if (this.uvs5) {
  37305. serializationObject.uvs5 = this.uvs5;
  37306. }
  37307. if (this.uvs6) {
  37308. serializationObject.uvs6 = this.uvs6;
  37309. }
  37310. if (this.colors) {
  37311. serializationObject.colors = this.colors;
  37312. }
  37313. if (this.matricesIndices) {
  37314. serializationObject.matricesIndices = this.matricesIndices;
  37315. serializationObject.matricesIndices._isExpanded = true;
  37316. }
  37317. if (this.matricesWeights) {
  37318. serializationObject.matricesWeights = this.matricesWeights;
  37319. }
  37320. if (this.matricesIndicesExtra) {
  37321. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37322. serializationObject.matricesIndicesExtra._isExpanded = true;
  37323. }
  37324. if (this.matricesWeightsExtra) {
  37325. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37326. }
  37327. serializationObject.indices = this.indices;
  37328. return serializationObject;
  37329. };
  37330. // Statics
  37331. /**
  37332. * Extracts the vertexData from a mesh
  37333. * @param mesh the mesh from which to extract the VertexData
  37334. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37335. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37336. * @returns the object VertexData associated to the passed mesh
  37337. */
  37338. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37339. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37340. };
  37341. /**
  37342. * Extracts the vertexData from the geometry
  37343. * @param geometry the geometry from which to extract the VertexData
  37344. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37345. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37346. * @returns the object VertexData associated to the passed mesh
  37347. */
  37348. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37349. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37350. };
  37351. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37352. var result = new VertexData();
  37353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37354. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37355. }
  37356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37357. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37358. }
  37359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37360. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37361. }
  37362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37363. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37364. }
  37365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37366. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37367. }
  37368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37369. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37370. }
  37371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37372. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37373. }
  37374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37375. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37376. }
  37377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37378. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37379. }
  37380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37381. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37382. }
  37383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37384. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37385. }
  37386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37387. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37388. }
  37389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37390. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37391. }
  37392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37393. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37394. }
  37395. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37396. return result;
  37397. };
  37398. /**
  37399. * Creates the VertexData for a Ribbon
  37400. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37401. * * pathArray array of paths, each of which an array of successive Vector3
  37402. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37403. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37404. * * 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
  37405. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37406. * * 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)
  37407. * * 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)
  37408. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37409. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37410. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37411. * @returns the VertexData of the ribbon
  37412. */
  37413. VertexData.CreateRibbon = function (options) {
  37414. var pathArray = options.pathArray;
  37415. var closeArray = options.closeArray || false;
  37416. var closePath = options.closePath || false;
  37417. var invertUV = options.invertUV || false;
  37418. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37419. var offset = options.offset || defaultOffset;
  37420. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37421. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37422. var customUV = options.uvs;
  37423. var customColors = options.colors;
  37424. var positions = [];
  37425. var indices = [];
  37426. var normals = [];
  37427. var uvs = [];
  37428. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37429. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37430. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37431. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37432. var minlg; // minimal length among all paths from pathArray
  37433. var lg = []; // array of path lengths : nb of vertex per path
  37434. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37435. var p; // path iterator
  37436. var i; // point iterator
  37437. var j; // point iterator
  37438. // if single path in pathArray
  37439. if (pathArray.length < 2) {
  37440. var ar1 = [];
  37441. var ar2 = [];
  37442. for (i = 0; i < pathArray[0].length - offset; i++) {
  37443. ar1.push(pathArray[0][i]);
  37444. ar2.push(pathArray[0][i + offset]);
  37445. }
  37446. pathArray = [ar1, ar2];
  37447. }
  37448. // positions and horizontal distances (u)
  37449. var idc = 0;
  37450. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37451. var path;
  37452. var l;
  37453. minlg = pathArray[0].length;
  37454. var vectlg;
  37455. var dist;
  37456. for (p = 0; p < pathArray.length; p++) {
  37457. uTotalDistance[p] = 0;
  37458. us[p] = [0];
  37459. path = pathArray[p];
  37460. l = path.length;
  37461. minlg = (minlg < l) ? minlg : l;
  37462. j = 0;
  37463. while (j < l) {
  37464. positions.push(path[j].x, path[j].y, path[j].z);
  37465. if (j > 0) {
  37466. vectlg = path[j].subtract(path[j - 1]).length();
  37467. dist = vectlg + uTotalDistance[p];
  37468. us[p].push(dist);
  37469. uTotalDistance[p] = dist;
  37470. }
  37471. j++;
  37472. }
  37473. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37474. j--;
  37475. positions.push(path[0].x, path[0].y, path[0].z);
  37476. vectlg = path[j].subtract(path[0]).length();
  37477. dist = vectlg + uTotalDistance[p];
  37478. us[p].push(dist);
  37479. uTotalDistance[p] = dist;
  37480. }
  37481. lg[p] = l + closePathCorr;
  37482. idx[p] = idc;
  37483. idc += (l + closePathCorr);
  37484. }
  37485. // vertical distances (v)
  37486. var path1;
  37487. var path2;
  37488. var vertex1 = null;
  37489. var vertex2 = null;
  37490. for (i = 0; i < minlg + closePathCorr; i++) {
  37491. vTotalDistance[i] = 0;
  37492. vs[i] = [0];
  37493. for (p = 0; p < pathArray.length - 1; p++) {
  37494. path1 = pathArray[p];
  37495. path2 = pathArray[p + 1];
  37496. if (i === minlg) { // closePath
  37497. vertex1 = path1[0];
  37498. vertex2 = path2[0];
  37499. }
  37500. else {
  37501. vertex1 = path1[i];
  37502. vertex2 = path2[i];
  37503. }
  37504. vectlg = vertex2.subtract(vertex1).length();
  37505. dist = vectlg + vTotalDistance[i];
  37506. vs[i].push(dist);
  37507. vTotalDistance[i] = dist;
  37508. }
  37509. if (closeArray && vertex2 && vertex1) {
  37510. path1 = pathArray[p];
  37511. path2 = pathArray[0];
  37512. if (i === minlg) { // closePath
  37513. vertex2 = path2[0];
  37514. }
  37515. vectlg = vertex2.subtract(vertex1).length();
  37516. dist = vectlg + vTotalDistance[i];
  37517. vTotalDistance[i] = dist;
  37518. }
  37519. }
  37520. // uvs
  37521. var u;
  37522. var v;
  37523. if (customUV) {
  37524. for (p = 0; p < customUV.length; p++) {
  37525. uvs.push(customUV[p].x, customUV[p].y);
  37526. }
  37527. }
  37528. else {
  37529. for (p = 0; p < pathArray.length; p++) {
  37530. for (i = 0; i < minlg + closePathCorr; i++) {
  37531. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37532. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37533. if (invertUV) {
  37534. uvs.push(v, u);
  37535. }
  37536. else {
  37537. uvs.push(u, v);
  37538. }
  37539. }
  37540. }
  37541. }
  37542. // indices
  37543. p = 0; // path index
  37544. var pi = 0; // positions array index
  37545. var l1 = lg[p] - 1; // path1 length
  37546. var l2 = lg[p + 1] - 1; // path2 length
  37547. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37548. var shft = idx[1] - idx[0]; // shift
  37549. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37550. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37551. // 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
  37552. indices.push(pi, pi + shft, pi + 1);
  37553. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37554. pi += 1;
  37555. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37556. p++;
  37557. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37558. shft = idx[0] - idx[p];
  37559. l1 = lg[p] - 1;
  37560. l2 = lg[0] - 1;
  37561. }
  37562. else {
  37563. shft = idx[p + 1] - idx[p];
  37564. l1 = lg[p] - 1;
  37565. l2 = lg[p + 1] - 1;
  37566. }
  37567. pi = idx[p];
  37568. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37569. }
  37570. }
  37571. // normals
  37572. VertexData.ComputeNormals(positions, indices, normals);
  37573. if (closePath) { // update both the first and last vertex normals to their average value
  37574. var indexFirst = 0;
  37575. var indexLast = 0;
  37576. for (p = 0; p < pathArray.length; p++) {
  37577. indexFirst = idx[p] * 3;
  37578. if (p + 1 < pathArray.length) {
  37579. indexLast = (idx[p + 1] - 1) * 3;
  37580. }
  37581. else {
  37582. indexLast = normals.length - 3;
  37583. }
  37584. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37585. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37586. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37587. normals[indexLast] = normals[indexFirst];
  37588. normals[indexLast + 1] = normals[indexFirst + 1];
  37589. normals[indexLast + 2] = normals[indexFirst + 2];
  37590. }
  37591. }
  37592. // sides
  37593. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37594. // Colors
  37595. var colors = null;
  37596. if (customColors) {
  37597. colors = new Float32Array(customColors.length * 4);
  37598. for (var c = 0; c < customColors.length; c++) {
  37599. colors[c * 4] = customColors[c].r;
  37600. colors[c * 4 + 1] = customColors[c].g;
  37601. colors[c * 4 + 2] = customColors[c].b;
  37602. colors[c * 4 + 3] = customColors[c].a;
  37603. }
  37604. }
  37605. // Result
  37606. var vertexData = new VertexData();
  37607. var positions32 = new Float32Array(positions);
  37608. var normals32 = new Float32Array(normals);
  37609. var uvs32 = new Float32Array(uvs);
  37610. vertexData.indices = indices;
  37611. vertexData.positions = positions32;
  37612. vertexData.normals = normals32;
  37613. vertexData.uvs = uvs32;
  37614. if (colors) {
  37615. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37616. }
  37617. if (closePath) {
  37618. vertexData._idx = idx;
  37619. }
  37620. return vertexData;
  37621. };
  37622. /**
  37623. * Creates the VertexData for a box
  37624. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37625. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37626. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37627. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37628. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37629. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37630. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37631. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37632. * * 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)
  37633. * * 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)
  37634. * @returns the VertexData of the box
  37635. */
  37636. VertexData.CreateBox = function (options) {
  37637. var normalsSource = [
  37638. new BABYLON.Vector3(0, 0, 1),
  37639. new BABYLON.Vector3(0, 0, -1),
  37640. new BABYLON.Vector3(1, 0, 0),
  37641. new BABYLON.Vector3(-1, 0, 0),
  37642. new BABYLON.Vector3(0, 1, 0),
  37643. new BABYLON.Vector3(0, -1, 0)
  37644. ];
  37645. var indices = [];
  37646. var positions = [];
  37647. var normals = [];
  37648. var uvs = [];
  37649. var width = options.width || options.size || 1;
  37650. var height = options.height || options.size || 1;
  37651. var depth = options.depth || options.size || 1;
  37652. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37653. var faceUV = options.faceUV || new Array(6);
  37654. var faceColors = options.faceColors;
  37655. var colors = [];
  37656. // default face colors and UV if undefined
  37657. for (var f = 0; f < 6; f++) {
  37658. if (faceUV[f] === undefined) {
  37659. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37660. }
  37661. if (faceColors && faceColors[f] === undefined) {
  37662. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37663. }
  37664. }
  37665. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37666. // Create each face in turn.
  37667. for (var index = 0; index < normalsSource.length; index++) {
  37668. var normal = normalsSource[index];
  37669. // Get two vectors perpendicular to the face normal and to each other.
  37670. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37671. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37672. // Six indices (two triangles) per face.
  37673. var verticesLength = positions.length / 3;
  37674. indices.push(verticesLength);
  37675. indices.push(verticesLength + 1);
  37676. indices.push(verticesLength + 2);
  37677. indices.push(verticesLength);
  37678. indices.push(verticesLength + 2);
  37679. indices.push(verticesLength + 3);
  37680. // Four vertices per face.
  37681. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37682. positions.push(vertex.x, vertex.y, vertex.z);
  37683. normals.push(normal.x, normal.y, normal.z);
  37684. uvs.push(faceUV[index].z, faceUV[index].w);
  37685. if (faceColors) {
  37686. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37687. }
  37688. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37689. positions.push(vertex.x, vertex.y, vertex.z);
  37690. normals.push(normal.x, normal.y, normal.z);
  37691. uvs.push(faceUV[index].x, faceUV[index].w);
  37692. if (faceColors) {
  37693. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37694. }
  37695. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37696. positions.push(vertex.x, vertex.y, vertex.z);
  37697. normals.push(normal.x, normal.y, normal.z);
  37698. uvs.push(faceUV[index].x, faceUV[index].y);
  37699. if (faceColors) {
  37700. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37701. }
  37702. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37703. positions.push(vertex.x, vertex.y, vertex.z);
  37704. normals.push(normal.x, normal.y, normal.z);
  37705. uvs.push(faceUV[index].z, faceUV[index].y);
  37706. if (faceColors) {
  37707. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37708. }
  37709. }
  37710. // sides
  37711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37712. // Result
  37713. var vertexData = new VertexData();
  37714. vertexData.indices = indices;
  37715. vertexData.positions = positions;
  37716. vertexData.normals = normals;
  37717. vertexData.uvs = uvs;
  37718. if (faceColors) {
  37719. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37720. vertexData.colors = totalColors;
  37721. }
  37722. return vertexData;
  37723. };
  37724. /**
  37725. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37726. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37727. * * segments sets the number of horizontal strips optional, default 32
  37728. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37729. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37730. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37731. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37732. * * 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
  37733. * * 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
  37734. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37735. * * 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)
  37736. * * 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)
  37737. * @returns the VertexData of the ellipsoid
  37738. */
  37739. VertexData.CreateSphere = function (options) {
  37740. var segments = options.segments || 32;
  37741. var diameterX = options.diameterX || options.diameter || 1;
  37742. var diameterY = options.diameterY || options.diameter || 1;
  37743. var diameterZ = options.diameterZ || options.diameter || 1;
  37744. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37745. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37747. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37748. var totalZRotationSteps = 2 + segments;
  37749. var totalYRotationSteps = 2 * totalZRotationSteps;
  37750. var indices = [];
  37751. var positions = [];
  37752. var normals = [];
  37753. var uvs = [];
  37754. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37755. var normalizedZ = zRotationStep / totalZRotationSteps;
  37756. var angleZ = normalizedZ * Math.PI * slice;
  37757. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37758. var normalizedY = yRotationStep / totalYRotationSteps;
  37759. var angleY = normalizedY * Math.PI * 2 * arc;
  37760. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37761. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37762. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37763. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37764. var vertex = complete.multiply(radius);
  37765. var normal = complete.divide(radius).normalize();
  37766. positions.push(vertex.x, vertex.y, vertex.z);
  37767. normals.push(normal.x, normal.y, normal.z);
  37768. uvs.push(normalizedY, normalizedZ);
  37769. }
  37770. if (zRotationStep > 0) {
  37771. var verticesCount = positions.length / 3;
  37772. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37773. indices.push((firstIndex));
  37774. indices.push((firstIndex + 1));
  37775. indices.push(firstIndex + totalYRotationSteps + 1);
  37776. indices.push((firstIndex + totalYRotationSteps + 1));
  37777. indices.push((firstIndex + 1));
  37778. indices.push((firstIndex + totalYRotationSteps + 2));
  37779. }
  37780. }
  37781. }
  37782. // Sides
  37783. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37784. // Result
  37785. var vertexData = new VertexData();
  37786. vertexData.indices = indices;
  37787. vertexData.positions = positions;
  37788. vertexData.normals = normals;
  37789. vertexData.uvs = uvs;
  37790. return vertexData;
  37791. };
  37792. /**
  37793. * Creates the VertexData for a cylinder, cone or prism
  37794. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37795. * * height sets the height (y direction) of the cylinder, optional, default 2
  37796. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37797. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37798. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37799. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37800. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37801. * * 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
  37802. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37803. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37804. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37805. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37806. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37807. * * 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)
  37808. * * 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)
  37809. * @returns the VertexData of the cylinder, cone or prism
  37810. */
  37811. VertexData.CreateCylinder = function (options) {
  37812. var height = options.height || 2;
  37813. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37814. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37815. var tessellation = options.tessellation || 24;
  37816. var subdivisions = options.subdivisions || 1;
  37817. var hasRings = options.hasRings ? true : false;
  37818. var enclose = options.enclose ? true : false;
  37819. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37820. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37821. var faceUV = options.faceUV || new Array(3);
  37822. var faceColors = options.faceColors;
  37823. // default face colors and UV if undefined
  37824. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37825. var ringNb = (hasRings) ? subdivisions : 1;
  37826. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37827. var f;
  37828. for (f = 0; f < surfaceNb; f++) {
  37829. if (faceColors && faceColors[f] === undefined) {
  37830. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37831. }
  37832. }
  37833. for (f = 0; f < surfaceNb; f++) {
  37834. if (faceUV && faceUV[f] === undefined) {
  37835. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37836. }
  37837. }
  37838. var indices = new Array();
  37839. var positions = new Array();
  37840. var normals = new Array();
  37841. var uvs = new Array();
  37842. var colors = new Array();
  37843. var angle_step = Math.PI * 2 * arc / tessellation;
  37844. var angle;
  37845. var h;
  37846. var radius;
  37847. var tan = (diameterBottom - diameterTop) / 2 / height;
  37848. var ringVertex = BABYLON.Vector3.Zero();
  37849. var ringNormal = BABYLON.Vector3.Zero();
  37850. var ringFirstVertex = BABYLON.Vector3.Zero();
  37851. var ringFirstNormal = BABYLON.Vector3.Zero();
  37852. var quadNormal = BABYLON.Vector3.Zero();
  37853. var Y = BABYLON.Axis.Y;
  37854. // positions, normals, uvs
  37855. var i;
  37856. var j;
  37857. var r;
  37858. var ringIdx = 1;
  37859. var s = 1; // surface index
  37860. var cs = 0;
  37861. var v = 0;
  37862. for (i = 0; i <= subdivisions; i++) {
  37863. h = i / subdivisions;
  37864. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37865. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37866. for (r = 0; r < ringIdx; r++) {
  37867. if (hasRings) {
  37868. s += r;
  37869. }
  37870. if (enclose) {
  37871. s += 2 * r;
  37872. }
  37873. for (j = 0; j <= tessellation; j++) {
  37874. angle = j * angle_step;
  37875. // position
  37876. ringVertex.x = Math.cos(-angle) * radius;
  37877. ringVertex.y = -height / 2 + h * height;
  37878. ringVertex.z = Math.sin(-angle) * radius;
  37879. // normal
  37880. if (diameterTop === 0 && i === subdivisions) {
  37881. // if no top cap, reuse former normals
  37882. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37883. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37884. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37885. }
  37886. else {
  37887. ringNormal.x = ringVertex.x;
  37888. ringNormal.z = ringVertex.z;
  37889. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37890. ringNormal.normalize();
  37891. }
  37892. // keep first ring vertex values for enclose
  37893. if (j === 0) {
  37894. ringFirstVertex.copyFrom(ringVertex);
  37895. ringFirstNormal.copyFrom(ringNormal);
  37896. }
  37897. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37898. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37899. if (hasRings) {
  37900. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37901. }
  37902. else {
  37903. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37904. }
  37905. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37906. if (faceColors) {
  37907. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37908. }
  37909. }
  37910. // if enclose, add four vertices and their dedicated normals
  37911. if (arc !== 1 && enclose) {
  37912. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37913. positions.push(0, ringVertex.y, 0);
  37914. positions.push(0, ringVertex.y, 0);
  37915. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37916. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37917. quadNormal.normalize();
  37918. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37919. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37920. quadNormal.normalize();
  37921. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37922. if (hasRings) {
  37923. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37924. }
  37925. else {
  37926. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37927. }
  37928. uvs.push(faceUV[s + 1].x, v);
  37929. uvs.push(faceUV[s + 1].z, v);
  37930. if (hasRings) {
  37931. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37932. }
  37933. else {
  37934. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37935. }
  37936. uvs.push(faceUV[s + 2].x, v);
  37937. uvs.push(faceUV[s + 2].z, v);
  37938. if (faceColors) {
  37939. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37940. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37941. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37942. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37943. }
  37944. }
  37945. if (cs !== s) {
  37946. cs = s;
  37947. }
  37948. }
  37949. }
  37950. // indices
  37951. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37952. var s;
  37953. i = 0;
  37954. for (s = 0; s < subdivisions; s++) {
  37955. var i0 = 0;
  37956. var i1 = 0;
  37957. var i2 = 0;
  37958. var i3 = 0;
  37959. for (j = 0; j < tessellation; j++) {
  37960. i0 = i * (e + 1) + j;
  37961. i1 = (i + 1) * (e + 1) + j;
  37962. i2 = i * (e + 1) + (j + 1);
  37963. i3 = (i + 1) * (e + 1) + (j + 1);
  37964. indices.push(i0, i1, i2);
  37965. indices.push(i3, i2, i1);
  37966. }
  37967. if (arc !== 1 && enclose) { // if enclose, add two quads
  37968. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37969. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37970. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37971. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37972. }
  37973. i = (hasRings) ? (i + 2) : (i + 1);
  37974. }
  37975. // Caps
  37976. var createCylinderCap = function (isTop) {
  37977. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37978. if (radius === 0) {
  37979. return;
  37980. }
  37981. // Cap positions, normals & uvs
  37982. var angle;
  37983. var circleVector;
  37984. var i;
  37985. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37986. var c = null;
  37987. if (faceColors) {
  37988. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37989. }
  37990. // cap center
  37991. var vbase = positions.length / 3;
  37992. var offset = isTop ? height / 2 : -height / 2;
  37993. var center = new BABYLON.Vector3(0, offset, 0);
  37994. positions.push(center.x, center.y, center.z);
  37995. normals.push(0, isTop ? 1 : -1, 0);
  37996. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37997. if (c) {
  37998. colors.push(c.r, c.g, c.b, c.a);
  37999. }
  38000. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38001. for (i = 0; i <= tessellation; i++) {
  38002. angle = Math.PI * 2 * i * arc / tessellation;
  38003. var cos = Math.cos(-angle);
  38004. var sin = Math.sin(-angle);
  38005. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38006. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38007. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38008. normals.push(0, isTop ? 1 : -1, 0);
  38009. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38010. if (c) {
  38011. colors.push(c.r, c.g, c.b, c.a);
  38012. }
  38013. }
  38014. // Cap indices
  38015. for (i = 0; i < tessellation; i++) {
  38016. if (!isTop) {
  38017. indices.push(vbase);
  38018. indices.push(vbase + (i + 1));
  38019. indices.push(vbase + (i + 2));
  38020. }
  38021. else {
  38022. indices.push(vbase);
  38023. indices.push(vbase + (i + 2));
  38024. indices.push(vbase + (i + 1));
  38025. }
  38026. }
  38027. };
  38028. // add caps to geometry
  38029. createCylinderCap(false);
  38030. createCylinderCap(true);
  38031. // Sides
  38032. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38033. var vertexData = new VertexData();
  38034. vertexData.indices = indices;
  38035. vertexData.positions = positions;
  38036. vertexData.normals = normals;
  38037. vertexData.uvs = uvs;
  38038. if (faceColors) {
  38039. vertexData.colors = colors;
  38040. }
  38041. return vertexData;
  38042. };
  38043. /**
  38044. * Creates the VertexData for a torus
  38045. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38046. * * diameter the diameter of the torus, optional default 1
  38047. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38048. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38049. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38050. * * 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)
  38051. * * 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)
  38052. * @returns the VertexData of the torus
  38053. */
  38054. VertexData.CreateTorus = function (options) {
  38055. var indices = [];
  38056. var positions = [];
  38057. var normals = [];
  38058. var uvs = [];
  38059. var diameter = options.diameter || 1;
  38060. var thickness = options.thickness || 0.5;
  38061. var tessellation = options.tessellation || 16;
  38062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38063. var stride = tessellation + 1;
  38064. for (var i = 0; i <= tessellation; i++) {
  38065. var u = i / tessellation;
  38066. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38067. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38068. for (var j = 0; j <= tessellation; j++) {
  38069. var v = 1 - j / tessellation;
  38070. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38071. var dx = Math.cos(innerAngle);
  38072. var dy = Math.sin(innerAngle);
  38073. // Create a vertex.
  38074. var normal = new BABYLON.Vector3(dx, dy, 0);
  38075. var position = normal.scale(thickness / 2);
  38076. var textureCoordinate = new BABYLON.Vector2(u, v);
  38077. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38078. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38079. positions.push(position.x, position.y, position.z);
  38080. normals.push(normal.x, normal.y, normal.z);
  38081. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38082. // And create indices for two triangles.
  38083. var nextI = (i + 1) % stride;
  38084. var nextJ = (j + 1) % stride;
  38085. indices.push(i * stride + j);
  38086. indices.push(i * stride + nextJ);
  38087. indices.push(nextI * stride + j);
  38088. indices.push(i * stride + nextJ);
  38089. indices.push(nextI * stride + nextJ);
  38090. indices.push(nextI * stride + j);
  38091. }
  38092. }
  38093. // Sides
  38094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38095. // Result
  38096. var vertexData = new VertexData();
  38097. vertexData.indices = indices;
  38098. vertexData.positions = positions;
  38099. vertexData.normals = normals;
  38100. vertexData.uvs = uvs;
  38101. return vertexData;
  38102. };
  38103. /**
  38104. * Creates the VertexData of the LineSystem
  38105. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38106. * - lines an array of lines, each line being an array of successive Vector3
  38107. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38108. * @returns the VertexData of the LineSystem
  38109. */
  38110. VertexData.CreateLineSystem = function (options) {
  38111. var indices = [];
  38112. var positions = [];
  38113. var lines = options.lines;
  38114. var colors = options.colors;
  38115. var vertexColors = [];
  38116. var idx = 0;
  38117. for (var l = 0; l < lines.length; l++) {
  38118. var points = lines[l];
  38119. for (var index = 0; index < points.length; index++) {
  38120. positions.push(points[index].x, points[index].y, points[index].z);
  38121. if (colors) {
  38122. var color = colors[l];
  38123. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38124. }
  38125. if (index > 0) {
  38126. indices.push(idx - 1);
  38127. indices.push(idx);
  38128. }
  38129. idx++;
  38130. }
  38131. }
  38132. var vertexData = new VertexData();
  38133. vertexData.indices = indices;
  38134. vertexData.positions = positions;
  38135. if (colors) {
  38136. vertexData.colors = vertexColors;
  38137. }
  38138. return vertexData;
  38139. };
  38140. /**
  38141. * Create the VertexData for a DashedLines
  38142. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38143. * - points an array successive Vector3
  38144. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38145. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38146. * - dashNb the intended total number of dashes, optional, default 200
  38147. * @returns the VertexData for the DashedLines
  38148. */
  38149. VertexData.CreateDashedLines = function (options) {
  38150. var dashSize = options.dashSize || 3;
  38151. var gapSize = options.gapSize || 1;
  38152. var dashNb = options.dashNb || 200;
  38153. var points = options.points;
  38154. var positions = new Array();
  38155. var indices = new Array();
  38156. var curvect = BABYLON.Vector3.Zero();
  38157. var lg = 0;
  38158. var nb = 0;
  38159. var shft = 0;
  38160. var dashshft = 0;
  38161. var curshft = 0;
  38162. var idx = 0;
  38163. var i = 0;
  38164. for (i = 0; i < points.length - 1; i++) {
  38165. points[i + 1].subtractToRef(points[i], curvect);
  38166. lg += curvect.length();
  38167. }
  38168. shft = lg / dashNb;
  38169. dashshft = dashSize * shft / (dashSize + gapSize);
  38170. for (i = 0; i < points.length - 1; i++) {
  38171. points[i + 1].subtractToRef(points[i], curvect);
  38172. nb = Math.floor(curvect.length() / shft);
  38173. curvect.normalize();
  38174. for (var j = 0; j < nb; j++) {
  38175. curshft = shft * j;
  38176. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38177. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38178. indices.push(idx, idx + 1);
  38179. idx += 2;
  38180. }
  38181. }
  38182. // Result
  38183. var vertexData = new VertexData();
  38184. vertexData.positions = positions;
  38185. vertexData.indices = indices;
  38186. return vertexData;
  38187. };
  38188. /**
  38189. * Creates the VertexData for a Ground
  38190. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38191. * - width the width (x direction) of the ground, optional, default 1
  38192. * - height the height (z direction) of the ground, optional, default 1
  38193. * - subdivisions the number of subdivisions per side, optional, default 1
  38194. * @returns the VertexData of the Ground
  38195. */
  38196. VertexData.CreateGround = function (options) {
  38197. var indices = [];
  38198. var positions = [];
  38199. var normals = [];
  38200. var uvs = [];
  38201. var row, col;
  38202. var width = options.width || 1;
  38203. var height = options.height || 1;
  38204. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38205. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38206. for (row = 0; row <= subdivisionsY; row++) {
  38207. for (col = 0; col <= subdivisionsX; col++) {
  38208. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38209. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38210. positions.push(position.x, position.y, position.z);
  38211. normals.push(normal.x, normal.y, normal.z);
  38212. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38213. }
  38214. }
  38215. for (row = 0; row < subdivisionsY; row++) {
  38216. for (col = 0; col < subdivisionsX; col++) {
  38217. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38218. indices.push(col + 1 + row * (subdivisionsX + 1));
  38219. indices.push(col + row * (subdivisionsX + 1));
  38220. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38221. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38222. indices.push(col + row * (subdivisionsX + 1));
  38223. }
  38224. }
  38225. // Result
  38226. var vertexData = new VertexData();
  38227. vertexData.indices = indices;
  38228. vertexData.positions = positions;
  38229. vertexData.normals = normals;
  38230. vertexData.uvs = uvs;
  38231. return vertexData;
  38232. };
  38233. /**
  38234. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38235. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38236. * * xmin the ground minimum X coordinate, optional, default -1
  38237. * * zmin the ground minimum Z coordinate, optional, default -1
  38238. * * xmax the ground maximum X coordinate, optional, default 1
  38239. * * zmax the ground maximum Z coordinate, optional, default 1
  38240. * * 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}
  38241. * * 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}
  38242. * @returns the VertexData of the TiledGround
  38243. */
  38244. VertexData.CreateTiledGround = function (options) {
  38245. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38246. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38247. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38248. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38249. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38250. var precision = options.precision || { w: 1, h: 1 };
  38251. var indices = new Array();
  38252. var positions = new Array();
  38253. var normals = new Array();
  38254. var uvs = new Array();
  38255. var row, col, tileRow, tileCol;
  38256. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38257. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38258. precision.w = (precision.w < 1) ? 1 : precision.w;
  38259. precision.h = (precision.h < 1) ? 1 : precision.h;
  38260. var tileSize = {
  38261. 'w': (xmax - xmin) / subdivisions.w,
  38262. 'h': (zmax - zmin) / subdivisions.h
  38263. };
  38264. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38265. // Indices
  38266. var base = positions.length / 3;
  38267. var rowLength = precision.w + 1;
  38268. for (row = 0; row < precision.h; row++) {
  38269. for (col = 0; col < precision.w; col++) {
  38270. var square = [
  38271. base + col + row * rowLength,
  38272. base + (col + 1) + row * rowLength,
  38273. base + (col + 1) + (row + 1) * rowLength,
  38274. base + col + (row + 1) * rowLength
  38275. ];
  38276. indices.push(square[1]);
  38277. indices.push(square[2]);
  38278. indices.push(square[3]);
  38279. indices.push(square[0]);
  38280. indices.push(square[1]);
  38281. indices.push(square[3]);
  38282. }
  38283. }
  38284. // Position, normals and uvs
  38285. var position = BABYLON.Vector3.Zero();
  38286. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38287. for (row = 0; row <= precision.h; row++) {
  38288. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38289. for (col = 0; col <= precision.w; col++) {
  38290. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38291. position.y = 0;
  38292. positions.push(position.x, position.y, position.z);
  38293. normals.push(normal.x, normal.y, normal.z);
  38294. uvs.push(col / precision.w, row / precision.h);
  38295. }
  38296. }
  38297. }
  38298. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38299. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38300. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38301. }
  38302. }
  38303. // Result
  38304. var vertexData = new VertexData();
  38305. vertexData.indices = indices;
  38306. vertexData.positions = positions;
  38307. vertexData.normals = normals;
  38308. vertexData.uvs = uvs;
  38309. return vertexData;
  38310. };
  38311. /**
  38312. * Creates the VertexData of the Ground designed from a heightmap
  38313. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38314. * * width the width (x direction) of the ground
  38315. * * height the height (z direction) of the ground
  38316. * * subdivisions the number of subdivisions per side
  38317. * * minHeight the minimum altitude on the ground, optional, default 0
  38318. * * maxHeight the maximum altitude on the ground, optional default 1
  38319. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38320. * * buffer the array holding the image color data
  38321. * * bufferWidth the width of image
  38322. * * bufferHeight the height of image
  38323. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38324. * @returns the VertexData of the Ground designed from a heightmap
  38325. */
  38326. VertexData.CreateGroundFromHeightMap = function (options) {
  38327. var indices = [];
  38328. var positions = [];
  38329. var normals = [];
  38330. var uvs = [];
  38331. var row, col;
  38332. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38333. var alphaFilter = options.alphaFilter || 0.0;
  38334. // Vertices
  38335. for (row = 0; row <= options.subdivisions; row++) {
  38336. for (col = 0; col <= options.subdivisions; col++) {
  38337. 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));
  38338. // Compute height
  38339. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38340. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38341. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38342. var r = options.buffer[pos] / 255.0;
  38343. var g = options.buffer[pos + 1] / 255.0;
  38344. var b = options.buffer[pos + 2] / 255.0;
  38345. var a = options.buffer[pos + 3] / 255.0;
  38346. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38347. // If our alpha channel is not within our filter then we will assign a 'special' height
  38348. // Then when building the indices, we will ignore any vertex that is using the special height
  38349. if (a >= alphaFilter)
  38350. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38351. else {
  38352. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38353. }
  38354. // Add vertex
  38355. positions.push(position.x, position.y, position.z);
  38356. normals.push(0, 0, 0);
  38357. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38358. }
  38359. }
  38360. // Indices
  38361. for (row = 0; row < options.subdivisions; row++) {
  38362. for (col = 0; col < options.subdivisions; col++) {
  38363. // Calculate Indices
  38364. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38365. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38366. var idx3 = (col + row * (options.subdivisions + 1));
  38367. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38368. // Check that all indices are visible (based on our special height)
  38369. // Only display the vertex if all Indices are visible
  38370. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38371. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38372. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38373. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38374. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38375. indices.push(idx1);
  38376. indices.push(idx2);
  38377. indices.push(idx3);
  38378. }
  38379. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38380. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38381. indices.push(idx4);
  38382. indices.push(idx1);
  38383. indices.push(idx3);
  38384. }
  38385. }
  38386. }
  38387. // Normals
  38388. VertexData.ComputeNormals(positions, indices, normals);
  38389. // Result
  38390. var vertexData = new VertexData();
  38391. vertexData.indices = indices;
  38392. vertexData.positions = positions;
  38393. vertexData.normals = normals;
  38394. vertexData.uvs = uvs;
  38395. return vertexData;
  38396. };
  38397. /**
  38398. * Creates the VertexData for a Plane
  38399. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38400. * * size sets the width and height of the plane to the value of size, optional default 1
  38401. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38402. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38403. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38404. * * 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)
  38405. * * 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)
  38406. * @returns the VertexData of the box
  38407. */
  38408. VertexData.CreatePlane = function (options) {
  38409. var indices = [];
  38410. var positions = [];
  38411. var normals = [];
  38412. var uvs = [];
  38413. var width = options.width || options.size || 1;
  38414. var height = options.height || options.size || 1;
  38415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38416. // Vertices
  38417. var halfWidth = width / 2.0;
  38418. var halfHeight = height / 2.0;
  38419. positions.push(-halfWidth, -halfHeight, 0);
  38420. normals.push(0, 0, -1.0);
  38421. uvs.push(0.0, 0.0);
  38422. positions.push(halfWidth, -halfHeight, 0);
  38423. normals.push(0, 0, -1.0);
  38424. uvs.push(1.0, 0.0);
  38425. positions.push(halfWidth, halfHeight, 0);
  38426. normals.push(0, 0, -1.0);
  38427. uvs.push(1.0, 1.0);
  38428. positions.push(-halfWidth, halfHeight, 0);
  38429. normals.push(0, 0, -1.0);
  38430. uvs.push(0.0, 1.0);
  38431. // Indices
  38432. indices.push(0);
  38433. indices.push(1);
  38434. indices.push(2);
  38435. indices.push(0);
  38436. indices.push(2);
  38437. indices.push(3);
  38438. // Sides
  38439. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38440. // Result
  38441. var vertexData = new VertexData();
  38442. vertexData.indices = indices;
  38443. vertexData.positions = positions;
  38444. vertexData.normals = normals;
  38445. vertexData.uvs = uvs;
  38446. return vertexData;
  38447. };
  38448. /**
  38449. * Creates the VertexData of the Disc or regular Polygon
  38450. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38451. * * radius the radius of the disc, optional default 0.5
  38452. * * tessellation the number of polygon sides, optional, default 64
  38453. * * 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
  38454. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38455. * * 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)
  38456. * * 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)
  38457. * @returns the VertexData of the box
  38458. */
  38459. VertexData.CreateDisc = function (options) {
  38460. var positions = new Array();
  38461. var indices = new Array();
  38462. var normals = new Array();
  38463. var uvs = new Array();
  38464. var radius = options.radius || 0.5;
  38465. var tessellation = options.tessellation || 64;
  38466. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38467. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38468. // positions and uvs
  38469. positions.push(0, 0, 0); // disc center first
  38470. uvs.push(0.5, 0.5);
  38471. var theta = Math.PI * 2 * arc;
  38472. var step = theta / tessellation;
  38473. for (var a = 0; a < theta; a += step) {
  38474. var x = Math.cos(a);
  38475. var y = Math.sin(a);
  38476. var u = (x + 1) / 2;
  38477. var v = (1 - y) / 2;
  38478. positions.push(radius * x, radius * y, 0);
  38479. uvs.push(u, v);
  38480. }
  38481. if (arc === 1) {
  38482. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38483. uvs.push(uvs[2], uvs[3]);
  38484. }
  38485. //indices
  38486. var vertexNb = positions.length / 3;
  38487. for (var i = 1; i < vertexNb - 1; i++) {
  38488. indices.push(i + 1, 0, i);
  38489. }
  38490. // result
  38491. VertexData.ComputeNormals(positions, indices, normals);
  38492. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38493. var vertexData = new VertexData();
  38494. vertexData.indices = indices;
  38495. vertexData.positions = positions;
  38496. vertexData.normals = normals;
  38497. vertexData.uvs = uvs;
  38498. return vertexData;
  38499. };
  38500. /**
  38501. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38502. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38503. * @param polygon a mesh built from polygonTriangulation.build()
  38504. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38505. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38506. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38507. * @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)
  38508. * @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)
  38509. * @returns the VertexData of the Polygon
  38510. */
  38511. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38512. var faceUV = fUV || new Array(3);
  38513. var faceColors = fColors;
  38514. var colors = [];
  38515. // default face colors and UV if undefined
  38516. for (var f = 0; f < 3; f++) {
  38517. if (faceUV[f] === undefined) {
  38518. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38519. }
  38520. if (faceColors && faceColors[f] === undefined) {
  38521. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38522. }
  38523. }
  38524. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38525. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38526. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38527. var indices = polygon.getIndices();
  38528. // set face colours and textures
  38529. var idx = 0;
  38530. var face = 0;
  38531. for (var index = 0; index < normals.length; index += 3) {
  38532. //Edge Face no. 1
  38533. if (Math.abs(normals[index + 1]) < 0.001) {
  38534. face = 1;
  38535. }
  38536. //Top Face no. 0
  38537. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38538. face = 0;
  38539. }
  38540. //Bottom Face no. 2
  38541. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38542. face = 2;
  38543. }
  38544. idx = index / 3;
  38545. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38546. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38547. if (faceColors) {
  38548. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38549. }
  38550. }
  38551. // sides
  38552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38553. // Result
  38554. var vertexData = new VertexData();
  38555. vertexData.indices = indices;
  38556. vertexData.positions = positions;
  38557. vertexData.normals = normals;
  38558. vertexData.uvs = uvs;
  38559. if (faceColors) {
  38560. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38561. vertexData.colors = totalColors;
  38562. }
  38563. return vertexData;
  38564. };
  38565. /**
  38566. * Creates the VertexData of the IcoSphere
  38567. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38568. * * radius the radius of the IcoSphere, optional default 1
  38569. * * radiusX allows stretching in the x direction, optional, default radius
  38570. * * radiusY allows stretching in the y direction, optional, default radius
  38571. * * radiusZ allows stretching in the z direction, optional, default radius
  38572. * * flat when true creates a flat shaded mesh, optional, default true
  38573. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38574. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38575. * * 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)
  38576. * * 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)
  38577. * @returns the VertexData of the IcoSphere
  38578. */
  38579. VertexData.CreateIcoSphere = function (options) {
  38580. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38581. var radius = options.radius || 1;
  38582. var flat = (options.flat === undefined) ? true : options.flat;
  38583. var subdivisions = options.subdivisions || 4;
  38584. var radiusX = options.radiusX || radius;
  38585. var radiusY = options.radiusY || radius;
  38586. var radiusZ = options.radiusZ || radius;
  38587. var t = (1 + Math.sqrt(5)) / 2;
  38588. // 12 vertex x,y,z
  38589. var ico_vertices = [
  38590. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38591. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38592. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38593. ];
  38594. // index of 3 vertex makes a face of icopshere
  38595. var ico_indices = [
  38596. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38597. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38598. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38599. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38600. ];
  38601. // vertex for uv have aliased position, not for UV
  38602. var vertices_unalias_id = [
  38603. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38604. // vertex alias
  38605. 0,
  38606. 2,
  38607. 3,
  38608. 3,
  38609. 3,
  38610. 4,
  38611. 7,
  38612. 8,
  38613. 9,
  38614. 9,
  38615. 10,
  38616. 11 // 23: B + 12
  38617. ];
  38618. // uv as integer step (not pixels !)
  38619. var ico_vertexuv = [
  38620. 5, 1, 3, 1, 6, 4, 0, 0,
  38621. 5, 3, 4, 2, 2, 2, 4, 0,
  38622. 2, 0, 1, 1, 6, 0, 6, 2,
  38623. // vertex alias (for same vertex on different faces)
  38624. 0, 4,
  38625. 3, 3,
  38626. 4, 4,
  38627. 3, 1,
  38628. 4, 2,
  38629. 4, 4,
  38630. 0, 2,
  38631. 1, 1,
  38632. 2, 2,
  38633. 3, 3,
  38634. 1, 3,
  38635. 2, 4 // 23: B + 12
  38636. ];
  38637. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38638. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38639. // First island of uv mapping
  38640. // v = 4h 3+ 2
  38641. // v = 3h 9+ 4
  38642. // v = 2h 9+ 5 B
  38643. // v = 1h 9 1 0
  38644. // v = 0h 3 8 7 A
  38645. // u = 0 1 2 3 4 5 6 *a
  38646. // Second island of uv mapping
  38647. // v = 4h 0+ B+ 4+
  38648. // v = 3h A+ 2+
  38649. // v = 2h 7+ 6 3+
  38650. // v = 1h 8+ 3+
  38651. // v = 0h
  38652. // u = 0 1 2 3 4 5 6 *a
  38653. // Face layout on texture UV mapping
  38654. // ============
  38655. // \ 4 /\ 16 / ======
  38656. // \ / \ / /\ 11 /
  38657. // \/ 7 \/ / \ /
  38658. // ======= / 10 \/
  38659. // /\ 17 /\ =======
  38660. // / \ / \ \ 15 /\
  38661. // / 8 \/ 12 \ \ / \
  38662. // ============ \/ 6 \
  38663. // \ 18 /\ ============
  38664. // \ / \ \ 5 /\ 0 /
  38665. // \/ 13 \ \ / \ /
  38666. // ======= \/ 1 \/
  38667. // =============
  38668. // /\ 19 /\ 2 /\
  38669. // / \ / \ / \
  38670. // / 14 \/ 9 \/ 3 \
  38671. // ===================
  38672. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38673. var ustep = 138 / 1024;
  38674. var vstep = 239 / 1024;
  38675. var uoffset = 60 / 1024;
  38676. var voffset = 26 / 1024;
  38677. // Second island should have margin, not to touch the first island
  38678. // avoid any borderline artefact in pixel rounding
  38679. var island_u_offset = -40 / 1024;
  38680. var island_v_offset = +20 / 1024;
  38681. // face is either island 0 or 1 :
  38682. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38683. var island = [
  38684. 0, 0, 0, 0, 1,
  38685. 0, 0, 1, 1, 0,
  38686. 0, 0, 1, 1, 0,
  38687. 0, 1, 1, 1, 0 // 15 - 19
  38688. ];
  38689. var indices = new Array();
  38690. var positions = new Array();
  38691. var normals = new Array();
  38692. var uvs = new Array();
  38693. var current_indice = 0;
  38694. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38695. var face_vertex_pos = new Array(3);
  38696. var face_vertex_uv = new Array(3);
  38697. var v012;
  38698. for (v012 = 0; v012 < 3; v012++) {
  38699. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38700. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38701. }
  38702. // create all with normals
  38703. for (var face = 0; face < 20; face++) {
  38704. // 3 vertex per face
  38705. for (v012 = 0; v012 < 3; v012++) {
  38706. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38707. var v_id = ico_indices[3 * face + v012];
  38708. // vertex have 3D position (x,y,z)
  38709. 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]);
  38710. // Normalize to get normal, then scale to radius
  38711. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38712. // uv Coordinates from vertex ID
  38713. 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);
  38714. }
  38715. // Subdivide the face (interpolate pos, norm, uv)
  38716. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38717. // - norm is linear interpolation of vertex corner normal
  38718. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38719. // - uv is linear interpolation
  38720. //
  38721. // Topology is as below for sub-divide by 2
  38722. // vertex shown as v0,v1,v2
  38723. // interp index is i1 to progress in range [v0,v1[
  38724. // interp index is i2 to progress in range [v0,v2[
  38725. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38726. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38727. //
  38728. //
  38729. // i2 v2
  38730. // ^ ^
  38731. // / / \
  38732. // / / \
  38733. // / / \
  38734. // / / (0,1) \
  38735. // / #---------\
  38736. // / / \ (0,0)'/ \
  38737. // / / \ / \
  38738. // / / \ / \
  38739. // / / (0,0) \ / (1,0) \
  38740. // / #---------#---------\
  38741. // v0 v1
  38742. //
  38743. // --------------------> i1
  38744. //
  38745. // interp of (i1,i2):
  38746. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38747. // along i1 : lerp(x0,x1, i1/(S-i2))
  38748. //
  38749. // centroid of triangle is needed to get help normal computation
  38750. // (c1,c2) are used for centroid location
  38751. var interp_vertex = function (i1, i2, c1, c2) {
  38752. // vertex is interpolated from
  38753. // - face_vertex_pos[0..2]
  38754. // - face_vertex_uv[0..2]
  38755. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38756. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38757. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38758. pos_interp.normalize();
  38759. var vertex_normal;
  38760. if (flat) {
  38761. // in flat mode, recalculate normal as face centroid normal
  38762. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38763. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38764. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38765. }
  38766. else {
  38767. // in smooth mode, recalculate normal from each single vertex position
  38768. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38769. }
  38770. // Vertex normal need correction due to X,Y,Z radius scaling
  38771. vertex_normal.x /= radiusX;
  38772. vertex_normal.y /= radiusY;
  38773. vertex_normal.z /= radiusZ;
  38774. vertex_normal.normalize();
  38775. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38776. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38777. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38778. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38779. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38780. uvs.push(uv_interp.x, uv_interp.y);
  38781. // push each vertex has member of a face
  38782. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38783. indices.push(current_indice);
  38784. current_indice++;
  38785. };
  38786. for (var i2 = 0; i2 < subdivisions; i2++) {
  38787. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38788. // face : (i1,i2) for /\ :
  38789. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38790. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38791. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38792. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38793. if (i1 + i2 + 1 < subdivisions) {
  38794. // face : (i1,i2)' for \/ :
  38795. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38796. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38797. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38798. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38799. }
  38800. }
  38801. }
  38802. }
  38803. // Sides
  38804. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38805. // Result
  38806. var vertexData = new VertexData();
  38807. vertexData.indices = indices;
  38808. vertexData.positions = positions;
  38809. vertexData.normals = normals;
  38810. vertexData.uvs = uvs;
  38811. return vertexData;
  38812. };
  38813. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38814. /**
  38815. * Creates the VertexData for a Polyhedron
  38816. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38817. * * type provided types are:
  38818. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38819. * * 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)
  38820. * * size the size of the IcoSphere, optional default 1
  38821. * * sizeX allows stretching in the x direction, optional, default size
  38822. * * sizeY allows stretching in the y direction, optional, default size
  38823. * * sizeZ allows stretching in the z direction, optional, default size
  38824. * * 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
  38825. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38826. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38827. * * flat when true creates a flat shaded mesh, optional, default true
  38828. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38829. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38830. * * 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)
  38831. * * 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)
  38832. * @returns the VertexData of the Polyhedron
  38833. */
  38834. VertexData.CreatePolyhedron = function (options) {
  38835. // provided polyhedron types :
  38836. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38837. // 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)
  38838. var polyhedra = [];
  38839. 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]] };
  38840. 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]] };
  38841. polyhedra[2] = {
  38842. 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]],
  38843. 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]]
  38844. };
  38845. polyhedra[3] = {
  38846. 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]],
  38847. 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]]
  38848. };
  38849. polyhedra[4] = {
  38850. 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]],
  38851. 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]]
  38852. };
  38853. 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]] };
  38854. 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]] };
  38855. 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]] };
  38856. 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]] };
  38857. 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]] };
  38858. 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]] };
  38859. 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]] };
  38860. 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]] };
  38861. 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]] };
  38862. polyhedra[14] = {
  38863. 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]],
  38864. 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]]
  38865. };
  38866. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38867. var size = options.size;
  38868. var sizeX = options.sizeX || size || 1;
  38869. var sizeY = options.sizeY || size || 1;
  38870. var sizeZ = options.sizeZ || size || 1;
  38871. var data = options.custom || polyhedra[type];
  38872. var nbfaces = data.face.length;
  38873. var faceUV = options.faceUV || new Array(nbfaces);
  38874. var faceColors = options.faceColors;
  38875. var flat = (options.flat === undefined) ? true : options.flat;
  38876. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38877. var positions = new Array();
  38878. var indices = new Array();
  38879. var normals = new Array();
  38880. var uvs = new Array();
  38881. var colors = new Array();
  38882. var index = 0;
  38883. var faceIdx = 0; // face cursor in the array "indexes"
  38884. var indexes = new Array();
  38885. var i = 0;
  38886. var f = 0;
  38887. var u, v, ang, x, y, tmp;
  38888. // default face colors and UV if undefined
  38889. if (flat) {
  38890. for (f = 0; f < nbfaces; f++) {
  38891. if (faceColors && faceColors[f] === undefined) {
  38892. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38893. }
  38894. if (faceUV && faceUV[f] === undefined) {
  38895. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38896. }
  38897. }
  38898. }
  38899. if (!flat) {
  38900. for (i = 0; i < data.vertex.length; i++) {
  38901. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38902. uvs.push(0, 0);
  38903. }
  38904. for (f = 0; f < nbfaces; f++) {
  38905. for (i = 0; i < data.face[f].length - 2; i++) {
  38906. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38907. }
  38908. }
  38909. }
  38910. else {
  38911. for (f = 0; f < nbfaces; f++) {
  38912. var fl = data.face[f].length; // number of vertices of the current face
  38913. ang = 2 * Math.PI / fl;
  38914. x = 0.5 * Math.tan(ang / 2);
  38915. y = 0.5;
  38916. // positions, uvs, colors
  38917. for (i = 0; i < fl; i++) {
  38918. // positions
  38919. 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);
  38920. indexes.push(index);
  38921. index++;
  38922. // uvs
  38923. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38924. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38925. uvs.push(u, v);
  38926. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38927. y = x * Math.sin(ang) + y * Math.cos(ang);
  38928. x = tmp;
  38929. // colors
  38930. if (faceColors) {
  38931. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38932. }
  38933. }
  38934. // indices from indexes
  38935. for (i = 0; i < fl - 2; i++) {
  38936. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38937. }
  38938. faceIdx += fl;
  38939. }
  38940. }
  38941. VertexData.ComputeNormals(positions, indices, normals);
  38942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38943. var vertexData = new VertexData();
  38944. vertexData.positions = positions;
  38945. vertexData.indices = indices;
  38946. vertexData.normals = normals;
  38947. vertexData.uvs = uvs;
  38948. if (faceColors && flat) {
  38949. vertexData.colors = colors;
  38950. }
  38951. return vertexData;
  38952. };
  38953. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38954. /**
  38955. * Creates the VertexData for a TorusKnot
  38956. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38957. * * radius the radius of the torus knot, optional, default 2
  38958. * * tube the thickness of the tube, optional, default 0.5
  38959. * * radialSegments the number of sides on each tube segments, optional, default 32
  38960. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38961. * * p the number of windings around the z axis, optional, default 2
  38962. * * q the number of windings around the x axis, optional, default 3
  38963. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38964. * * 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)
  38965. * * 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)
  38966. * @returns the VertexData of the Torus Knot
  38967. */
  38968. VertexData.CreateTorusKnot = function (options) {
  38969. var indices = new Array();
  38970. var positions = new Array();
  38971. var normals = new Array();
  38972. var uvs = new Array();
  38973. var radius = options.radius || 2;
  38974. var tube = options.tube || 0.5;
  38975. var radialSegments = options.radialSegments || 32;
  38976. var tubularSegments = options.tubularSegments || 32;
  38977. var p = options.p || 2;
  38978. var q = options.q || 3;
  38979. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38980. // Helper
  38981. var getPos = function (angle) {
  38982. var cu = Math.cos(angle);
  38983. var su = Math.sin(angle);
  38984. var quOverP = q / p * angle;
  38985. var cs = Math.cos(quOverP);
  38986. var tx = radius * (2 + cs) * 0.5 * cu;
  38987. var ty = radius * (2 + cs) * su * 0.5;
  38988. var tz = radius * Math.sin(quOverP) * 0.5;
  38989. return new BABYLON.Vector3(tx, ty, tz);
  38990. };
  38991. // Vertices
  38992. var i;
  38993. var j;
  38994. for (i = 0; i <= radialSegments; i++) {
  38995. var modI = i % radialSegments;
  38996. var u = modI / radialSegments * 2 * p * Math.PI;
  38997. var p1 = getPos(u);
  38998. var p2 = getPos(u + 0.01);
  38999. var tang = p2.subtract(p1);
  39000. var n = p2.add(p1);
  39001. var bitan = BABYLON.Vector3.Cross(tang, n);
  39002. n = BABYLON.Vector3.Cross(bitan, tang);
  39003. bitan.normalize();
  39004. n.normalize();
  39005. for (j = 0; j < tubularSegments; j++) {
  39006. var modJ = j % tubularSegments;
  39007. var v = modJ / tubularSegments * 2 * Math.PI;
  39008. var cx = -tube * Math.cos(v);
  39009. var cy = tube * Math.sin(v);
  39010. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39011. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39012. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39013. uvs.push(i / radialSegments);
  39014. uvs.push(j / tubularSegments);
  39015. }
  39016. }
  39017. for (i = 0; i < radialSegments; i++) {
  39018. for (j = 0; j < tubularSegments; j++) {
  39019. var jNext = (j + 1) % tubularSegments;
  39020. var a = i * tubularSegments + j;
  39021. var b = (i + 1) * tubularSegments + j;
  39022. var c = (i + 1) * tubularSegments + jNext;
  39023. var d = i * tubularSegments + jNext;
  39024. indices.push(d);
  39025. indices.push(b);
  39026. indices.push(a);
  39027. indices.push(d);
  39028. indices.push(c);
  39029. indices.push(b);
  39030. }
  39031. }
  39032. // Normals
  39033. VertexData.ComputeNormals(positions, indices, normals);
  39034. // Sides
  39035. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39036. // Result
  39037. var vertexData = new VertexData();
  39038. vertexData.indices = indices;
  39039. vertexData.positions = positions;
  39040. vertexData.normals = normals;
  39041. vertexData.uvs = uvs;
  39042. return vertexData;
  39043. };
  39044. // Tools
  39045. /**
  39046. * Compute normals for given positions and indices
  39047. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39048. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39049. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39050. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39051. * * facetNormals : optional array of facet normals (vector3)
  39052. * * facetPositions : optional array of facet positions (vector3)
  39053. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39054. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39055. * * bInfo : optional bounding info, required for facetPartitioning computation
  39056. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39057. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39058. * * useRightHandedSystem: optional boolean to for right handed system computation
  39059. * * depthSort : optional boolean to enable the facet depth sort computation
  39060. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39061. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39062. */
  39063. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39064. // temporary scalar variables
  39065. var index = 0; // facet index
  39066. var p1p2x = 0.0; // p1p2 vector x coordinate
  39067. var p1p2y = 0.0; // p1p2 vector y coordinate
  39068. var p1p2z = 0.0; // p1p2 vector z coordinate
  39069. var p3p2x = 0.0; // p3p2 vector x coordinate
  39070. var p3p2y = 0.0; // p3p2 vector y coordinate
  39071. var p3p2z = 0.0; // p3p2 vector z coordinate
  39072. var faceNormalx = 0.0; // facet normal x coordinate
  39073. var faceNormaly = 0.0; // facet normal y coordinate
  39074. var faceNormalz = 0.0; // facet normal z coordinate
  39075. var length = 0.0; // facet normal length before normalization
  39076. var v1x = 0; // vector1 x index in the positions array
  39077. var v1y = 0; // vector1 y index in the positions array
  39078. var v1z = 0; // vector1 z index in the positions array
  39079. var v2x = 0; // vector2 x index in the positions array
  39080. var v2y = 0; // vector2 y index in the positions array
  39081. var v2z = 0; // vector2 z index in the positions array
  39082. var v3x = 0; // vector3 x index in the positions array
  39083. var v3y = 0; // vector3 y index in the positions array
  39084. var v3z = 0; // vector3 z index in the positions array
  39085. var computeFacetNormals = false;
  39086. var computeFacetPositions = false;
  39087. var computeFacetPartitioning = false;
  39088. var computeDepthSort = false;
  39089. var faceNormalSign = 1;
  39090. var ratio = 0;
  39091. var distanceTo = null;
  39092. if (options) {
  39093. computeFacetNormals = (options.facetNormals) ? true : false;
  39094. computeFacetPositions = (options.facetPositions) ? true : false;
  39095. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39096. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39097. ratio = options.ratio || 0;
  39098. computeDepthSort = (options.depthSort) ? true : false;
  39099. distanceTo = (options.distanceTo);
  39100. if (computeDepthSort) {
  39101. if (distanceTo === undefined) {
  39102. distanceTo = BABYLON.Vector3.Zero();
  39103. }
  39104. var depthSortedFacets = options.depthSortedFacets;
  39105. }
  39106. }
  39107. // facetPartitioning reinit if needed
  39108. var xSubRatio = 0;
  39109. var ySubRatio = 0;
  39110. var zSubRatio = 0;
  39111. var subSq = 0;
  39112. if (computeFacetPartitioning && options && options.bbSize) {
  39113. var ox = 0; // X partitioning index for facet position
  39114. var oy = 0; // Y partinioning index for facet position
  39115. var oz = 0; // Z partinioning index for facet position
  39116. var b1x = 0; // X partitioning index for facet v1 vertex
  39117. var b1y = 0; // Y partitioning index for facet v1 vertex
  39118. var b1z = 0; // z partitioning index for facet v1 vertex
  39119. var b2x = 0; // X partitioning index for facet v2 vertex
  39120. var b2y = 0; // Y partitioning index for facet v2 vertex
  39121. var b2z = 0; // Z partitioning index for facet v2 vertex
  39122. var b3x = 0; // X partitioning index for facet v3 vertex
  39123. var b3y = 0; // Y partitioning index for facet v3 vertex
  39124. var b3z = 0; // Z partitioning index for facet v3 vertex
  39125. var block_idx_o = 0; // facet barycenter block index
  39126. var block_idx_v1 = 0; // v1 vertex block index
  39127. var block_idx_v2 = 0; // v2 vertex block index
  39128. var block_idx_v3 = 0; // v3 vertex block index
  39129. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39130. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39131. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39132. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39133. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39134. subSq = options.subDiv.max * options.subDiv.max;
  39135. options.facetPartitioning.length = 0;
  39136. }
  39137. // reset the normals
  39138. for (index = 0; index < positions.length; index++) {
  39139. normals[index] = 0.0;
  39140. }
  39141. // Loop : 1 indice triplet = 1 facet
  39142. var nbFaces = (indices.length / 3) | 0;
  39143. for (index = 0; index < nbFaces; index++) {
  39144. // get the indexes of the coordinates of each vertex of the facet
  39145. v1x = indices[index * 3] * 3;
  39146. v1y = v1x + 1;
  39147. v1z = v1x + 2;
  39148. v2x = indices[index * 3 + 1] * 3;
  39149. v2y = v2x + 1;
  39150. v2z = v2x + 2;
  39151. v3x = indices[index * 3 + 2] * 3;
  39152. v3y = v3x + 1;
  39153. v3z = v3x + 2;
  39154. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39155. p1p2y = positions[v1y] - positions[v2y];
  39156. p1p2z = positions[v1z] - positions[v2z];
  39157. p3p2x = positions[v3x] - positions[v2x];
  39158. p3p2y = positions[v3y] - positions[v2y];
  39159. p3p2z = positions[v3z] - positions[v2z];
  39160. // compute the face normal with the cross product
  39161. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39162. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39163. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39164. // normalize this normal and store it in the array facetData
  39165. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39166. length = (length === 0) ? 1.0 : length;
  39167. faceNormalx /= length;
  39168. faceNormaly /= length;
  39169. faceNormalz /= length;
  39170. if (computeFacetNormals && options) {
  39171. options.facetNormals[index].x = faceNormalx;
  39172. options.facetNormals[index].y = faceNormaly;
  39173. options.facetNormals[index].z = faceNormalz;
  39174. }
  39175. if (computeFacetPositions && options) {
  39176. // compute and the facet barycenter coordinates in the array facetPositions
  39177. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39178. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39179. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39180. }
  39181. if (computeFacetPartitioning && options) {
  39182. // store the facet indexes in arrays in the main facetPartitioning array :
  39183. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39184. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39185. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39186. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39187. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39188. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39189. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39190. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39191. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39192. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39193. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39194. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39195. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39196. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39197. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39198. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39199. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39200. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39201. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39202. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39203. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39204. // push each facet index in each block containing the vertex
  39205. options.facetPartitioning[block_idx_v1].push(index);
  39206. if (block_idx_v2 != block_idx_v1) {
  39207. options.facetPartitioning[block_idx_v2].push(index);
  39208. }
  39209. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39210. options.facetPartitioning[block_idx_v3].push(index);
  39211. }
  39212. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39213. options.facetPartitioning[block_idx_o].push(index);
  39214. }
  39215. }
  39216. if (computeDepthSort && options && options.facetPositions) {
  39217. var dsf = depthSortedFacets[index];
  39218. dsf.ind = index * 3;
  39219. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39220. }
  39221. // compute the normals anyway
  39222. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39223. normals[v1y] += faceNormaly;
  39224. normals[v1z] += faceNormalz;
  39225. normals[v2x] += faceNormalx;
  39226. normals[v2y] += faceNormaly;
  39227. normals[v2z] += faceNormalz;
  39228. normals[v3x] += faceNormalx;
  39229. normals[v3y] += faceNormaly;
  39230. normals[v3z] += faceNormalz;
  39231. }
  39232. // last normalization of each normal
  39233. for (index = 0; index < normals.length / 3; index++) {
  39234. faceNormalx = normals[index * 3];
  39235. faceNormaly = normals[index * 3 + 1];
  39236. faceNormalz = normals[index * 3 + 2];
  39237. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39238. length = (length === 0) ? 1.0 : length;
  39239. faceNormalx /= length;
  39240. faceNormaly /= length;
  39241. faceNormalz /= length;
  39242. normals[index * 3] = faceNormalx;
  39243. normals[index * 3 + 1] = faceNormaly;
  39244. normals[index * 3 + 2] = faceNormalz;
  39245. }
  39246. };
  39247. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39248. var li = indices.length;
  39249. var ln = normals.length;
  39250. var i;
  39251. var n;
  39252. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39253. switch (sideOrientation) {
  39254. case BABYLON.Mesh.FRONTSIDE:
  39255. // nothing changed
  39256. break;
  39257. case BABYLON.Mesh.BACKSIDE:
  39258. var tmp;
  39259. // indices
  39260. for (i = 0; i < li; i += 3) {
  39261. tmp = indices[i];
  39262. indices[i] = indices[i + 2];
  39263. indices[i + 2] = tmp;
  39264. }
  39265. // normals
  39266. for (n = 0; n < ln; n++) {
  39267. normals[n] = -normals[n];
  39268. }
  39269. break;
  39270. case BABYLON.Mesh.DOUBLESIDE:
  39271. // positions
  39272. var lp = positions.length;
  39273. var l = lp / 3;
  39274. for (var p = 0; p < lp; p++) {
  39275. positions[lp + p] = positions[p];
  39276. }
  39277. // indices
  39278. for (i = 0; i < li; i += 3) {
  39279. indices[i + li] = indices[i + 2] + l;
  39280. indices[i + 1 + li] = indices[i + 1] + l;
  39281. indices[i + 2 + li] = indices[i] + l;
  39282. }
  39283. // normals
  39284. for (n = 0; n < ln; n++) {
  39285. normals[ln + n] = -normals[n];
  39286. }
  39287. // uvs
  39288. var lu = uvs.length;
  39289. var u = 0;
  39290. for (u = 0; u < lu; u++) {
  39291. uvs[u + lu] = uvs[u];
  39292. }
  39293. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39294. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39295. u = 0;
  39296. for (i = 0; i < lu / 2; i++) {
  39297. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39298. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39299. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39300. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39301. u += 2;
  39302. }
  39303. break;
  39304. }
  39305. };
  39306. /**
  39307. * Applies VertexData created from the imported parameters to the geometry
  39308. * @param parsedVertexData the parsed data from an imported file
  39309. * @param geometry the geometry to apply the VertexData to
  39310. */
  39311. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39312. var vertexData = new VertexData();
  39313. // positions
  39314. var positions = parsedVertexData.positions;
  39315. if (positions) {
  39316. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39317. }
  39318. // normals
  39319. var normals = parsedVertexData.normals;
  39320. if (normals) {
  39321. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39322. }
  39323. // tangents
  39324. var tangents = parsedVertexData.tangents;
  39325. if (tangents) {
  39326. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39327. }
  39328. // uvs
  39329. var uvs = parsedVertexData.uvs;
  39330. if (uvs) {
  39331. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39332. }
  39333. // uv2s
  39334. var uv2s = parsedVertexData.uv2s;
  39335. if (uv2s) {
  39336. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39337. }
  39338. // uv3s
  39339. var uv3s = parsedVertexData.uv3s;
  39340. if (uv3s) {
  39341. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39342. }
  39343. // uv4s
  39344. var uv4s = parsedVertexData.uv4s;
  39345. if (uv4s) {
  39346. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39347. }
  39348. // uv5s
  39349. var uv5s = parsedVertexData.uv5s;
  39350. if (uv5s) {
  39351. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39352. }
  39353. // uv6s
  39354. var uv6s = parsedVertexData.uv6s;
  39355. if (uv6s) {
  39356. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39357. }
  39358. // colors
  39359. var colors = parsedVertexData.colors;
  39360. if (colors) {
  39361. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39362. }
  39363. // matricesIndices
  39364. var matricesIndices = parsedVertexData.matricesIndices;
  39365. if (matricesIndices) {
  39366. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39367. }
  39368. // matricesWeights
  39369. var matricesWeights = parsedVertexData.matricesWeights;
  39370. if (matricesWeights) {
  39371. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39372. }
  39373. // indices
  39374. var indices = parsedVertexData.indices;
  39375. if (indices) {
  39376. vertexData.indices = indices;
  39377. }
  39378. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39379. };
  39380. return VertexData;
  39381. }());
  39382. BABYLON.VertexData = VertexData;
  39383. })(BABYLON || (BABYLON = {}));
  39384. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39385. var BABYLON;
  39386. (function (BABYLON) {
  39387. /**
  39388. * Class used to store geometry data (vertex buffers + index buffer)
  39389. */
  39390. var Geometry = /** @class */ (function () {
  39391. /**
  39392. * Creates a new geometry
  39393. * @param id defines the unique ID
  39394. * @param scene defines the hosting scene
  39395. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39396. * @param updatable defines if geometry must be updatable (false by default)
  39397. * @param mesh defines the mesh that will be associated with the geometry
  39398. */
  39399. function Geometry(id, scene, vertexData, updatable, mesh) {
  39400. if (updatable === void 0) { updatable = false; }
  39401. if (mesh === void 0) { mesh = null; }
  39402. /**
  39403. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39404. */
  39405. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39406. this._totalVertices = 0;
  39407. this._isDisposed = false;
  39408. this._indexBufferIsUpdatable = false;
  39409. this.id = id;
  39410. this._engine = scene.getEngine();
  39411. this._meshes = [];
  39412. this._scene = scene;
  39413. //Init vertex buffer cache
  39414. this._vertexBuffers = {};
  39415. this._indices = [];
  39416. this._updatable = updatable;
  39417. // vertexData
  39418. if (vertexData) {
  39419. this.setAllVerticesData(vertexData, updatable);
  39420. }
  39421. else {
  39422. this._totalVertices = 0;
  39423. this._indices = [];
  39424. }
  39425. if (this._engine.getCaps().vertexArrayObject) {
  39426. this._vertexArrayObjects = {};
  39427. }
  39428. // applyToMesh
  39429. if (mesh) {
  39430. if (mesh.getClassName() === "LinesMesh") {
  39431. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39432. this._updateExtend();
  39433. }
  39434. this.applyToMesh(mesh);
  39435. mesh.computeWorldMatrix(true);
  39436. }
  39437. }
  39438. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39439. /**
  39440. * 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
  39441. */
  39442. get: function () {
  39443. return this._boundingBias;
  39444. },
  39445. /**
  39446. * 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
  39447. */
  39448. set: function (value) {
  39449. if (this._boundingBias && this._boundingBias.equals(value)) {
  39450. return;
  39451. }
  39452. this._boundingBias = value.clone();
  39453. this._updateBoundingInfo(true, null);
  39454. },
  39455. enumerable: true,
  39456. configurable: true
  39457. });
  39458. /**
  39459. * Static function used to attach a new empty geometry to a mesh
  39460. * @param mesh defines the mesh to attach the geometry to
  39461. * @returns the new {BABYLON.Geometry}
  39462. */
  39463. Geometry.CreateGeometryForMesh = function (mesh) {
  39464. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39465. geometry.applyToMesh(mesh);
  39466. return geometry;
  39467. };
  39468. Object.defineProperty(Geometry.prototype, "extend", {
  39469. /**
  39470. * Gets the current extend of the geometry
  39471. */
  39472. get: function () {
  39473. return this._extend;
  39474. },
  39475. enumerable: true,
  39476. configurable: true
  39477. });
  39478. /**
  39479. * Gets the hosting scene
  39480. * @returns the hosting {BABYLON.Scene}
  39481. */
  39482. Geometry.prototype.getScene = function () {
  39483. return this._scene;
  39484. };
  39485. /**
  39486. * Gets the hosting engine
  39487. * @returns the hosting {BABYLON.Engine}
  39488. */
  39489. Geometry.prototype.getEngine = function () {
  39490. return this._engine;
  39491. };
  39492. /**
  39493. * Defines if the geometry is ready to use
  39494. * @returns true if the geometry is ready to be used
  39495. */
  39496. Geometry.prototype.isReady = function () {
  39497. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39498. };
  39499. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39500. /**
  39501. * Gets a value indicating that the geometry should not be serialized
  39502. */
  39503. get: function () {
  39504. for (var index = 0; index < this._meshes.length; index++) {
  39505. if (!this._meshes[index].doNotSerialize) {
  39506. return false;
  39507. }
  39508. }
  39509. return true;
  39510. },
  39511. enumerable: true,
  39512. configurable: true
  39513. });
  39514. /** @hidden */
  39515. Geometry.prototype._rebuild = function () {
  39516. if (this._vertexArrayObjects) {
  39517. this._vertexArrayObjects = {};
  39518. }
  39519. // Index buffer
  39520. if (this._meshes.length !== 0 && this._indices) {
  39521. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39522. }
  39523. // Vertex buffers
  39524. for (var key in this._vertexBuffers) {
  39525. var vertexBuffer = this._vertexBuffers[key];
  39526. vertexBuffer._rebuild();
  39527. }
  39528. };
  39529. /**
  39530. * Affects all geometry data in one call
  39531. * @param vertexData defines the geometry data
  39532. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39533. */
  39534. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39535. vertexData.applyToGeometry(this, updatable);
  39536. this.notifyUpdate();
  39537. };
  39538. /**
  39539. * Set specific vertex data
  39540. * @param kind defines the data kind (Position, normal, etc...)
  39541. * @param data defines the vertex data to use
  39542. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39543. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39544. */
  39545. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39546. if (updatable === void 0) { updatable = false; }
  39547. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39548. this.setVerticesBuffer(buffer);
  39549. };
  39550. /**
  39551. * Removes a specific vertex data
  39552. * @param kind defines the data kind (Position, normal, etc...)
  39553. */
  39554. Geometry.prototype.removeVerticesData = function (kind) {
  39555. if (this._vertexBuffers[kind]) {
  39556. this._vertexBuffers[kind].dispose();
  39557. delete this._vertexBuffers[kind];
  39558. }
  39559. };
  39560. /**
  39561. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39562. * @param buffer defines the vertex buffer to use
  39563. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39564. */
  39565. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39566. if (totalVertices === void 0) { totalVertices = null; }
  39567. var kind = buffer.getKind();
  39568. if (this._vertexBuffers[kind]) {
  39569. this._vertexBuffers[kind].dispose();
  39570. }
  39571. this._vertexBuffers[kind] = buffer;
  39572. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39573. var data = buffer.getData();
  39574. if (totalVertices != null) {
  39575. this._totalVertices = totalVertices;
  39576. }
  39577. else {
  39578. if (data != null) {
  39579. this._totalVertices = data.length / (buffer.byteStride / 4);
  39580. }
  39581. }
  39582. this._updateExtend(data);
  39583. this._resetPointsArrayCache();
  39584. var meshes = this._meshes;
  39585. var numOfMeshes = meshes.length;
  39586. for (var index = 0; index < numOfMeshes; index++) {
  39587. var mesh = meshes[index];
  39588. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39589. mesh._createGlobalSubMesh(false);
  39590. mesh.computeWorldMatrix(true);
  39591. }
  39592. }
  39593. this.notifyUpdate(kind);
  39594. if (this._vertexArrayObjects) {
  39595. this._disposeVertexArrayObjects();
  39596. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39597. }
  39598. };
  39599. /**
  39600. * Update a specific vertex buffer
  39601. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39602. * It will do nothing if the buffer is not updatable
  39603. * @param kind defines the data kind (Position, normal, etc...)
  39604. * @param data defines the data to use
  39605. * @param offset defines the offset in the target buffer where to store the data
  39606. * @param useBytes set to true if the offset is in bytes
  39607. */
  39608. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39609. if (useBytes === void 0) { useBytes = false; }
  39610. var vertexBuffer = this.getVertexBuffer(kind);
  39611. if (!vertexBuffer) {
  39612. return;
  39613. }
  39614. vertexBuffer.updateDirectly(data, offset, useBytes);
  39615. this.notifyUpdate(kind);
  39616. };
  39617. /**
  39618. * Update a specific vertex buffer
  39619. * This function will create a new buffer if the current one is not updatable
  39620. * @param kind defines the data kind (Position, normal, etc...)
  39621. * @param data defines the data to use
  39622. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39623. */
  39624. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39625. if (updateExtends === void 0) { updateExtends = false; }
  39626. var vertexBuffer = this.getVertexBuffer(kind);
  39627. if (!vertexBuffer) {
  39628. return;
  39629. }
  39630. vertexBuffer.update(data);
  39631. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39632. this._updateBoundingInfo(updateExtends, data);
  39633. }
  39634. this.notifyUpdate(kind);
  39635. };
  39636. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39637. if (updateExtends) {
  39638. this._updateExtend(data);
  39639. }
  39640. var meshes = this._meshes;
  39641. var numOfMeshes = meshes.length;
  39642. this._resetPointsArrayCache();
  39643. for (var index = 0; index < numOfMeshes; index++) {
  39644. var mesh = meshes[index];
  39645. if (updateExtends) {
  39646. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39647. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39648. var subMesh = mesh.subMeshes[subIndex];
  39649. subMesh.refreshBoundingInfo();
  39650. }
  39651. }
  39652. }
  39653. };
  39654. /** @hidden */
  39655. Geometry.prototype._bind = function (effect, indexToBind) {
  39656. if (!effect) {
  39657. return;
  39658. }
  39659. if (indexToBind === undefined) {
  39660. indexToBind = this._indexBuffer;
  39661. }
  39662. var vbs = this.getVertexBuffers();
  39663. if (!vbs) {
  39664. return;
  39665. }
  39666. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39667. this._engine.bindBuffers(vbs, indexToBind, effect);
  39668. return;
  39669. }
  39670. // Using VAO
  39671. if (!this._vertexArrayObjects[effect.key]) {
  39672. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39673. }
  39674. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39675. };
  39676. /**
  39677. * Gets total number of vertices
  39678. * @returns the total number of vertices
  39679. */
  39680. Geometry.prototype.getTotalVertices = function () {
  39681. if (!this.isReady()) {
  39682. return 0;
  39683. }
  39684. return this._totalVertices;
  39685. };
  39686. /**
  39687. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39688. * @param kind defines the data kind (Position, normal, etc...)
  39689. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39690. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39691. * @returns a float array containing vertex data
  39692. */
  39693. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39694. var vertexBuffer = this.getVertexBuffer(kind);
  39695. if (!vertexBuffer) {
  39696. return null;
  39697. }
  39698. var data = vertexBuffer.getData();
  39699. if (!data) {
  39700. return null;
  39701. }
  39702. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39703. var count = this._totalVertices * vertexBuffer.getSize();
  39704. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39705. var copy_1 = new Array(count);
  39706. vertexBuffer.forEach(count, function (value, index) {
  39707. copy_1[index] = value;
  39708. });
  39709. return copy_1;
  39710. }
  39711. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39712. if (data instanceof Array) {
  39713. var offset = vertexBuffer.byteOffset / 4;
  39714. return BABYLON.Tools.Slice(data, offset, offset + count);
  39715. }
  39716. else if (data instanceof ArrayBuffer) {
  39717. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39718. }
  39719. else {
  39720. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39721. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39722. var result = new Float32Array(count);
  39723. var source = new Float32Array(data.buffer, offset, count);
  39724. result.set(source);
  39725. return result;
  39726. }
  39727. return new Float32Array(data.buffer, offset, count);
  39728. }
  39729. }
  39730. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39731. return BABYLON.Tools.Slice(data);
  39732. }
  39733. return data;
  39734. };
  39735. /**
  39736. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39737. * @param kind defines the data kind (Position, normal, etc...)
  39738. * @returns true if the vertex buffer with the specified kind is updatable
  39739. */
  39740. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39741. var vb = this._vertexBuffers[kind];
  39742. if (!vb) {
  39743. return false;
  39744. }
  39745. return vb.isUpdatable();
  39746. };
  39747. /**
  39748. * Gets a specific vertex buffer
  39749. * @param kind defines the data kind (Position, normal, etc...)
  39750. * @returns a {BABYLON.VertexBuffer}
  39751. */
  39752. Geometry.prototype.getVertexBuffer = function (kind) {
  39753. if (!this.isReady()) {
  39754. return null;
  39755. }
  39756. return this._vertexBuffers[kind];
  39757. };
  39758. /**
  39759. * Returns all vertex buffers
  39760. * @return an object holding all vertex buffers indexed by kind
  39761. */
  39762. Geometry.prototype.getVertexBuffers = function () {
  39763. if (!this.isReady()) {
  39764. return null;
  39765. }
  39766. return this._vertexBuffers;
  39767. };
  39768. /**
  39769. * Gets a boolean indicating if specific vertex buffer is present
  39770. * @param kind defines the data kind (Position, normal, etc...)
  39771. * @returns true if data is present
  39772. */
  39773. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39774. if (!this._vertexBuffers) {
  39775. if (this._delayInfo) {
  39776. return this._delayInfo.indexOf(kind) !== -1;
  39777. }
  39778. return false;
  39779. }
  39780. return this._vertexBuffers[kind] !== undefined;
  39781. };
  39782. /**
  39783. * Gets a list of all attached data kinds (Position, normal, etc...)
  39784. * @returns a list of string containing all kinds
  39785. */
  39786. Geometry.prototype.getVerticesDataKinds = function () {
  39787. var result = [];
  39788. var kind;
  39789. if (!this._vertexBuffers && this._delayInfo) {
  39790. for (kind in this._delayInfo) {
  39791. result.push(kind);
  39792. }
  39793. }
  39794. else {
  39795. for (kind in this._vertexBuffers) {
  39796. result.push(kind);
  39797. }
  39798. }
  39799. return result;
  39800. };
  39801. /**
  39802. * Update index buffer
  39803. * @param indices defines the indices to store in the index buffer
  39804. * @param offset defines the offset in the target buffer where to store the data
  39805. */
  39806. Geometry.prototype.updateIndices = function (indices, offset) {
  39807. if (!this._indexBuffer) {
  39808. return;
  39809. }
  39810. if (!this._indexBufferIsUpdatable) {
  39811. this.setIndices(indices, null, true);
  39812. }
  39813. else {
  39814. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39815. }
  39816. };
  39817. /**
  39818. * Creates a new index buffer
  39819. * @param indices defines the indices to store in the index buffer
  39820. * @param totalVertices defines the total number of vertices (could be null)
  39821. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39822. */
  39823. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39824. if (totalVertices === void 0) { totalVertices = null; }
  39825. if (updatable === void 0) { updatable = false; }
  39826. if (this._indexBuffer) {
  39827. this._engine._releaseBuffer(this._indexBuffer);
  39828. }
  39829. this._disposeVertexArrayObjects();
  39830. this._indices = indices;
  39831. this._indexBufferIsUpdatable = updatable;
  39832. if (this._meshes.length !== 0 && this._indices) {
  39833. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39834. }
  39835. if (totalVertices != undefined) { // including null and undefined
  39836. this._totalVertices = totalVertices;
  39837. }
  39838. var meshes = this._meshes;
  39839. var numOfMeshes = meshes.length;
  39840. for (var index = 0; index < numOfMeshes; index++) {
  39841. meshes[index]._createGlobalSubMesh(true);
  39842. }
  39843. this.notifyUpdate();
  39844. };
  39845. /**
  39846. * Return the total number of indices
  39847. * @returns the total number of indices
  39848. */
  39849. Geometry.prototype.getTotalIndices = function () {
  39850. if (!this.isReady()) {
  39851. return 0;
  39852. }
  39853. return this._indices.length;
  39854. };
  39855. /**
  39856. * Gets the index buffer array
  39857. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39858. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39859. * @returns the index buffer array
  39860. */
  39861. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39862. if (!this.isReady()) {
  39863. return null;
  39864. }
  39865. var orig = this._indices;
  39866. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39867. return orig;
  39868. }
  39869. else {
  39870. var len = orig.length;
  39871. var copy = [];
  39872. for (var i = 0; i < len; i++) {
  39873. copy.push(orig[i]);
  39874. }
  39875. return copy;
  39876. }
  39877. };
  39878. /**
  39879. * Gets the index buffer
  39880. * @return the index buffer
  39881. */
  39882. Geometry.prototype.getIndexBuffer = function () {
  39883. if (!this.isReady()) {
  39884. return null;
  39885. }
  39886. return this._indexBuffer;
  39887. };
  39888. /** @hidden */
  39889. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39890. if (effect === void 0) { effect = null; }
  39891. if (!effect || !this._vertexArrayObjects) {
  39892. return;
  39893. }
  39894. if (this._vertexArrayObjects[effect.key]) {
  39895. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39896. delete this._vertexArrayObjects[effect.key];
  39897. }
  39898. };
  39899. /**
  39900. * Release the associated resources for a specific mesh
  39901. * @param mesh defines the source mesh
  39902. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39903. */
  39904. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39905. var meshes = this._meshes;
  39906. var index = meshes.indexOf(mesh);
  39907. if (index === -1) {
  39908. return;
  39909. }
  39910. meshes.splice(index, 1);
  39911. mesh._geometry = null;
  39912. if (meshes.length === 0 && shouldDispose) {
  39913. this.dispose();
  39914. }
  39915. };
  39916. /**
  39917. * Apply current geometry to a given mesh
  39918. * @param mesh defines the mesh to apply geometry to
  39919. */
  39920. Geometry.prototype.applyToMesh = function (mesh) {
  39921. if (mesh._geometry === this) {
  39922. return;
  39923. }
  39924. var previousGeometry = mesh._geometry;
  39925. if (previousGeometry) {
  39926. previousGeometry.releaseForMesh(mesh);
  39927. }
  39928. var meshes = this._meshes;
  39929. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39930. mesh._geometry = this;
  39931. this._scene.pushGeometry(this);
  39932. meshes.push(mesh);
  39933. if (this.isReady()) {
  39934. this._applyToMesh(mesh);
  39935. }
  39936. else {
  39937. mesh._boundingInfo = this._boundingInfo;
  39938. }
  39939. };
  39940. Geometry.prototype._updateExtend = function (data) {
  39941. if (data === void 0) { data = null; }
  39942. if (!data) {
  39943. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39944. }
  39945. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39946. };
  39947. Geometry.prototype._applyToMesh = function (mesh) {
  39948. var numOfMeshes = this._meshes.length;
  39949. // vertexBuffers
  39950. for (var kind in this._vertexBuffers) {
  39951. if (numOfMeshes === 1) {
  39952. this._vertexBuffers[kind].create();
  39953. }
  39954. var buffer = this._vertexBuffers[kind].getBuffer();
  39955. if (buffer)
  39956. buffer.references = numOfMeshes;
  39957. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39958. if (!this._extend) {
  39959. this._updateExtend();
  39960. }
  39961. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39962. mesh._createGlobalSubMesh(false);
  39963. //bounding info was just created again, world matrix should be applied again.
  39964. mesh._updateBoundingInfo();
  39965. }
  39966. }
  39967. // indexBuffer
  39968. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39969. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39970. }
  39971. if (this._indexBuffer) {
  39972. this._indexBuffer.references = numOfMeshes;
  39973. }
  39974. };
  39975. Geometry.prototype.notifyUpdate = function (kind) {
  39976. if (this.onGeometryUpdated) {
  39977. this.onGeometryUpdated(this, kind);
  39978. }
  39979. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39980. var mesh = _a[_i];
  39981. mesh._markSubMeshesAsAttributesDirty();
  39982. }
  39983. };
  39984. /**
  39985. * Load the geometry if it was flagged as delay loaded
  39986. * @param scene defines the hosting scene
  39987. * @param onLoaded defines a callback called when the geometry is loaded
  39988. */
  39989. Geometry.prototype.load = function (scene, onLoaded) {
  39990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39991. return;
  39992. }
  39993. if (this.isReady()) {
  39994. if (onLoaded) {
  39995. onLoaded();
  39996. }
  39997. return;
  39998. }
  39999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40000. this._queueLoad(scene, onLoaded);
  40001. };
  40002. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40003. var _this = this;
  40004. if (!this.delayLoadingFile) {
  40005. return;
  40006. }
  40007. scene._addPendingData(this);
  40008. scene._loadFile(this.delayLoadingFile, function (data) {
  40009. if (!_this._delayLoadingFunction) {
  40010. return;
  40011. }
  40012. _this._delayLoadingFunction(JSON.parse(data), _this);
  40013. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40014. _this._delayInfo = [];
  40015. scene._removePendingData(_this);
  40016. var meshes = _this._meshes;
  40017. var numOfMeshes = meshes.length;
  40018. for (var index = 0; index < numOfMeshes; index++) {
  40019. _this._applyToMesh(meshes[index]);
  40020. }
  40021. if (onLoaded) {
  40022. onLoaded();
  40023. }
  40024. }, undefined, true);
  40025. };
  40026. /**
  40027. * Invert the geometry to move from a right handed system to a left handed one.
  40028. */
  40029. Geometry.prototype.toLeftHanded = function () {
  40030. // Flip faces
  40031. var tIndices = this.getIndices(false);
  40032. if (tIndices != null && tIndices.length > 0) {
  40033. for (var i = 0; i < tIndices.length; i += 3) {
  40034. var tTemp = tIndices[i + 0];
  40035. tIndices[i + 0] = tIndices[i + 2];
  40036. tIndices[i + 2] = tTemp;
  40037. }
  40038. this.setIndices(tIndices);
  40039. }
  40040. // Negate position.z
  40041. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40042. if (tPositions != null && tPositions.length > 0) {
  40043. for (var i = 0; i < tPositions.length; i += 3) {
  40044. tPositions[i + 2] = -tPositions[i + 2];
  40045. }
  40046. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40047. }
  40048. // Negate normal.z
  40049. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40050. if (tNormals != null && tNormals.length > 0) {
  40051. for (var i = 0; i < tNormals.length; i += 3) {
  40052. tNormals[i + 2] = -tNormals[i + 2];
  40053. }
  40054. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40055. }
  40056. };
  40057. // Cache
  40058. /** @hidden */
  40059. Geometry.prototype._resetPointsArrayCache = function () {
  40060. this._positions = null;
  40061. };
  40062. /** @hidden */
  40063. Geometry.prototype._generatePointsArray = function () {
  40064. if (this._positions)
  40065. return true;
  40066. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40067. if (!data || data.length === 0) {
  40068. return false;
  40069. }
  40070. this._positions = [];
  40071. for (var index = 0; index < data.length; index += 3) {
  40072. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40073. }
  40074. return true;
  40075. };
  40076. /**
  40077. * Gets a value indicating if the geometry is disposed
  40078. * @returns true if the geometry was disposed
  40079. */
  40080. Geometry.prototype.isDisposed = function () {
  40081. return this._isDisposed;
  40082. };
  40083. Geometry.prototype._disposeVertexArrayObjects = function () {
  40084. if (this._vertexArrayObjects) {
  40085. for (var kind in this._vertexArrayObjects) {
  40086. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40087. }
  40088. this._vertexArrayObjects = {};
  40089. }
  40090. };
  40091. /**
  40092. * Free all associated resources
  40093. */
  40094. Geometry.prototype.dispose = function () {
  40095. var meshes = this._meshes;
  40096. var numOfMeshes = meshes.length;
  40097. var index;
  40098. for (index = 0; index < numOfMeshes; index++) {
  40099. this.releaseForMesh(meshes[index]);
  40100. }
  40101. this._meshes = [];
  40102. this._disposeVertexArrayObjects();
  40103. for (var kind in this._vertexBuffers) {
  40104. this._vertexBuffers[kind].dispose();
  40105. }
  40106. this._vertexBuffers = {};
  40107. this._totalVertices = 0;
  40108. if (this._indexBuffer) {
  40109. this._engine._releaseBuffer(this._indexBuffer);
  40110. }
  40111. this._indexBuffer = null;
  40112. this._indices = [];
  40113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40114. this.delayLoadingFile = null;
  40115. this._delayLoadingFunction = null;
  40116. this._delayInfo = [];
  40117. this._boundingInfo = null;
  40118. this._scene.removeGeometry(this);
  40119. this._isDisposed = true;
  40120. };
  40121. /**
  40122. * Clone the current geometry into a new geometry
  40123. * @param id defines the unique ID of the new geometry
  40124. * @returns a new geometry object
  40125. */
  40126. Geometry.prototype.copy = function (id) {
  40127. var vertexData = new BABYLON.VertexData();
  40128. vertexData.indices = [];
  40129. var indices = this.getIndices();
  40130. if (indices) {
  40131. for (var index = 0; index < indices.length; index++) {
  40132. vertexData.indices.push(indices[index]);
  40133. }
  40134. }
  40135. var updatable = false;
  40136. var stopChecking = false;
  40137. var kind;
  40138. for (kind in this._vertexBuffers) {
  40139. // using slice() to make a copy of the array and not just reference it
  40140. var data = this.getVerticesData(kind);
  40141. if (data instanceof Float32Array) {
  40142. vertexData.set(new Float32Array(data), kind);
  40143. }
  40144. else {
  40145. vertexData.set(data.slice(0), kind);
  40146. }
  40147. if (!stopChecking) {
  40148. var vb = this.getVertexBuffer(kind);
  40149. if (vb) {
  40150. updatable = vb.isUpdatable();
  40151. stopChecking = !updatable;
  40152. }
  40153. }
  40154. }
  40155. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40156. geometry.delayLoadState = this.delayLoadState;
  40157. geometry.delayLoadingFile = this.delayLoadingFile;
  40158. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40159. for (kind in this._delayInfo) {
  40160. geometry._delayInfo = geometry._delayInfo || [];
  40161. geometry._delayInfo.push(kind);
  40162. }
  40163. // Bounding info
  40164. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40165. return geometry;
  40166. };
  40167. /**
  40168. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40169. * @return a JSON representation of the current geometry data (without the vertices data)
  40170. */
  40171. Geometry.prototype.serialize = function () {
  40172. var serializationObject = {};
  40173. serializationObject.id = this.id;
  40174. serializationObject.updatable = this._updatable;
  40175. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40176. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40177. }
  40178. return serializationObject;
  40179. };
  40180. Geometry.prototype.toNumberArray = function (origin) {
  40181. if (Array.isArray(origin)) {
  40182. return origin;
  40183. }
  40184. else {
  40185. return Array.prototype.slice.call(origin);
  40186. }
  40187. };
  40188. /**
  40189. * Serialize all vertices data into a JSON oject
  40190. * @returns a JSON representation of the current geometry data
  40191. */
  40192. Geometry.prototype.serializeVerticeData = function () {
  40193. var serializationObject = this.serialize();
  40194. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40195. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40196. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40197. serializationObject.positions._updatable = true;
  40198. }
  40199. }
  40200. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40201. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40202. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40203. serializationObject.normals._updatable = true;
  40204. }
  40205. }
  40206. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40207. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40208. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40209. serializationObject.tangets._updatable = true;
  40210. }
  40211. }
  40212. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40213. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40214. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40215. serializationObject.uvs._updatable = true;
  40216. }
  40217. }
  40218. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40219. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40220. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40221. serializationObject.uv2s._updatable = true;
  40222. }
  40223. }
  40224. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40225. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40226. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40227. serializationObject.uv3s._updatable = true;
  40228. }
  40229. }
  40230. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40231. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40232. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40233. serializationObject.uv4s._updatable = true;
  40234. }
  40235. }
  40236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40237. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40239. serializationObject.uv5s._updatable = true;
  40240. }
  40241. }
  40242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40243. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40244. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40245. serializationObject.uv6s._updatable = true;
  40246. }
  40247. }
  40248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40249. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40250. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40251. serializationObject.colors._updatable = true;
  40252. }
  40253. }
  40254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40255. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40256. serializationObject.matricesIndices._isExpanded = true;
  40257. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40258. serializationObject.matricesIndices._updatable = true;
  40259. }
  40260. }
  40261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40262. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40263. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40264. serializationObject.matricesWeights._updatable = true;
  40265. }
  40266. }
  40267. serializationObject.indices = this.toNumberArray(this.getIndices());
  40268. return serializationObject;
  40269. };
  40270. // Statics
  40271. /**
  40272. * Extracts a clone of a mesh geometry
  40273. * @param mesh defines the source mesh
  40274. * @param id defines the unique ID of the new geometry object
  40275. * @returns the new geometry object
  40276. */
  40277. Geometry.ExtractFromMesh = function (mesh, id) {
  40278. var geometry = mesh._geometry;
  40279. if (!geometry) {
  40280. return null;
  40281. }
  40282. return geometry.copy(id);
  40283. };
  40284. /**
  40285. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40286. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40287. * Be aware Math.random() could cause collisions, but:
  40288. * "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"
  40289. * @returns a string containing a new GUID
  40290. */
  40291. Geometry.RandomId = function () {
  40292. return BABYLON.Tools.RandomId();
  40293. };
  40294. /** @hidden */
  40295. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40296. var scene = mesh.getScene();
  40297. // Geometry
  40298. var geometryId = parsedGeometry.geometryId;
  40299. if (geometryId) {
  40300. var geometry = scene.getGeometryByID(geometryId);
  40301. if (geometry) {
  40302. geometry.applyToMesh(mesh);
  40303. }
  40304. }
  40305. else if (parsedGeometry instanceof ArrayBuffer) {
  40306. var binaryInfo = mesh._binaryInfo;
  40307. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40308. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40309. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40310. }
  40311. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40312. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40313. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40314. }
  40315. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40316. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40317. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40318. }
  40319. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40320. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40321. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40322. }
  40323. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40324. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40325. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40326. }
  40327. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40328. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40329. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40330. }
  40331. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40332. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40333. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40334. }
  40335. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40336. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40337. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40338. }
  40339. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40340. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40341. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40342. }
  40343. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40344. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40345. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40346. }
  40347. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40348. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40349. var floatIndices = [];
  40350. for (var i = 0; i < matricesIndicesData.length; i++) {
  40351. var index = matricesIndicesData[i];
  40352. floatIndices.push(index & 0x000000FF);
  40353. floatIndices.push((index & 0x0000FF00) >> 8);
  40354. floatIndices.push((index & 0x00FF0000) >> 16);
  40355. floatIndices.push(index >> 24);
  40356. }
  40357. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40358. }
  40359. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40360. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40361. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40362. }
  40363. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40364. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40365. mesh.setIndices(indicesData, null);
  40366. }
  40367. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40368. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40369. mesh.subMeshes = [];
  40370. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40371. var materialIndex = subMeshesData[(i * 5) + 0];
  40372. var verticesStart = subMeshesData[(i * 5) + 1];
  40373. var verticesCount = subMeshesData[(i * 5) + 2];
  40374. var indexStart = subMeshesData[(i * 5) + 3];
  40375. var indexCount = subMeshesData[(i * 5) + 4];
  40376. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40377. }
  40378. }
  40379. }
  40380. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40381. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40382. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40383. if (parsedGeometry.tangents) {
  40384. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40385. }
  40386. if (parsedGeometry.uvs) {
  40387. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40388. }
  40389. if (parsedGeometry.uvs2) {
  40390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40391. }
  40392. if (parsedGeometry.uvs3) {
  40393. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40394. }
  40395. if (parsedGeometry.uvs4) {
  40396. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40397. }
  40398. if (parsedGeometry.uvs5) {
  40399. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40400. }
  40401. if (parsedGeometry.uvs6) {
  40402. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40403. }
  40404. if (parsedGeometry.colors) {
  40405. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40406. }
  40407. if (parsedGeometry.matricesIndices) {
  40408. if (!parsedGeometry.matricesIndices._isExpanded) {
  40409. var floatIndices = [];
  40410. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40411. var matricesIndex = parsedGeometry.matricesIndices[i];
  40412. floatIndices.push(matricesIndex & 0x000000FF);
  40413. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40414. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40415. floatIndices.push(matricesIndex >> 24);
  40416. }
  40417. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40418. }
  40419. else {
  40420. delete parsedGeometry.matricesIndices._isExpanded;
  40421. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40422. }
  40423. }
  40424. if (parsedGeometry.matricesIndicesExtra) {
  40425. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40426. var floatIndices = [];
  40427. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40428. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40429. floatIndices.push(matricesIndex & 0x000000FF);
  40430. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40431. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40432. floatIndices.push(matricesIndex >> 24);
  40433. }
  40434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40435. }
  40436. else {
  40437. delete parsedGeometry.matricesIndices._isExpanded;
  40438. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40439. }
  40440. }
  40441. if (parsedGeometry.matricesWeights) {
  40442. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40443. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40444. }
  40445. if (parsedGeometry.matricesWeightsExtra) {
  40446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40447. }
  40448. mesh.setIndices(parsedGeometry.indices, null);
  40449. }
  40450. // SubMeshes
  40451. if (parsedGeometry.subMeshes) {
  40452. mesh.subMeshes = [];
  40453. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40454. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40455. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40456. }
  40457. }
  40458. // Flat shading
  40459. if (mesh._shouldGenerateFlatShading) {
  40460. mesh.convertToFlatShadedMesh();
  40461. delete mesh._shouldGenerateFlatShading;
  40462. }
  40463. // Update
  40464. mesh.computeWorldMatrix(true);
  40465. scene.onMeshImportedObservable.notifyObservers(mesh);
  40466. };
  40467. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40468. var epsilon = 1e-3;
  40469. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40470. return;
  40471. }
  40472. var noInfluenceBoneIndex = 0.0;
  40473. if (parsedGeometry.skeletonId > -1) {
  40474. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40475. if (!skeleton) {
  40476. return;
  40477. }
  40478. noInfluenceBoneIndex = skeleton.bones.length;
  40479. }
  40480. else {
  40481. return;
  40482. }
  40483. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40484. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40485. var matricesWeights = parsedGeometry.matricesWeights;
  40486. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40487. var influencers = parsedGeometry.numBoneInfluencer;
  40488. var size = matricesWeights.length;
  40489. for (var i = 0; i < size; i += 4) {
  40490. var weight = 0.0;
  40491. var firstZeroWeight = -1;
  40492. for (var j = 0; j < 4; j++) {
  40493. var w = matricesWeights[i + j];
  40494. weight += w;
  40495. if (w < epsilon && firstZeroWeight < 0) {
  40496. firstZeroWeight = j;
  40497. }
  40498. }
  40499. if (matricesWeightsExtra) {
  40500. for (var j = 0; j < 4; j++) {
  40501. var w = matricesWeightsExtra[i + j];
  40502. weight += w;
  40503. if (w < epsilon && firstZeroWeight < 0) {
  40504. firstZeroWeight = j + 4;
  40505. }
  40506. }
  40507. }
  40508. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40509. firstZeroWeight = influencers - 1;
  40510. }
  40511. if (weight > epsilon) {
  40512. var mweight = 1.0 / weight;
  40513. for (var j = 0; j < 4; j++) {
  40514. matricesWeights[i + j] *= mweight;
  40515. }
  40516. if (matricesWeightsExtra) {
  40517. for (var j = 0; j < 4; j++) {
  40518. matricesWeightsExtra[i + j] *= mweight;
  40519. }
  40520. }
  40521. }
  40522. else {
  40523. if (firstZeroWeight >= 4) {
  40524. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40525. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40526. }
  40527. else {
  40528. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40529. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40530. }
  40531. }
  40532. }
  40533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40534. if (parsedGeometry.matricesWeightsExtra) {
  40535. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40536. }
  40537. };
  40538. /**
  40539. * Create a new geometry from persisted data (Using .babylon file format)
  40540. * @param parsedVertexData defines the persisted data
  40541. * @param scene defines the hosting scene
  40542. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40543. * @returns the new geometry object
  40544. */
  40545. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40546. if (scene.getGeometryByID(parsedVertexData.id)) {
  40547. return null; // null since geometry could be something else than a box...
  40548. }
  40549. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40550. if (BABYLON.Tags) {
  40551. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40552. }
  40553. if (parsedVertexData.delayLoadingFile) {
  40554. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40555. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40556. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40557. geometry._delayInfo = [];
  40558. if (parsedVertexData.hasUVs) {
  40559. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40560. }
  40561. if (parsedVertexData.hasUVs2) {
  40562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40563. }
  40564. if (parsedVertexData.hasUVs3) {
  40565. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40566. }
  40567. if (parsedVertexData.hasUVs4) {
  40568. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40569. }
  40570. if (parsedVertexData.hasUVs5) {
  40571. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40572. }
  40573. if (parsedVertexData.hasUVs6) {
  40574. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40575. }
  40576. if (parsedVertexData.hasColors) {
  40577. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40578. }
  40579. if (parsedVertexData.hasMatricesIndices) {
  40580. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40581. }
  40582. if (parsedVertexData.hasMatricesWeights) {
  40583. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40584. }
  40585. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40586. }
  40587. else {
  40588. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40589. }
  40590. scene.pushGeometry(geometry, true);
  40591. return geometry;
  40592. };
  40593. return Geometry;
  40594. }());
  40595. BABYLON.Geometry = Geometry;
  40596. // Primitives
  40597. /// Abstract class
  40598. /**
  40599. * Abstract class used to provide common services for all typed geometries
  40600. * @hidden
  40601. */
  40602. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40603. __extends(_PrimitiveGeometry, _super);
  40604. /**
  40605. * Creates a new typed geometry
  40606. * @param id defines the unique ID of the geometry
  40607. * @param scene defines the hosting scene
  40608. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40609. * @param mesh defines the hosting mesh (can be null)
  40610. */
  40611. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40612. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40613. if (mesh === void 0) { mesh = null; }
  40614. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40615. _this._canBeRegenerated = _canBeRegenerated;
  40616. _this._beingRegenerated = true;
  40617. _this.regenerate();
  40618. _this._beingRegenerated = false;
  40619. return _this;
  40620. }
  40621. /**
  40622. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40623. * @returns true if the geometry can be regenerated
  40624. */
  40625. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40626. return this._canBeRegenerated;
  40627. };
  40628. /**
  40629. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40630. */
  40631. _PrimitiveGeometry.prototype.regenerate = function () {
  40632. if (!this._canBeRegenerated) {
  40633. return;
  40634. }
  40635. this._beingRegenerated = true;
  40636. this.setAllVerticesData(this._regenerateVertexData(), false);
  40637. this._beingRegenerated = false;
  40638. };
  40639. /**
  40640. * Clone the geometry
  40641. * @param id defines the unique ID of the new geometry
  40642. * @returns the new geometry
  40643. */
  40644. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40645. return _super.prototype.copy.call(this, id);
  40646. };
  40647. // overrides
  40648. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40649. if (!this._beingRegenerated) {
  40650. return;
  40651. }
  40652. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40653. };
  40654. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40655. if (!this._beingRegenerated) {
  40656. return;
  40657. }
  40658. _super.prototype.setVerticesData.call(this, kind, data, false);
  40659. };
  40660. // to override
  40661. /** @hidden */
  40662. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40663. throw new Error("Abstract method");
  40664. };
  40665. _PrimitiveGeometry.prototype.copy = function (id) {
  40666. throw new Error("Must be overriden in sub-classes.");
  40667. };
  40668. _PrimitiveGeometry.prototype.serialize = function () {
  40669. var serializationObject = _super.prototype.serialize.call(this);
  40670. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40671. return serializationObject;
  40672. };
  40673. return _PrimitiveGeometry;
  40674. }(Geometry));
  40675. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40676. /**
  40677. * Creates a ribbon geometry
  40678. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40679. */
  40680. var RibbonGeometry = /** @class */ (function (_super) {
  40681. __extends(RibbonGeometry, _super);
  40682. /**
  40683. * Creates a ribbon geometry
  40684. * @param id defines the unique ID of the geometry
  40685. * @param scene defines the hosting scene
  40686. * @param pathArray defines the array of paths to use
  40687. * @param closeArray defines if the last path and the first path must be joined
  40688. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40689. * @param offset defines the offset between points
  40690. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40691. * @param mesh defines the hosting mesh (can be null)
  40692. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40693. */
  40694. function RibbonGeometry(id, scene,
  40695. /**
  40696. * Defines the array of paths to use
  40697. */
  40698. pathArray,
  40699. /**
  40700. * Defines if the last and first points of each path in your pathArray must be joined
  40701. */
  40702. closeArray,
  40703. /**
  40704. * Defines if the last and first points of each path in your pathArray must be joined
  40705. */
  40706. closePath,
  40707. /**
  40708. * Defines the offset between points
  40709. */
  40710. offset, canBeRegenerated, mesh,
  40711. /**
  40712. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40713. */
  40714. side) {
  40715. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40716. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40717. _this.pathArray = pathArray;
  40718. _this.closeArray = closeArray;
  40719. _this.closePath = closePath;
  40720. _this.offset = offset;
  40721. _this.side = side;
  40722. return _this;
  40723. }
  40724. /** @hidden */
  40725. RibbonGeometry.prototype._regenerateVertexData = function () {
  40726. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40727. };
  40728. RibbonGeometry.prototype.copy = function (id) {
  40729. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40730. };
  40731. return RibbonGeometry;
  40732. }(_PrimitiveGeometry));
  40733. BABYLON.RibbonGeometry = RibbonGeometry;
  40734. /**
  40735. * Creates a box geometry
  40736. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40737. */
  40738. var BoxGeometry = /** @class */ (function (_super) {
  40739. __extends(BoxGeometry, _super);
  40740. /**
  40741. * Creates a box geometry
  40742. * @param id defines the unique ID of the geometry
  40743. * @param scene defines the hosting scene
  40744. * @param size defines the zise of the box (width, height and depth are the same)
  40745. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40746. * @param mesh defines the hosting mesh (can be null)
  40747. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40748. */
  40749. function BoxGeometry(id, scene,
  40750. /**
  40751. * Defines the zise of the box (width, height and depth are the same)
  40752. */
  40753. size, canBeRegenerated, mesh,
  40754. /**
  40755. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40756. */
  40757. side) {
  40758. if (mesh === void 0) { mesh = null; }
  40759. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40760. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40761. _this.size = size;
  40762. _this.side = side;
  40763. return _this;
  40764. }
  40765. /** @hidden */
  40766. BoxGeometry.prototype._regenerateVertexData = function () {
  40767. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40768. };
  40769. BoxGeometry.prototype.copy = function (id) {
  40770. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40771. };
  40772. BoxGeometry.prototype.serialize = function () {
  40773. var serializationObject = _super.prototype.serialize.call(this);
  40774. serializationObject.size = this.size;
  40775. return serializationObject;
  40776. };
  40777. BoxGeometry.Parse = function (parsedBox, scene) {
  40778. if (scene.getGeometryByID(parsedBox.id)) {
  40779. return null; // null since geometry could be something else than a box...
  40780. }
  40781. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40782. if (BABYLON.Tags) {
  40783. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40784. }
  40785. scene.pushGeometry(box, true);
  40786. return box;
  40787. };
  40788. return BoxGeometry;
  40789. }(_PrimitiveGeometry));
  40790. BABYLON.BoxGeometry = BoxGeometry;
  40791. /**
  40792. * Creates a sphere geometry
  40793. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40794. */
  40795. var SphereGeometry = /** @class */ (function (_super) {
  40796. __extends(SphereGeometry, _super);
  40797. /**
  40798. * Create a new sphere geometry
  40799. * @param id defines the unique ID of the geometry
  40800. * @param scene defines the hosting scene
  40801. * @param segments defines the number of segments to use to create the sphere
  40802. * @param diameter defines the diameter of the sphere
  40803. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40804. * @param mesh defines the hosting mesh (can be null)
  40805. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40806. */
  40807. function SphereGeometry(id, scene,
  40808. /**
  40809. * Defines the number of segments to use to create the sphere
  40810. */
  40811. segments,
  40812. /**
  40813. * Defines the diameter of the sphere
  40814. */
  40815. diameter, canBeRegenerated, mesh,
  40816. /**
  40817. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40818. */
  40819. side) {
  40820. if (mesh === void 0) { mesh = null; }
  40821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40822. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40823. _this.segments = segments;
  40824. _this.diameter = diameter;
  40825. _this.side = side;
  40826. return _this;
  40827. }
  40828. /** @hidden */
  40829. SphereGeometry.prototype._regenerateVertexData = function () {
  40830. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40831. };
  40832. SphereGeometry.prototype.copy = function (id) {
  40833. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40834. };
  40835. SphereGeometry.prototype.serialize = function () {
  40836. var serializationObject = _super.prototype.serialize.call(this);
  40837. serializationObject.segments = this.segments;
  40838. serializationObject.diameter = this.diameter;
  40839. return serializationObject;
  40840. };
  40841. SphereGeometry.Parse = function (parsedSphere, scene) {
  40842. if (scene.getGeometryByID(parsedSphere.id)) {
  40843. return null; // null since geometry could be something else than a sphere...
  40844. }
  40845. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40846. if (BABYLON.Tags) {
  40847. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40848. }
  40849. scene.pushGeometry(sphere, true);
  40850. return sphere;
  40851. };
  40852. return SphereGeometry;
  40853. }(_PrimitiveGeometry));
  40854. BABYLON.SphereGeometry = SphereGeometry;
  40855. /**
  40856. * Creates a disc geometry
  40857. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40858. */
  40859. var DiscGeometry = /** @class */ (function (_super) {
  40860. __extends(DiscGeometry, _super);
  40861. /**
  40862. * Creates a new disc geometry
  40863. * @param id defines the unique ID of the geometry
  40864. * @param scene defines the hosting scene
  40865. * @param radius defines the radius of the disc
  40866. * @param tessellation defines the tesselation factor to apply to the disc
  40867. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40868. * @param mesh defines the hosting mesh (can be null)
  40869. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40870. */
  40871. function DiscGeometry(id, scene,
  40872. /**
  40873. * Defines the radius of the disc
  40874. */
  40875. radius,
  40876. /**
  40877. * Defines the tesselation factor to apply to the disc
  40878. */
  40879. tessellation, canBeRegenerated, mesh,
  40880. /**
  40881. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40882. */
  40883. side) {
  40884. if (mesh === void 0) { mesh = null; }
  40885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40887. _this.radius = radius;
  40888. _this.tessellation = tessellation;
  40889. _this.side = side;
  40890. return _this;
  40891. }
  40892. /** @hidden */
  40893. DiscGeometry.prototype._regenerateVertexData = function () {
  40894. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40895. };
  40896. DiscGeometry.prototype.copy = function (id) {
  40897. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40898. };
  40899. return DiscGeometry;
  40900. }(_PrimitiveGeometry));
  40901. BABYLON.DiscGeometry = DiscGeometry;
  40902. /**
  40903. * Creates a new cylinder geometry
  40904. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40905. */
  40906. var CylinderGeometry = /** @class */ (function (_super) {
  40907. __extends(CylinderGeometry, _super);
  40908. /**
  40909. * Creates a new cylinder geometry
  40910. * @param id defines the unique ID of the geometry
  40911. * @param scene defines the hosting scene
  40912. * @param height defines the height of the cylinder
  40913. * @param diameterTop defines the diameter of the cylinder's top cap
  40914. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40915. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40916. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40917. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40918. * @param mesh defines the hosting mesh (can be null)
  40919. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40920. */
  40921. function CylinderGeometry(id, scene,
  40922. /**
  40923. * Defines the height of the cylinder
  40924. */
  40925. height,
  40926. /**
  40927. * Defines the diameter of the cylinder's top cap
  40928. */
  40929. diameterTop,
  40930. /**
  40931. * Defines the diameter of the cylinder's bottom cap
  40932. */
  40933. diameterBottom,
  40934. /**
  40935. * Defines the tessellation factor to apply to the cylinder
  40936. */
  40937. tessellation,
  40938. /**
  40939. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40940. */
  40941. subdivisions, canBeRegenerated, mesh,
  40942. /**
  40943. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40944. */
  40945. side) {
  40946. if (subdivisions === void 0) { subdivisions = 1; }
  40947. if (mesh === void 0) { mesh = null; }
  40948. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40949. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40950. _this.height = height;
  40951. _this.diameterTop = diameterTop;
  40952. _this.diameterBottom = diameterBottom;
  40953. _this.tessellation = tessellation;
  40954. _this.subdivisions = subdivisions;
  40955. _this.side = side;
  40956. return _this;
  40957. }
  40958. /** @hidden */
  40959. CylinderGeometry.prototype._regenerateVertexData = function () {
  40960. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40961. };
  40962. CylinderGeometry.prototype.copy = function (id) {
  40963. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40964. };
  40965. CylinderGeometry.prototype.serialize = function () {
  40966. var serializationObject = _super.prototype.serialize.call(this);
  40967. serializationObject.height = this.height;
  40968. serializationObject.diameterTop = this.diameterTop;
  40969. serializationObject.diameterBottom = this.diameterBottom;
  40970. serializationObject.tessellation = this.tessellation;
  40971. return serializationObject;
  40972. };
  40973. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40974. if (scene.getGeometryByID(parsedCylinder.id)) {
  40975. return null; // null since geometry could be something else than a cylinder...
  40976. }
  40977. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40978. if (BABYLON.Tags) {
  40979. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40980. }
  40981. scene.pushGeometry(cylinder, true);
  40982. return cylinder;
  40983. };
  40984. return CylinderGeometry;
  40985. }(_PrimitiveGeometry));
  40986. BABYLON.CylinderGeometry = CylinderGeometry;
  40987. /**
  40988. * Creates a new torus geometry
  40989. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40990. */
  40991. var TorusGeometry = /** @class */ (function (_super) {
  40992. __extends(TorusGeometry, _super);
  40993. /**
  40994. * Creates a new torus geometry
  40995. * @param id defines the unique ID of the geometry
  40996. * @param scene defines the hosting scene
  40997. * @param diameter defines the diameter of the torus
  40998. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40999. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41000. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41001. * @param mesh defines the hosting mesh (can be null)
  41002. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41003. */
  41004. function TorusGeometry(id, scene,
  41005. /**
  41006. * Defines the diameter of the torus
  41007. */
  41008. diameter,
  41009. /**
  41010. * Defines the thickness of the torus (ie. internal diameter)
  41011. */
  41012. thickness,
  41013. /**
  41014. * Defines the tesselation factor to apply to the torus
  41015. */
  41016. tessellation, canBeRegenerated, mesh,
  41017. /**
  41018. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41019. */
  41020. side) {
  41021. if (mesh === void 0) { mesh = null; }
  41022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41024. _this.diameter = diameter;
  41025. _this.thickness = thickness;
  41026. _this.tessellation = tessellation;
  41027. _this.side = side;
  41028. return _this;
  41029. }
  41030. /** @hidden */
  41031. TorusGeometry.prototype._regenerateVertexData = function () {
  41032. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41033. };
  41034. TorusGeometry.prototype.copy = function (id) {
  41035. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41036. };
  41037. TorusGeometry.prototype.serialize = function () {
  41038. var serializationObject = _super.prototype.serialize.call(this);
  41039. serializationObject.diameter = this.diameter;
  41040. serializationObject.thickness = this.thickness;
  41041. serializationObject.tessellation = this.tessellation;
  41042. return serializationObject;
  41043. };
  41044. TorusGeometry.Parse = function (parsedTorus, scene) {
  41045. if (scene.getGeometryByID(parsedTorus.id)) {
  41046. return null; // null since geometry could be something else than a torus...
  41047. }
  41048. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41049. if (BABYLON.Tags) {
  41050. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41051. }
  41052. scene.pushGeometry(torus, true);
  41053. return torus;
  41054. };
  41055. return TorusGeometry;
  41056. }(_PrimitiveGeometry));
  41057. BABYLON.TorusGeometry = TorusGeometry;
  41058. /**
  41059. * Creates a new ground geometry
  41060. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41061. */
  41062. var GroundGeometry = /** @class */ (function (_super) {
  41063. __extends(GroundGeometry, _super);
  41064. /**
  41065. * Creates a new ground geometry
  41066. * @param id defines the unique ID of the geometry
  41067. * @param scene defines the hosting scene
  41068. * @param width defines the width of the ground
  41069. * @param height defines the height of the ground
  41070. * @param subdivisions defines the subdivisions to apply to the ground
  41071. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41072. * @param mesh defines the hosting mesh (can be null)
  41073. */
  41074. function GroundGeometry(id, scene,
  41075. /**
  41076. * Defines the width of the ground
  41077. */
  41078. width,
  41079. /**
  41080. * Defines the height of the ground
  41081. */
  41082. height,
  41083. /**
  41084. * Defines the subdivisions to apply to the ground
  41085. */
  41086. subdivisions, canBeRegenerated, mesh) {
  41087. if (mesh === void 0) { mesh = null; }
  41088. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41089. _this.width = width;
  41090. _this.height = height;
  41091. _this.subdivisions = subdivisions;
  41092. return _this;
  41093. }
  41094. /** @hidden */
  41095. GroundGeometry.prototype._regenerateVertexData = function () {
  41096. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41097. };
  41098. GroundGeometry.prototype.copy = function (id) {
  41099. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41100. };
  41101. GroundGeometry.prototype.serialize = function () {
  41102. var serializationObject = _super.prototype.serialize.call(this);
  41103. serializationObject.width = this.width;
  41104. serializationObject.height = this.height;
  41105. serializationObject.subdivisions = this.subdivisions;
  41106. return serializationObject;
  41107. };
  41108. GroundGeometry.Parse = function (parsedGround, scene) {
  41109. if (scene.getGeometryByID(parsedGround.id)) {
  41110. return null; // null since geometry could be something else than a ground...
  41111. }
  41112. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41113. if (BABYLON.Tags) {
  41114. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41115. }
  41116. scene.pushGeometry(ground, true);
  41117. return ground;
  41118. };
  41119. return GroundGeometry;
  41120. }(_PrimitiveGeometry));
  41121. BABYLON.GroundGeometry = GroundGeometry;
  41122. /**
  41123. * Creates a tiled ground geometry
  41124. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41125. */
  41126. var TiledGroundGeometry = /** @class */ (function (_super) {
  41127. __extends(TiledGroundGeometry, _super);
  41128. /**
  41129. * Creates a tiled ground geometry
  41130. * @param id defines the unique ID of the geometry
  41131. * @param scene defines the hosting scene
  41132. * @param xmin defines the minimum value on X axis
  41133. * @param zmin defines the minimum value on Z axis
  41134. * @param xmax defines the maximum value on X axis
  41135. * @param zmax defines the maximum value on Z axis
  41136. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41137. * @param precision defines the precision to use when computing the tiles
  41138. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41139. * @param mesh defines the hosting mesh (can be null)
  41140. */
  41141. function TiledGroundGeometry(id, scene,
  41142. /**
  41143. * Defines the minimum value on X axis
  41144. */
  41145. xmin,
  41146. /**
  41147. * Defines the minimum value on Z axis
  41148. */
  41149. zmin,
  41150. /**
  41151. * Defines the maximum value on X axis
  41152. */
  41153. xmax,
  41154. /**
  41155. * Defines the maximum value on Z axis
  41156. */
  41157. zmax,
  41158. /**
  41159. * Defines the subdivisions to apply to the ground
  41160. */
  41161. subdivisions,
  41162. /**
  41163. * Defines the precision to use when computing the tiles
  41164. */
  41165. precision, canBeRegenerated, mesh) {
  41166. if (mesh === void 0) { mesh = null; }
  41167. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41168. _this.xmin = xmin;
  41169. _this.zmin = zmin;
  41170. _this.xmax = xmax;
  41171. _this.zmax = zmax;
  41172. _this.subdivisions = subdivisions;
  41173. _this.precision = precision;
  41174. return _this;
  41175. }
  41176. /** @hidden */
  41177. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41178. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41179. };
  41180. TiledGroundGeometry.prototype.copy = function (id) {
  41181. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41182. };
  41183. return TiledGroundGeometry;
  41184. }(_PrimitiveGeometry));
  41185. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41186. /**
  41187. * Creates a plane geometry
  41188. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41189. */
  41190. var PlaneGeometry = /** @class */ (function (_super) {
  41191. __extends(PlaneGeometry, _super);
  41192. /**
  41193. * Creates a plane geometry
  41194. * @param id defines the unique ID of the geometry
  41195. * @param scene defines the hosting scene
  41196. * @param size defines the size of the plane (width === height)
  41197. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41198. * @param mesh defines the hosting mesh (can be null)
  41199. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41200. */
  41201. function PlaneGeometry(id, scene,
  41202. /**
  41203. * Defines the size of the plane (width === height)
  41204. */
  41205. size, canBeRegenerated, mesh,
  41206. /**
  41207. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41208. */
  41209. side) {
  41210. if (mesh === void 0) { mesh = null; }
  41211. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41213. _this.size = size;
  41214. _this.side = side;
  41215. return _this;
  41216. }
  41217. /** @hidden */
  41218. PlaneGeometry.prototype._regenerateVertexData = function () {
  41219. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41220. };
  41221. PlaneGeometry.prototype.copy = function (id) {
  41222. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41223. };
  41224. PlaneGeometry.prototype.serialize = function () {
  41225. var serializationObject = _super.prototype.serialize.call(this);
  41226. serializationObject.size = this.size;
  41227. return serializationObject;
  41228. };
  41229. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41230. if (scene.getGeometryByID(parsedPlane.id)) {
  41231. return null; // null since geometry could be something else than a ground...
  41232. }
  41233. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41234. if (BABYLON.Tags) {
  41235. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41236. }
  41237. scene.pushGeometry(plane, true);
  41238. return plane;
  41239. };
  41240. return PlaneGeometry;
  41241. }(_PrimitiveGeometry));
  41242. BABYLON.PlaneGeometry = PlaneGeometry;
  41243. /**
  41244. * Creates a torus knot geometry
  41245. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41246. */
  41247. var TorusKnotGeometry = /** @class */ (function (_super) {
  41248. __extends(TorusKnotGeometry, _super);
  41249. /**
  41250. * Creates a torus knot geometry
  41251. * @param id defines the unique ID of the geometry
  41252. * @param scene defines the hosting scene
  41253. * @param radius defines the radius of the torus knot
  41254. * @param tube defines the thickness of the torus knot tube
  41255. * @param radialSegments defines the number of radial segments
  41256. * @param tubularSegments defines the number of tubular segments
  41257. * @param p defines the first number of windings
  41258. * @param q defines the second number of windings
  41259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41260. * @param mesh defines the hosting mesh (can be null)
  41261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41262. */
  41263. function TorusKnotGeometry(id, scene,
  41264. /**
  41265. * Defines the radius of the torus knot
  41266. */
  41267. radius,
  41268. /**
  41269. * Defines the thickness of the torus knot tube
  41270. */
  41271. tube,
  41272. /**
  41273. * Defines the number of radial segments
  41274. */
  41275. radialSegments,
  41276. /**
  41277. * Defines the number of tubular segments
  41278. */
  41279. tubularSegments,
  41280. /**
  41281. * Defines the first number of windings
  41282. */
  41283. p,
  41284. /**
  41285. * Defines the second number of windings
  41286. */
  41287. q, canBeRegenerated, mesh,
  41288. /**
  41289. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41290. */
  41291. side) {
  41292. if (mesh === void 0) { mesh = null; }
  41293. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41294. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41295. _this.radius = radius;
  41296. _this.tube = tube;
  41297. _this.radialSegments = radialSegments;
  41298. _this.tubularSegments = tubularSegments;
  41299. _this.p = p;
  41300. _this.q = q;
  41301. _this.side = side;
  41302. return _this;
  41303. }
  41304. /** @hidden */
  41305. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41306. 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 });
  41307. };
  41308. TorusKnotGeometry.prototype.copy = function (id) {
  41309. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41310. };
  41311. TorusKnotGeometry.prototype.serialize = function () {
  41312. var serializationObject = _super.prototype.serialize.call(this);
  41313. serializationObject.radius = this.radius;
  41314. serializationObject.tube = this.tube;
  41315. serializationObject.radialSegments = this.radialSegments;
  41316. serializationObject.tubularSegments = this.tubularSegments;
  41317. serializationObject.p = this.p;
  41318. serializationObject.q = this.q;
  41319. return serializationObject;
  41320. };
  41321. ;
  41322. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41323. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41324. return null; // null since geometry could be something else than a ground...
  41325. }
  41326. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41327. if (BABYLON.Tags) {
  41328. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41329. }
  41330. scene.pushGeometry(torusKnot, true);
  41331. return torusKnot;
  41332. };
  41333. return TorusKnotGeometry;
  41334. }(_PrimitiveGeometry));
  41335. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41336. //}
  41337. })(BABYLON || (BABYLON = {}));
  41338. //# sourceMappingURL=babylon.geometry.js.map
  41339. var BABYLON;
  41340. (function (BABYLON) {
  41341. /**
  41342. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41343. */
  41344. var PerformanceMonitor = /** @class */ (function () {
  41345. /**
  41346. * constructor
  41347. * @param frameSampleSize The number of samples required to saturate the sliding window
  41348. */
  41349. function PerformanceMonitor(frameSampleSize) {
  41350. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41351. this._enabled = true;
  41352. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41353. }
  41354. /**
  41355. * Samples current frame
  41356. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41357. */
  41358. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41359. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41360. if (!this._enabled)
  41361. return;
  41362. if (this._lastFrameTimeMs != null) {
  41363. var dt = timeMs - this._lastFrameTimeMs;
  41364. this._rollingFrameTime.add(dt);
  41365. }
  41366. this._lastFrameTimeMs = timeMs;
  41367. };
  41368. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41369. /**
  41370. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41371. */
  41372. get: function () {
  41373. return this._rollingFrameTime.average;
  41374. },
  41375. enumerable: true,
  41376. configurable: true
  41377. });
  41378. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41379. /**
  41380. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41381. */
  41382. get: function () {
  41383. return this._rollingFrameTime.variance;
  41384. },
  41385. enumerable: true,
  41386. configurable: true
  41387. });
  41388. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41389. /**
  41390. * Returns the frame time of the most recent frame
  41391. */
  41392. get: function () {
  41393. return this._rollingFrameTime.history(0);
  41394. },
  41395. enumerable: true,
  41396. configurable: true
  41397. });
  41398. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41399. /**
  41400. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41401. */
  41402. get: function () {
  41403. return 1000.0 / this._rollingFrameTime.average;
  41404. },
  41405. enumerable: true,
  41406. configurable: true
  41407. });
  41408. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41409. /**
  41410. * Returns the average framerate in frames per second using the most recent frame time
  41411. */
  41412. get: function () {
  41413. var history = this._rollingFrameTime.history(0);
  41414. if (history === 0) {
  41415. return 0;
  41416. }
  41417. return 1000.0 / history;
  41418. },
  41419. enumerable: true,
  41420. configurable: true
  41421. });
  41422. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41423. /**
  41424. * Returns true if enough samples have been taken to completely fill the sliding window
  41425. */
  41426. get: function () {
  41427. return this._rollingFrameTime.isSaturated();
  41428. },
  41429. enumerable: true,
  41430. configurable: true
  41431. });
  41432. /**
  41433. * Enables contributions to the sliding window sample set
  41434. */
  41435. PerformanceMonitor.prototype.enable = function () {
  41436. this._enabled = true;
  41437. };
  41438. /**
  41439. * Disables contributions to the sliding window sample set
  41440. * Samples will not be interpolated over the disabled period
  41441. */
  41442. PerformanceMonitor.prototype.disable = function () {
  41443. this._enabled = false;
  41444. //clear last sample to avoid interpolating over the disabled period when next enabled
  41445. this._lastFrameTimeMs = null;
  41446. };
  41447. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41448. /**
  41449. * Returns true if sampling is enabled
  41450. */
  41451. get: function () {
  41452. return this._enabled;
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. /**
  41458. * Resets performance monitor
  41459. */
  41460. PerformanceMonitor.prototype.reset = function () {
  41461. //clear last sample to avoid interpolating over the disabled period when next enabled
  41462. this._lastFrameTimeMs = null;
  41463. //wipe record
  41464. this._rollingFrameTime.reset();
  41465. };
  41466. return PerformanceMonitor;
  41467. }());
  41468. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41469. /**
  41470. * RollingAverage
  41471. *
  41472. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41473. */
  41474. var RollingAverage = /** @class */ (function () {
  41475. /**
  41476. * constructor
  41477. * @param length The number of samples required to saturate the sliding window
  41478. */
  41479. function RollingAverage(length) {
  41480. this._samples = new Array(length);
  41481. this.reset();
  41482. }
  41483. /**
  41484. * Adds a sample to the sample set
  41485. * @param v The sample value
  41486. */
  41487. RollingAverage.prototype.add = function (v) {
  41488. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41489. var delta;
  41490. //we need to check if we've already wrapped round
  41491. if (this.isSaturated()) {
  41492. //remove bottom of stack from mean
  41493. var bottomValue = this._samples[this._pos];
  41494. delta = bottomValue - this.average;
  41495. this.average -= delta / (this._sampleCount - 1);
  41496. this._m2 -= delta * (bottomValue - this.average);
  41497. }
  41498. else {
  41499. this._sampleCount++;
  41500. }
  41501. //add new value to mean
  41502. delta = v - this.average;
  41503. this.average += delta / (this._sampleCount);
  41504. this._m2 += delta * (v - this.average);
  41505. //set the new variance
  41506. this.variance = this._m2 / (this._sampleCount - 1);
  41507. this._samples[this._pos] = v;
  41508. this._pos++;
  41509. this._pos %= this._samples.length; //positive wrap around
  41510. };
  41511. /**
  41512. * Returns previously added values or null if outside of history or outside the sliding window domain
  41513. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41514. * @return Value previously recorded with add() or null if outside of range
  41515. */
  41516. RollingAverage.prototype.history = function (i) {
  41517. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41518. return 0;
  41519. }
  41520. var i0 = this._wrapPosition(this._pos - 1.0);
  41521. return this._samples[this._wrapPosition(i0 - i)];
  41522. };
  41523. /**
  41524. * Returns true if enough samples have been taken to completely fill the sliding window
  41525. * @return true if sample-set saturated
  41526. */
  41527. RollingAverage.prototype.isSaturated = function () {
  41528. return this._sampleCount >= this._samples.length;
  41529. };
  41530. /**
  41531. * Resets the rolling average (equivalent to 0 samples taken so far)
  41532. */
  41533. RollingAverage.prototype.reset = function () {
  41534. this.average = 0;
  41535. this.variance = 0;
  41536. this._sampleCount = 0;
  41537. this._pos = 0;
  41538. this._m2 = 0;
  41539. };
  41540. /**
  41541. * Wraps a value around the sample range boundaries
  41542. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41543. * @return Wrapped position in sample range
  41544. */
  41545. RollingAverage.prototype._wrapPosition = function (i) {
  41546. var max = this._samples.length;
  41547. return ((i % max) + max) % max;
  41548. };
  41549. return RollingAverage;
  41550. }());
  41551. BABYLON.RollingAverage = RollingAverage;
  41552. })(BABYLON || (BABYLON = {}));
  41553. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41554. var BABYLON;
  41555. (function (BABYLON) {
  41556. /**
  41557. * "Static Class" containing the most commonly used helper while dealing with material for
  41558. * rendering purpose.
  41559. *
  41560. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41561. *
  41562. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41563. */
  41564. var MaterialHelper = /** @class */ (function () {
  41565. function MaterialHelper() {
  41566. }
  41567. /**
  41568. * Bind the current view position to an effect.
  41569. * @param effect The effect to be bound
  41570. * @param scene The scene the eyes position is used from
  41571. */
  41572. MaterialHelper.BindEyePosition = function (effect, scene) {
  41573. if (scene._forcedViewPosition) {
  41574. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41575. return;
  41576. }
  41577. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41578. };
  41579. /**
  41580. * Helps preparing the defines values about the UVs in used in the effect.
  41581. * UVs are shared as much as we can accross channels in the shaders.
  41582. * @param texture The texture we are preparing the UVs for
  41583. * @param defines The defines to update
  41584. * @param key The channel key "diffuse", "specular"... used in the shader
  41585. */
  41586. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41587. defines._needUVs = true;
  41588. defines[key] = true;
  41589. if (texture.getTextureMatrix().isIdentity(true)) {
  41590. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41591. if (texture.coordinatesIndex === 0) {
  41592. defines["MAINUV1"] = true;
  41593. }
  41594. else {
  41595. defines["MAINUV2"] = true;
  41596. }
  41597. }
  41598. else {
  41599. defines[key + "DIRECTUV"] = 0;
  41600. }
  41601. };
  41602. /**
  41603. * Binds a texture matrix value to its corrsponding uniform
  41604. * @param texture The texture to bind the matrix for
  41605. * @param uniformBuffer The uniform buffer receivin the data
  41606. * @param key The channel key "diffuse", "specular"... used in the shader
  41607. */
  41608. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41609. var matrix = texture.getTextureMatrix();
  41610. if (!matrix.isIdentity(true)) {
  41611. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41612. }
  41613. };
  41614. /**
  41615. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41616. * @param mesh defines the current mesh
  41617. * @param scene defines the current scene
  41618. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41619. * @param pointsCloud defines if point cloud rendering has to be turned on
  41620. * @param fogEnabled defines if fog has to be turned on
  41621. * @param alphaTest defines if alpha testing has to be turned on
  41622. * @param defines defines the current list of defines
  41623. */
  41624. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41625. if (defines._areMiscDirty) {
  41626. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41627. defines["POINTSIZE"] = pointsCloud;
  41628. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41629. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41630. defines["ALPHATEST"] = alphaTest;
  41631. }
  41632. };
  41633. /**
  41634. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41635. * @param scene defines the current scene
  41636. * @param engine defines the current engine
  41637. * @param defines specifies the list of active defines
  41638. * @param useInstances defines if instances have to be turned on
  41639. * @param useClipPlane defines if clip plane have to be turned on
  41640. */
  41641. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41642. if (useClipPlane === void 0) { useClipPlane = null; }
  41643. var changed = false;
  41644. var useClipPlane1 = false;
  41645. var useClipPlane2 = false;
  41646. var useClipPlane3 = false;
  41647. var useClipPlane4 = false;
  41648. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41649. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41650. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41651. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41652. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41653. defines["CLIPPLANE"] = useClipPlane1;
  41654. changed = true;
  41655. }
  41656. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41657. defines["CLIPPLANE2"] = useClipPlane2;
  41658. changed = true;
  41659. }
  41660. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41661. defines["CLIPPLANE3"] = useClipPlane3;
  41662. changed = true;
  41663. }
  41664. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41665. defines["CLIPPLANE4"] = useClipPlane4;
  41666. changed = true;
  41667. }
  41668. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41669. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41670. changed = true;
  41671. }
  41672. if (defines["INSTANCES"] !== useInstances) {
  41673. defines["INSTANCES"] = useInstances;
  41674. changed = true;
  41675. }
  41676. if (changed) {
  41677. defines.markAsUnprocessed();
  41678. }
  41679. };
  41680. /**
  41681. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41682. * @param mesh The mesh containing the geometry data we will draw
  41683. * @param defines The defines to update
  41684. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41685. * @param useBones Precise whether bones should be used or not (override mesh info)
  41686. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41687. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41688. * @returns false if defines are considered not dirty and have not been checked
  41689. */
  41690. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41691. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41692. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41693. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41694. return false;
  41695. }
  41696. defines._normals = defines._needNormals;
  41697. defines._uvs = defines._needUVs;
  41698. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41699. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41700. defines["TANGENT"] = true;
  41701. }
  41702. if (defines._needUVs) {
  41703. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41704. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41705. }
  41706. else {
  41707. defines["UV1"] = false;
  41708. defines["UV2"] = false;
  41709. }
  41710. if (useVertexColor) {
  41711. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41712. defines["VERTEXCOLOR"] = hasVertexColors;
  41713. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41714. }
  41715. if (useBones) {
  41716. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41717. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41718. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41719. }
  41720. else {
  41721. defines["NUM_BONE_INFLUENCERS"] = 0;
  41722. defines["BonesPerMesh"] = 0;
  41723. }
  41724. }
  41725. if (useMorphTargets) {
  41726. var manager = mesh.morphTargetManager;
  41727. if (manager) {
  41728. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41729. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41730. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41731. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41732. }
  41733. else {
  41734. defines["MORPHTARGETS_TANGENT"] = false;
  41735. defines["MORPHTARGETS_NORMAL"] = false;
  41736. defines["MORPHTARGETS"] = false;
  41737. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41738. }
  41739. }
  41740. return true;
  41741. };
  41742. /**
  41743. * Prepares the defines related to the light information passed in parameter
  41744. * @param scene The scene we are intending to draw
  41745. * @param mesh The mesh the effect is compiling for
  41746. * @param defines The defines to update
  41747. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41748. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41749. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41750. * @returns true if normals will be required for the rest of the effect
  41751. */
  41752. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41753. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41754. if (disableLighting === void 0) { disableLighting = false; }
  41755. if (!defines._areLightsDirty) {
  41756. return defines._needNormals;
  41757. }
  41758. var lightIndex = 0;
  41759. var needNormals = false;
  41760. var needRebuild = false;
  41761. var lightmapMode = false;
  41762. var shadowEnabled = false;
  41763. var specularEnabled = false;
  41764. if (scene.lightsEnabled && !disableLighting) {
  41765. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41766. var light = _a[_i];
  41767. needNormals = true;
  41768. if (defines["LIGHT" + lightIndex] === undefined) {
  41769. needRebuild = true;
  41770. }
  41771. defines["LIGHT" + lightIndex] = true;
  41772. defines["SPOTLIGHT" + lightIndex] = false;
  41773. defines["HEMILIGHT" + lightIndex] = false;
  41774. defines["POINTLIGHT" + lightIndex] = false;
  41775. defines["DIRLIGHT" + lightIndex] = false;
  41776. light.prepareLightSpecificDefines(defines, lightIndex);
  41777. // FallOff.
  41778. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41779. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41780. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41781. switch (light.falloffType) {
  41782. case BABYLON.Light.FALLOFF_GLTF:
  41783. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41784. break;
  41785. case BABYLON.Light.FALLOFF_PHYSICAL:
  41786. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41787. break;
  41788. case BABYLON.Light.FALLOFF_STANDARD:
  41789. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41790. break;
  41791. }
  41792. // Specular
  41793. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41794. specularEnabled = true;
  41795. }
  41796. // Shadows
  41797. defines["SHADOW" + lightIndex] = false;
  41798. defines["SHADOWPCF" + lightIndex] = false;
  41799. defines["SHADOWPCSS" + lightIndex] = false;
  41800. defines["SHADOWPOISSON" + lightIndex] = false;
  41801. defines["SHADOWESM" + lightIndex] = false;
  41802. defines["SHADOWCUBE" + lightIndex] = false;
  41803. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41804. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41805. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41806. var shadowGenerator = light.getShadowGenerator();
  41807. if (shadowGenerator) {
  41808. var shadowMap = shadowGenerator.getShadowMap();
  41809. if (shadowMap) {
  41810. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41811. shadowEnabled = true;
  41812. shadowGenerator.prepareDefines(defines, lightIndex);
  41813. }
  41814. }
  41815. }
  41816. }
  41817. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41818. lightmapMode = true;
  41819. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41820. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41821. }
  41822. else {
  41823. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41824. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41825. }
  41826. lightIndex++;
  41827. if (lightIndex === maxSimultaneousLights)
  41828. break;
  41829. }
  41830. }
  41831. defines["SPECULARTERM"] = specularEnabled;
  41832. defines["SHADOWS"] = shadowEnabled;
  41833. // Resetting all other lights if any
  41834. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41835. if (defines["LIGHT" + index] !== undefined) {
  41836. defines["LIGHT" + index] = false;
  41837. defines["HEMILIGHT" + lightIndex] = false;
  41838. defines["POINTLIGHT" + lightIndex] = false;
  41839. defines["DIRLIGHT" + lightIndex] = false;
  41840. defines["SPOTLIGHT" + lightIndex] = false;
  41841. defines["SHADOW" + lightIndex] = false;
  41842. }
  41843. }
  41844. var caps = scene.getEngine().getCaps();
  41845. if (defines["SHADOWFLOAT"] === undefined) {
  41846. needRebuild = true;
  41847. }
  41848. defines["SHADOWFLOAT"] = shadowEnabled &&
  41849. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41850. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41851. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41852. if (needRebuild) {
  41853. defines.rebuild();
  41854. }
  41855. return needNormals;
  41856. };
  41857. /**
  41858. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41859. * that won t be acctive due to defines being turned off.
  41860. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41861. * @param samplersList The samplers list
  41862. * @param defines The defines helping in the list generation
  41863. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41864. */
  41865. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41866. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41867. var uniformsList;
  41868. var uniformBuffersList = null;
  41869. if (uniformsListOrOptions.uniformsNames) {
  41870. var options = uniformsListOrOptions;
  41871. uniformsList = options.uniformsNames;
  41872. uniformBuffersList = options.uniformBuffersNames;
  41873. samplersList = options.samplers;
  41874. defines = options.defines;
  41875. maxSimultaneousLights = options.maxSimultaneousLights;
  41876. }
  41877. else {
  41878. uniformsList = uniformsListOrOptions;
  41879. if (!samplersList) {
  41880. samplersList = [];
  41881. }
  41882. }
  41883. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41884. if (!defines["LIGHT" + lightIndex]) {
  41885. break;
  41886. }
  41887. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41888. if (uniformBuffersList) {
  41889. uniformBuffersList.push("Light" + lightIndex);
  41890. }
  41891. samplersList.push("shadowSampler" + lightIndex);
  41892. samplersList.push("depthSampler" + lightIndex);
  41893. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41894. samplersList.push("projectionLightSampler" + lightIndex);
  41895. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41896. }
  41897. }
  41898. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41899. uniformsList.push("morphTargetInfluences");
  41900. }
  41901. };
  41902. /**
  41903. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41904. * @param defines The defines to update while falling back
  41905. * @param fallbacks The authorized effect fallbacks
  41906. * @param maxSimultaneousLights The maximum number of lights allowed
  41907. * @param rank the current rank of the Effect
  41908. * @returns The newly affected rank
  41909. */
  41910. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41911. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41912. if (rank === void 0) { rank = 0; }
  41913. var lightFallbackRank = 0;
  41914. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41915. if (!defines["LIGHT" + lightIndex]) {
  41916. break;
  41917. }
  41918. if (lightIndex > 0) {
  41919. lightFallbackRank = rank + lightIndex;
  41920. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41921. }
  41922. if (!defines["SHADOWS"]) {
  41923. if (defines["SHADOW" + lightIndex]) {
  41924. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41925. }
  41926. if (defines["SHADOWPCF" + lightIndex]) {
  41927. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41928. }
  41929. if (defines["SHADOWPCSS" + lightIndex]) {
  41930. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41931. }
  41932. if (defines["SHADOWPOISSON" + lightIndex]) {
  41933. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41934. }
  41935. if (defines["SHADOWESM" + lightIndex]) {
  41936. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41937. }
  41938. }
  41939. }
  41940. return lightFallbackRank++;
  41941. };
  41942. /**
  41943. * Prepares the list of attributes required for morph targets according to the effect defines.
  41944. * @param attribs The current list of supported attribs
  41945. * @param mesh The mesh to prepare the morph targets attributes for
  41946. * @param defines The current Defines of the effect
  41947. */
  41948. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41949. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41950. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41951. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41952. var manager = mesh.morphTargetManager;
  41953. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41954. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41955. for (var index = 0; index < influencers; index++) {
  41956. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41957. if (normal) {
  41958. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41959. }
  41960. if (tangent) {
  41961. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41962. }
  41963. if (attribs.length > maxAttributesCount) {
  41964. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41965. }
  41966. }
  41967. }
  41968. };
  41969. /**
  41970. * Prepares the list of attributes required for bones according to the effect defines.
  41971. * @param attribs The current list of supported attribs
  41972. * @param mesh The mesh to prepare the bones attributes for
  41973. * @param defines The current Defines of the effect
  41974. * @param fallbacks The current efffect fallback strategy
  41975. */
  41976. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41977. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41978. fallbacks.addCPUSkinningFallback(0, mesh);
  41979. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41980. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41981. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41982. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41983. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41984. }
  41985. }
  41986. };
  41987. /**
  41988. * Prepares the list of attributes required for instances according to the effect defines.
  41989. * @param attribs The current list of supported attribs
  41990. * @param defines The current Defines of the effect
  41991. */
  41992. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41993. if (defines["INSTANCES"]) {
  41994. attribs.push("world0");
  41995. attribs.push("world1");
  41996. attribs.push("world2");
  41997. attribs.push("world3");
  41998. }
  41999. };
  42000. /**
  42001. * Binds the light shadow information to the effect for the given mesh.
  42002. * @param light The light containing the generator
  42003. * @param scene The scene the lights belongs to
  42004. * @param mesh The mesh we are binding the information to render
  42005. * @param lightIndex The light index in the effect used to render the mesh
  42006. * @param effect The effect we are binding the data to
  42007. */
  42008. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42009. if (light.shadowEnabled && mesh.receiveShadows) {
  42010. var shadowGenerator = light.getShadowGenerator();
  42011. if (shadowGenerator) {
  42012. shadowGenerator.bindShadowLight(lightIndex, effect);
  42013. }
  42014. }
  42015. };
  42016. /**
  42017. * Binds the light information to the effect.
  42018. * @param light The light containing the generator
  42019. * @param effect The effect we are binding the data to
  42020. * @param lightIndex The light index in the effect used to render
  42021. */
  42022. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42023. light.transferToEffect(effect, lightIndex + "");
  42024. };
  42025. /**
  42026. * Binds the lights information from the scene to the effect for the given mesh.
  42027. * @param scene The scene the lights belongs to
  42028. * @param mesh The mesh we are binding the information to render
  42029. * @param effect The effect we are binding the data to
  42030. * @param defines The generated defines for the effect
  42031. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42032. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42033. */
  42034. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42035. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42036. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42037. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42038. for (var i = 0; i < len; i++) {
  42039. var light = mesh._lightSources[i];
  42040. var iAsString = i.toString();
  42041. var scaledIntensity = light.getScaledIntensity();
  42042. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42043. MaterialHelper.BindLightProperties(light, effect, i);
  42044. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42045. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42046. if (defines["SPECULARTERM"]) {
  42047. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42048. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42049. }
  42050. // Shadows
  42051. if (scene.shadowsEnabled) {
  42052. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42053. }
  42054. light._uniformBuffer.update();
  42055. }
  42056. };
  42057. /**
  42058. * Binds the fog information from the scene to the effect for the given mesh.
  42059. * @param scene The scene the lights belongs to
  42060. * @param mesh The mesh we are binding the information to render
  42061. * @param effect The effect we are binding the data to
  42062. * @param linearSpace Defines if the fog effect is applied in linear space
  42063. */
  42064. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42065. if (linearSpace === void 0) { linearSpace = false; }
  42066. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42067. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42068. // Convert fog color to linear space if used in a linear space computed shader.
  42069. if (linearSpace) {
  42070. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42071. effect.setColor3("vFogColor", this._tempFogColor);
  42072. }
  42073. else {
  42074. effect.setColor3("vFogColor", scene.fogColor);
  42075. }
  42076. }
  42077. };
  42078. /**
  42079. * Binds the bones information from the mesh to the effect.
  42080. * @param mesh The mesh we are binding the information to render
  42081. * @param effect The effect we are binding the data to
  42082. */
  42083. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42084. if (!effect || !mesh) {
  42085. return;
  42086. }
  42087. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42088. mesh.computeBonesUsingShaders = false;
  42089. }
  42090. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42091. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42092. if (matrices) {
  42093. effect.setMatrices("mBones", matrices);
  42094. }
  42095. }
  42096. };
  42097. /**
  42098. * Binds the morph targets information from the mesh to the effect.
  42099. * @param abstractMesh The mesh we are binding the information to render
  42100. * @param effect The effect we are binding the data to
  42101. */
  42102. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42103. var manager = abstractMesh.morphTargetManager;
  42104. if (!abstractMesh || !manager) {
  42105. return;
  42106. }
  42107. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42108. };
  42109. /**
  42110. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42111. * @param defines The generated defines used in the effect
  42112. * @param effect The effect we are binding the data to
  42113. * @param scene The scene we are willing to render with logarithmic scale for
  42114. */
  42115. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42116. if (defines["LOGARITHMICDEPTH"]) {
  42117. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42118. }
  42119. };
  42120. /**
  42121. * Binds the clip plane information from the scene to the effect.
  42122. * @param scene The scene the clip plane information are extracted from
  42123. * @param effect The effect we are binding the data to
  42124. */
  42125. MaterialHelper.BindClipPlane = function (effect, scene) {
  42126. if (scene.clipPlane) {
  42127. var clipPlane = scene.clipPlane;
  42128. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42129. }
  42130. if (scene.clipPlane2) {
  42131. var clipPlane = scene.clipPlane2;
  42132. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42133. }
  42134. if (scene.clipPlane3) {
  42135. var clipPlane = scene.clipPlane3;
  42136. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42137. }
  42138. if (scene.clipPlane4) {
  42139. var clipPlane = scene.clipPlane4;
  42140. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42141. }
  42142. };
  42143. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42144. return MaterialHelper;
  42145. }());
  42146. BABYLON.MaterialHelper = MaterialHelper;
  42147. })(BABYLON || (BABYLON = {}));
  42148. //# sourceMappingURL=babylon.materialHelper.js.map
  42149. var BABYLON;
  42150. (function (BABYLON) {
  42151. /**
  42152. * Base class of materials working in push mode in babylon JS
  42153. * @hidden
  42154. */
  42155. var PushMaterial = /** @class */ (function (_super) {
  42156. __extends(PushMaterial, _super);
  42157. function PushMaterial(name, scene) {
  42158. var _this = _super.call(this, name, scene) || this;
  42159. _this._normalMatrix = new BABYLON.Matrix();
  42160. _this.storeEffectOnSubMeshes = true;
  42161. return _this;
  42162. }
  42163. PushMaterial.prototype.getEffect = function () {
  42164. return this._activeEffect;
  42165. };
  42166. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42167. if (!mesh) {
  42168. return false;
  42169. }
  42170. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42171. return true;
  42172. }
  42173. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42174. };
  42175. /**
  42176. * Binds the given world matrix to the active effect
  42177. *
  42178. * @param world the matrix to bind
  42179. */
  42180. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42181. this._activeEffect.setMatrix("world", world);
  42182. };
  42183. /**
  42184. * Binds the given normal matrix to the active effect
  42185. *
  42186. * @param normalMatrix the matrix to bind
  42187. */
  42188. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42189. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42190. };
  42191. PushMaterial.prototype.bind = function (world, mesh) {
  42192. if (!mesh) {
  42193. return;
  42194. }
  42195. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42196. };
  42197. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42198. if (effect === void 0) { effect = null; }
  42199. _super.prototype._afterBind.call(this, mesh);
  42200. this.getScene()._cachedEffect = effect;
  42201. };
  42202. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42203. if (visibility === void 0) { visibility = 1; }
  42204. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42205. };
  42206. return PushMaterial;
  42207. }(BABYLON.Material));
  42208. BABYLON.PushMaterial = PushMaterial;
  42209. })(BABYLON || (BABYLON = {}));
  42210. //# sourceMappingURL=babylon.pushMaterial.js.map
  42211. var BABYLON;
  42212. (function (BABYLON) {
  42213. /** @hidden */
  42214. var StandardMaterialDefines = /** @class */ (function (_super) {
  42215. __extends(StandardMaterialDefines, _super);
  42216. function StandardMaterialDefines() {
  42217. var _this = _super.call(this) || this;
  42218. _this.MAINUV1 = false;
  42219. _this.MAINUV2 = false;
  42220. _this.DIFFUSE = false;
  42221. _this.DIFFUSEDIRECTUV = 0;
  42222. _this.AMBIENT = false;
  42223. _this.AMBIENTDIRECTUV = 0;
  42224. _this.OPACITY = false;
  42225. _this.OPACITYDIRECTUV = 0;
  42226. _this.OPACITYRGB = false;
  42227. _this.REFLECTION = false;
  42228. _this.EMISSIVE = false;
  42229. _this.EMISSIVEDIRECTUV = 0;
  42230. _this.SPECULAR = false;
  42231. _this.SPECULARDIRECTUV = 0;
  42232. _this.BUMP = false;
  42233. _this.BUMPDIRECTUV = 0;
  42234. _this.PARALLAX = false;
  42235. _this.PARALLAXOCCLUSION = false;
  42236. _this.SPECULAROVERALPHA = false;
  42237. _this.CLIPPLANE = false;
  42238. _this.CLIPPLANE2 = false;
  42239. _this.CLIPPLANE3 = false;
  42240. _this.CLIPPLANE4 = false;
  42241. _this.ALPHATEST = false;
  42242. _this.DEPTHPREPASS = false;
  42243. _this.ALPHAFROMDIFFUSE = false;
  42244. _this.POINTSIZE = false;
  42245. _this.FOG = false;
  42246. _this.SPECULARTERM = false;
  42247. _this.DIFFUSEFRESNEL = false;
  42248. _this.OPACITYFRESNEL = false;
  42249. _this.REFLECTIONFRESNEL = false;
  42250. _this.REFRACTIONFRESNEL = false;
  42251. _this.EMISSIVEFRESNEL = false;
  42252. _this.FRESNEL = false;
  42253. _this.NORMAL = false;
  42254. _this.UV1 = false;
  42255. _this.UV2 = false;
  42256. _this.VERTEXCOLOR = false;
  42257. _this.VERTEXALPHA = false;
  42258. _this.NUM_BONE_INFLUENCERS = 0;
  42259. _this.BonesPerMesh = 0;
  42260. _this.INSTANCES = false;
  42261. _this.GLOSSINESS = false;
  42262. _this.ROUGHNESS = false;
  42263. _this.EMISSIVEASILLUMINATION = false;
  42264. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42265. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42266. _this.LIGHTMAP = false;
  42267. _this.LIGHTMAPDIRECTUV = 0;
  42268. _this.OBJECTSPACE_NORMALMAP = false;
  42269. _this.USELIGHTMAPASSHADOWMAP = false;
  42270. _this.REFLECTIONMAP_3D = false;
  42271. _this.REFLECTIONMAP_SPHERICAL = false;
  42272. _this.REFLECTIONMAP_PLANAR = false;
  42273. _this.REFLECTIONMAP_CUBIC = false;
  42274. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42275. _this.REFLECTIONMAP_PROJECTION = false;
  42276. _this.REFLECTIONMAP_SKYBOX = false;
  42277. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42278. _this.REFLECTIONMAP_EXPLICIT = false;
  42279. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42280. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42281. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42282. _this.INVERTCUBICMAP = false;
  42283. _this.LOGARITHMICDEPTH = false;
  42284. _this.REFRACTION = false;
  42285. _this.REFRACTIONMAP_3D = false;
  42286. _this.REFLECTIONOVERALPHA = false;
  42287. _this.TWOSIDEDLIGHTING = false;
  42288. _this.SHADOWFLOAT = false;
  42289. _this.MORPHTARGETS = false;
  42290. _this.MORPHTARGETS_NORMAL = false;
  42291. _this.MORPHTARGETS_TANGENT = false;
  42292. _this.NUM_MORPH_INFLUENCERS = 0;
  42293. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42294. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42295. _this.IMAGEPROCESSING = false;
  42296. _this.VIGNETTE = false;
  42297. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42298. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42299. _this.TONEMAPPING = false;
  42300. _this.TONEMAPPING_ACES = false;
  42301. _this.CONTRAST = false;
  42302. _this.COLORCURVES = false;
  42303. _this.COLORGRADING = false;
  42304. _this.COLORGRADING3D = false;
  42305. _this.SAMPLER3DGREENDEPTH = false;
  42306. _this.SAMPLER3DBGRMAP = false;
  42307. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42308. /**
  42309. * If the reflection texture on this material is in linear color space
  42310. * @hidden
  42311. */
  42312. _this.IS_REFLECTION_LINEAR = false;
  42313. /**
  42314. * If the refraction texture on this material is in linear color space
  42315. * @hidden
  42316. */
  42317. _this.IS_REFRACTION_LINEAR = false;
  42318. _this.EXPOSURE = false;
  42319. _this.rebuild();
  42320. return _this;
  42321. }
  42322. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42323. var modes = [
  42324. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42325. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42326. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42327. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42328. ];
  42329. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42330. var mode = modes_1[_i];
  42331. this[mode] = (mode === modeToEnable);
  42332. }
  42333. };
  42334. return StandardMaterialDefines;
  42335. }(BABYLON.MaterialDefines));
  42336. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42337. /**
  42338. * This is the default material used in Babylon. It is the best trade off between quality
  42339. * and performances.
  42340. * @see http://doc.babylonjs.com/babylon101/materials
  42341. */
  42342. var StandardMaterial = /** @class */ (function (_super) {
  42343. __extends(StandardMaterial, _super);
  42344. /**
  42345. * Instantiates a new standard material.
  42346. * This is the default material used in Babylon. It is the best trade off between quality
  42347. * and performances.
  42348. * @see http://doc.babylonjs.com/babylon101/materials
  42349. * @param name Define the name of the material in the scene
  42350. * @param scene Define the scene the material belong to
  42351. */
  42352. function StandardMaterial(name, scene) {
  42353. var _this = _super.call(this, name, scene) || this;
  42354. /**
  42355. * The color of the material lit by the environmental background lighting.
  42356. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42357. */
  42358. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42359. /**
  42360. * The basic color of the material as viewed under a light.
  42361. */
  42362. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42363. /**
  42364. * Define how the color and intensity of the highlight given by the light in the material.
  42365. */
  42366. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42367. /**
  42368. * Define the color of the material as if self lit.
  42369. * This will be mixed in the final result even in the absence of light.
  42370. */
  42371. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42372. /**
  42373. * Defines how sharp are the highlights in the material.
  42374. * The bigger the value the sharper giving a more glossy feeling to the result.
  42375. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42376. */
  42377. _this.specularPower = 64;
  42378. _this._useAlphaFromDiffuseTexture = false;
  42379. _this._useEmissiveAsIllumination = false;
  42380. _this._linkEmissiveWithDiffuse = false;
  42381. _this._useSpecularOverAlpha = false;
  42382. _this._useReflectionOverAlpha = false;
  42383. _this._disableLighting = false;
  42384. _this._useObjectSpaceNormalMap = false;
  42385. _this._useParallax = false;
  42386. _this._useParallaxOcclusion = false;
  42387. /**
  42388. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  42389. */
  42390. _this.parallaxScaleBias = 0.05;
  42391. _this._roughness = 0;
  42392. /**
  42393. * In case of refraction, define the value of the indice of refraction.
  42394. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42395. */
  42396. _this.indexOfRefraction = 0.98;
  42397. /**
  42398. * Invert the refraction texture alongside the y axis.
  42399. * It can be usefull with procedural textures or probe for instance.
  42400. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42401. */
  42402. _this.invertRefractionY = true;
  42403. /**
  42404. * Defines the alpha limits in alpha test mode.
  42405. */
  42406. _this.alphaCutOff = 0.4;
  42407. _this._useLightmapAsShadowmap = false;
  42408. _this._useReflectionFresnelFromSpecular = false;
  42409. _this._useGlossinessFromSpecularMapAlpha = false;
  42410. _this._maxSimultaneousLights = 4;
  42411. _this._invertNormalMapX = false;
  42412. _this._invertNormalMapY = false;
  42413. _this._twoSidedLighting = false;
  42414. _this._renderTargets = new BABYLON.SmartArray(16);
  42415. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42416. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42417. // Setup the default processing configuration to the scene.
  42418. _this._attachImageProcessingConfiguration(null);
  42419. _this.getRenderTargetTextures = function () {
  42420. _this._renderTargets.reset();
  42421. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42422. _this._renderTargets.push(_this._reflectionTexture);
  42423. }
  42424. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42425. _this._renderTargets.push(_this._refractionTexture);
  42426. }
  42427. return _this._renderTargets;
  42428. };
  42429. return _this;
  42430. }
  42431. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42432. /**
  42433. * Gets the image processing configuration used either in this material.
  42434. */
  42435. get: function () {
  42436. return this._imageProcessingConfiguration;
  42437. },
  42438. /**
  42439. * Sets the Default image processing configuration used either in the this material.
  42440. *
  42441. * If sets to null, the scene one is in use.
  42442. */
  42443. set: function (value) {
  42444. this._attachImageProcessingConfiguration(value);
  42445. // Ensure the effect will be rebuilt.
  42446. this._markAllSubMeshesAsTexturesDirty();
  42447. },
  42448. enumerable: true,
  42449. configurable: true
  42450. });
  42451. /**
  42452. * Attaches a new image processing configuration to the Standard Material.
  42453. * @param configuration
  42454. */
  42455. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42456. var _this = this;
  42457. if (configuration === this._imageProcessingConfiguration) {
  42458. return;
  42459. }
  42460. // Detaches observer.
  42461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42463. }
  42464. // Pick the scene configuration if needed.
  42465. if (!configuration) {
  42466. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42467. }
  42468. else {
  42469. this._imageProcessingConfiguration = configuration;
  42470. }
  42471. // Attaches observer.
  42472. if (this._imageProcessingConfiguration) {
  42473. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42474. _this._markAllSubMeshesAsImageProcessingDirty();
  42475. });
  42476. }
  42477. };
  42478. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42479. /**
  42480. * Gets wether the color curves effect is enabled.
  42481. */
  42482. get: function () {
  42483. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42484. },
  42485. /**
  42486. * Sets wether the color curves effect is enabled.
  42487. */
  42488. set: function (value) {
  42489. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42490. },
  42491. enumerable: true,
  42492. configurable: true
  42493. });
  42494. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42495. /**
  42496. * Gets wether the color grading effect is enabled.
  42497. */
  42498. get: function () {
  42499. return this.imageProcessingConfiguration.colorGradingEnabled;
  42500. },
  42501. /**
  42502. * Gets wether the color grading effect is enabled.
  42503. */
  42504. set: function (value) {
  42505. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42511. /**
  42512. * Gets wether tonemapping is enabled or not.
  42513. */
  42514. get: function () {
  42515. return this._imageProcessingConfiguration.toneMappingEnabled;
  42516. },
  42517. /**
  42518. * Sets wether tonemapping is enabled or not
  42519. */
  42520. set: function (value) {
  42521. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42522. },
  42523. enumerable: true,
  42524. configurable: true
  42525. });
  42526. ;
  42527. ;
  42528. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42529. /**
  42530. * The camera exposure used on this material.
  42531. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42532. * This corresponds to a photographic exposure.
  42533. */
  42534. get: function () {
  42535. return this._imageProcessingConfiguration.exposure;
  42536. },
  42537. /**
  42538. * The camera exposure used on this material.
  42539. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42540. * This corresponds to a photographic exposure.
  42541. */
  42542. set: function (value) {
  42543. this._imageProcessingConfiguration.exposure = value;
  42544. },
  42545. enumerable: true,
  42546. configurable: true
  42547. });
  42548. ;
  42549. ;
  42550. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42551. /**
  42552. * Gets The camera contrast used on this material.
  42553. */
  42554. get: function () {
  42555. return this._imageProcessingConfiguration.contrast;
  42556. },
  42557. /**
  42558. * Sets The camera contrast used on this material.
  42559. */
  42560. set: function (value) {
  42561. this._imageProcessingConfiguration.contrast = value;
  42562. },
  42563. enumerable: true,
  42564. configurable: true
  42565. });
  42566. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42567. /**
  42568. * Gets the Color Grading 2D Lookup Texture.
  42569. */
  42570. get: function () {
  42571. return this._imageProcessingConfiguration.colorGradingTexture;
  42572. },
  42573. /**
  42574. * Sets the Color Grading 2D Lookup Texture.
  42575. */
  42576. set: function (value) {
  42577. this._imageProcessingConfiguration.colorGradingTexture = value;
  42578. },
  42579. enumerable: true,
  42580. configurable: true
  42581. });
  42582. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42583. /**
  42584. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42585. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42586. * 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;
  42587. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42588. */
  42589. get: function () {
  42590. return this._imageProcessingConfiguration.colorCurves;
  42591. },
  42592. /**
  42593. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42594. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42595. * 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;
  42596. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42597. */
  42598. set: function (value) {
  42599. this._imageProcessingConfiguration.colorCurves = value;
  42600. },
  42601. enumerable: true,
  42602. configurable: true
  42603. });
  42604. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42605. /**
  42606. * Gets a boolean indicating that current material needs to register RTT
  42607. */
  42608. get: function () {
  42609. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42610. return true;
  42611. }
  42612. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42613. return true;
  42614. }
  42615. return false;
  42616. },
  42617. enumerable: true,
  42618. configurable: true
  42619. });
  42620. /**
  42621. * Gets the current class name of the material e.g. "StandardMaterial"
  42622. * Mainly use in serialization.
  42623. * @returns the class name
  42624. */
  42625. StandardMaterial.prototype.getClassName = function () {
  42626. return "StandardMaterial";
  42627. };
  42628. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42629. /**
  42630. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42631. * You can try switching to logarithmic depth.
  42632. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42633. */
  42634. get: function () {
  42635. return this._useLogarithmicDepth;
  42636. },
  42637. set: function (value) {
  42638. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42639. this._markAllSubMeshesAsMiscDirty();
  42640. },
  42641. enumerable: true,
  42642. configurable: true
  42643. });
  42644. /**
  42645. * Specifies if the material will require alpha blending
  42646. * @returns a boolean specifying if alpha blending is needed
  42647. */
  42648. StandardMaterial.prototype.needAlphaBlending = function () {
  42649. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42650. };
  42651. /**
  42652. * Specifies if this material should be rendered in alpha test mode
  42653. * @returns a boolean specifying if an alpha test is needed.
  42654. */
  42655. StandardMaterial.prototype.needAlphaTesting = function () {
  42656. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42657. };
  42658. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42659. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42660. };
  42661. /**
  42662. * Get the texture used for alpha test purpose.
  42663. * @returns the diffuse texture in case of the standard material.
  42664. */
  42665. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42666. return this._diffuseTexture;
  42667. };
  42668. /**
  42669. * Get if the submesh is ready to be used and all its information available.
  42670. * Child classes can use it to update shaders
  42671. * @param mesh defines the mesh to check
  42672. * @param subMesh defines which submesh to check
  42673. * @param useInstances specifies that instances should be used
  42674. * @returns a boolean indicating that the submesh is ready or not
  42675. */
  42676. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42677. if (useInstances === void 0) { useInstances = false; }
  42678. if (subMesh.effect && this.isFrozen) {
  42679. if (this._wasPreviouslyReady) {
  42680. return true;
  42681. }
  42682. }
  42683. if (!subMesh._materialDefines) {
  42684. subMesh._materialDefines = new StandardMaterialDefines();
  42685. }
  42686. var scene = this.getScene();
  42687. var defines = subMesh._materialDefines;
  42688. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42689. if (defines._renderId === scene.getRenderId()) {
  42690. return true;
  42691. }
  42692. }
  42693. var engine = scene.getEngine();
  42694. // Lights
  42695. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42696. // Textures
  42697. if (defines._areTexturesDirty) {
  42698. defines._needUVs = false;
  42699. defines.MAINUV1 = false;
  42700. defines.MAINUV2 = false;
  42701. if (scene.texturesEnabled) {
  42702. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42703. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42704. return false;
  42705. }
  42706. else {
  42707. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42708. }
  42709. }
  42710. else {
  42711. defines.DIFFUSE = false;
  42712. }
  42713. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42714. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42715. return false;
  42716. }
  42717. else {
  42718. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42719. }
  42720. }
  42721. else {
  42722. defines.AMBIENT = false;
  42723. }
  42724. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42725. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42726. return false;
  42727. }
  42728. else {
  42729. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42730. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42731. }
  42732. }
  42733. else {
  42734. defines.OPACITY = false;
  42735. }
  42736. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42737. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42738. return false;
  42739. }
  42740. else {
  42741. defines._needNormals = true;
  42742. defines.REFLECTION = true;
  42743. defines.ROUGHNESS = (this._roughness > 0);
  42744. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42745. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42746. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42747. switch (this._reflectionTexture.coordinatesMode) {
  42748. case BABYLON.Texture.EXPLICIT_MODE:
  42749. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42750. break;
  42751. case BABYLON.Texture.PLANAR_MODE:
  42752. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42753. break;
  42754. case BABYLON.Texture.PROJECTION_MODE:
  42755. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42756. break;
  42757. case BABYLON.Texture.SKYBOX_MODE:
  42758. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42759. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42760. break;
  42761. case BABYLON.Texture.SPHERICAL_MODE:
  42762. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42763. break;
  42764. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42765. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42766. break;
  42767. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42768. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42769. break;
  42770. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42771. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42772. break;
  42773. case BABYLON.Texture.CUBIC_MODE:
  42774. case BABYLON.Texture.INVCUBIC_MODE:
  42775. default:
  42776. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42777. break;
  42778. }
  42779. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42780. }
  42781. }
  42782. else {
  42783. defines.REFLECTION = false;
  42784. }
  42785. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42786. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42787. return false;
  42788. }
  42789. else {
  42790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42791. }
  42792. }
  42793. else {
  42794. defines.EMISSIVE = false;
  42795. }
  42796. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42797. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42798. return false;
  42799. }
  42800. else {
  42801. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42802. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42803. }
  42804. }
  42805. else {
  42806. defines.LIGHTMAP = false;
  42807. }
  42808. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42809. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42810. return false;
  42811. }
  42812. else {
  42813. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42814. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42815. }
  42816. }
  42817. else {
  42818. defines.SPECULAR = false;
  42819. }
  42820. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42821. // Bump texure can not be not blocking.
  42822. if (!this._bumpTexture.isReady()) {
  42823. return false;
  42824. }
  42825. else {
  42826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42827. defines.PARALLAX = this._useParallax;
  42828. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42829. }
  42830. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42831. }
  42832. else {
  42833. defines.BUMP = false;
  42834. }
  42835. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42836. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42837. return false;
  42838. }
  42839. else {
  42840. defines._needUVs = true;
  42841. defines.REFRACTION = true;
  42842. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42843. }
  42844. }
  42845. else {
  42846. defines.REFRACTION = false;
  42847. }
  42848. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42849. }
  42850. else {
  42851. defines.DIFFUSE = false;
  42852. defines.AMBIENT = false;
  42853. defines.OPACITY = false;
  42854. defines.REFLECTION = false;
  42855. defines.EMISSIVE = false;
  42856. defines.LIGHTMAP = false;
  42857. defines.BUMP = false;
  42858. defines.REFRACTION = false;
  42859. }
  42860. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42861. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42862. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42863. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42864. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42865. }
  42866. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42867. if (!this._imageProcessingConfiguration.isReady()) {
  42868. return false;
  42869. }
  42870. this._imageProcessingConfiguration.prepareDefines(defines);
  42871. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42872. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42873. }
  42874. if (defines._areFresnelDirty) {
  42875. if (StandardMaterial.FresnelEnabled) {
  42876. // Fresnel
  42877. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42878. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42879. this._reflectionFresnelParameters) {
  42880. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42881. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42882. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42883. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42884. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42885. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42886. defines._needNormals = true;
  42887. defines.FRESNEL = true;
  42888. }
  42889. }
  42890. else {
  42891. defines.FRESNEL = false;
  42892. }
  42893. }
  42894. // Misc.
  42895. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42896. // Attribs
  42897. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42898. // Values that need to be evaluated on every frame
  42899. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42900. // Get correct effect
  42901. if (defines.isDirty) {
  42902. defines.markAsProcessed();
  42903. scene.resetCachedMaterial();
  42904. // Fallbacks
  42905. var fallbacks = new BABYLON.EffectFallbacks();
  42906. if (defines.REFLECTION) {
  42907. fallbacks.addFallback(0, "REFLECTION");
  42908. }
  42909. if (defines.SPECULAR) {
  42910. fallbacks.addFallback(0, "SPECULAR");
  42911. }
  42912. if (defines.BUMP) {
  42913. fallbacks.addFallback(0, "BUMP");
  42914. }
  42915. if (defines.PARALLAX) {
  42916. fallbacks.addFallback(1, "PARALLAX");
  42917. }
  42918. if (defines.PARALLAXOCCLUSION) {
  42919. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42920. }
  42921. if (defines.SPECULAROVERALPHA) {
  42922. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42923. }
  42924. if (defines.FOG) {
  42925. fallbacks.addFallback(1, "FOG");
  42926. }
  42927. if (defines.POINTSIZE) {
  42928. fallbacks.addFallback(0, "POINTSIZE");
  42929. }
  42930. if (defines.LOGARITHMICDEPTH) {
  42931. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42932. }
  42933. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42934. if (defines.SPECULARTERM) {
  42935. fallbacks.addFallback(0, "SPECULARTERM");
  42936. }
  42937. if (defines.DIFFUSEFRESNEL) {
  42938. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42939. }
  42940. if (defines.OPACITYFRESNEL) {
  42941. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42942. }
  42943. if (defines.REFLECTIONFRESNEL) {
  42944. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42945. }
  42946. if (defines.EMISSIVEFRESNEL) {
  42947. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42948. }
  42949. if (defines.FRESNEL) {
  42950. fallbacks.addFallback(4, "FRESNEL");
  42951. }
  42952. //Attributes
  42953. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42954. if (defines.NORMAL) {
  42955. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42956. }
  42957. if (defines.UV1) {
  42958. attribs.push(BABYLON.VertexBuffer.UVKind);
  42959. }
  42960. if (defines.UV2) {
  42961. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42962. }
  42963. if (defines.VERTEXCOLOR) {
  42964. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42965. }
  42966. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42967. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42968. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42969. var shaderName = "default";
  42970. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42971. "vFogInfos", "vFogColor", "pointSize",
  42972. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42973. "mBones",
  42974. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42975. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42976. "vReflectionPosition", "vReflectionSize",
  42977. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42978. ];
  42979. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42980. var uniformBuffers = ["Material", "Scene"];
  42981. if (BABYLON.ImageProcessingConfiguration) {
  42982. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42983. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42984. }
  42985. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42986. uniformsNames: uniforms,
  42987. uniformBuffersNames: uniformBuffers,
  42988. samplers: samplers,
  42989. defines: defines,
  42990. maxSimultaneousLights: this._maxSimultaneousLights
  42991. });
  42992. if (this.customShaderNameResolve) {
  42993. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42994. }
  42995. var join = defines.toString();
  42996. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42997. attributes: attribs,
  42998. uniformsNames: uniforms,
  42999. uniformBuffersNames: uniformBuffers,
  43000. samplers: samplers,
  43001. defines: join,
  43002. fallbacks: fallbacks,
  43003. onCompiled: this.onCompiled,
  43004. onError: this.onError,
  43005. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43006. }, engine), defines);
  43007. this.buildUniformLayout();
  43008. }
  43009. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43010. return false;
  43011. }
  43012. defines._renderId = scene.getRenderId();
  43013. this._wasPreviouslyReady = true;
  43014. return true;
  43015. };
  43016. /**
  43017. * Builds the material UBO layouts.
  43018. * Used internally during the effect preparation.
  43019. */
  43020. StandardMaterial.prototype.buildUniformLayout = function () {
  43021. // Order is important !
  43022. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43023. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43024. this._uniformBuffer.addUniform("opacityParts", 4);
  43025. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43026. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43027. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43028. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43029. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43030. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43031. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43032. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43033. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43034. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43035. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43036. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43037. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43038. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43039. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43040. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43041. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43042. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43043. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43044. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43045. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43046. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43047. this._uniformBuffer.addUniform("specularMatrix", 16);
  43048. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43049. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43050. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43051. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43052. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43053. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43054. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43055. this._uniformBuffer.addUniform("pointSize", 1);
  43056. this._uniformBuffer.create();
  43057. };
  43058. /**
  43059. * Unbinds the material from the mesh
  43060. */
  43061. StandardMaterial.prototype.unbind = function () {
  43062. if (this._activeEffect) {
  43063. var needFlag = false;
  43064. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43065. this._activeEffect.setTexture("reflection2DSampler", null);
  43066. needFlag = true;
  43067. }
  43068. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43069. this._activeEffect.setTexture("refraction2DSampler", null);
  43070. needFlag = true;
  43071. }
  43072. if (needFlag) {
  43073. this._markAllSubMeshesAsTexturesDirty();
  43074. }
  43075. }
  43076. _super.prototype.unbind.call(this);
  43077. };
  43078. /**
  43079. * Binds the submesh to this material by preparing the effect and shader to draw
  43080. * @param world defines the world transformation matrix
  43081. * @param mesh defines the mesh containing the submesh
  43082. * @param subMesh defines the submesh to bind the material to
  43083. */
  43084. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43085. var scene = this.getScene();
  43086. var defines = subMesh._materialDefines;
  43087. if (!defines) {
  43088. return;
  43089. }
  43090. var effect = subMesh.effect;
  43091. if (!effect) {
  43092. return;
  43093. }
  43094. this._activeEffect = effect;
  43095. // Matrices
  43096. this.bindOnlyWorldMatrix(world);
  43097. // Normal Matrix
  43098. if (defines.OBJECTSPACE_NORMALMAP) {
  43099. world.toNormalMatrix(this._normalMatrix);
  43100. this.bindOnlyNormalMatrix(this._normalMatrix);
  43101. }
  43102. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43103. // Bones
  43104. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43105. if (mustRebind) {
  43106. this._uniformBuffer.bindToEffect(effect, "Material");
  43107. this.bindViewProjection(effect);
  43108. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43109. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43110. // Fresnel
  43111. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43112. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43113. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43114. }
  43115. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43116. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43117. }
  43118. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43119. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43120. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43121. }
  43122. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43123. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43124. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43125. }
  43126. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43127. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43128. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43129. }
  43130. }
  43131. // Textures
  43132. if (scene.texturesEnabled) {
  43133. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43134. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43135. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43136. if (this._diffuseTexture.hasAlpha) {
  43137. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43138. }
  43139. }
  43140. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43141. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43142. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43143. }
  43144. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43145. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43146. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43147. }
  43148. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43149. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43150. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43151. if (this._reflectionTexture.boundingBoxSize) {
  43152. var cubeTexture = this._reflectionTexture;
  43153. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43154. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43155. }
  43156. }
  43157. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43158. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43159. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43160. }
  43161. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43162. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43163. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43164. }
  43165. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43166. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43167. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43168. }
  43169. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43170. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43171. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43172. if (scene._mirroredCameraPosition) {
  43173. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43174. }
  43175. else {
  43176. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43177. }
  43178. }
  43179. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43180. var depth = 1.0;
  43181. if (!this._refractionTexture.isCube) {
  43182. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43183. if (this._refractionTexture.depth) {
  43184. depth = this._refractionTexture.depth;
  43185. }
  43186. }
  43187. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43188. }
  43189. }
  43190. // Point size
  43191. if (this.pointsCloud) {
  43192. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43193. }
  43194. if (defines.SPECULARTERM) {
  43195. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43196. }
  43197. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43198. // Diffuse
  43199. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43200. }
  43201. // Textures
  43202. if (scene.texturesEnabled) {
  43203. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43204. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43205. }
  43206. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43207. effect.setTexture("ambientSampler", this._ambientTexture);
  43208. }
  43209. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43210. effect.setTexture("opacitySampler", this._opacityTexture);
  43211. }
  43212. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43213. if (this._reflectionTexture.isCube) {
  43214. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43215. }
  43216. else {
  43217. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43218. }
  43219. }
  43220. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43221. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43222. }
  43223. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43224. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43225. }
  43226. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43227. effect.setTexture("specularSampler", this._specularTexture);
  43228. }
  43229. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43230. effect.setTexture("bumpSampler", this._bumpTexture);
  43231. }
  43232. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43233. var depth = 1.0;
  43234. if (this._refractionTexture.isCube) {
  43235. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43236. }
  43237. else {
  43238. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43239. }
  43240. }
  43241. }
  43242. // Clip plane
  43243. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43244. // Colors
  43245. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43246. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43247. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43248. }
  43249. if (mustRebind || !this.isFrozen) {
  43250. // Lights
  43251. if (scene.lightsEnabled && !this._disableLighting) {
  43252. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43253. }
  43254. // View
  43255. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43256. this.bindView(effect);
  43257. }
  43258. // Fog
  43259. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43260. // Morph targets
  43261. if (defines.NUM_MORPH_INFLUENCERS) {
  43262. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43263. }
  43264. // Log. depth
  43265. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43266. // image processing
  43267. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43268. this._imageProcessingConfiguration.bind(this._activeEffect);
  43269. }
  43270. }
  43271. this._uniformBuffer.update();
  43272. this._afterBind(mesh, this._activeEffect);
  43273. };
  43274. /**
  43275. * Get the list of animatables in the material.
  43276. * @returns the list of animatables object used in the material
  43277. */
  43278. StandardMaterial.prototype.getAnimatables = function () {
  43279. var results = [];
  43280. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43281. results.push(this._diffuseTexture);
  43282. }
  43283. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43284. results.push(this._ambientTexture);
  43285. }
  43286. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43287. results.push(this._opacityTexture);
  43288. }
  43289. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43290. results.push(this._reflectionTexture);
  43291. }
  43292. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43293. results.push(this._emissiveTexture);
  43294. }
  43295. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43296. results.push(this._specularTexture);
  43297. }
  43298. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43299. results.push(this._bumpTexture);
  43300. }
  43301. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43302. results.push(this._lightmapTexture);
  43303. }
  43304. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43305. results.push(this._refractionTexture);
  43306. }
  43307. return results;
  43308. };
  43309. /**
  43310. * Gets the active textures from the material
  43311. * @returns an array of textures
  43312. */
  43313. StandardMaterial.prototype.getActiveTextures = function () {
  43314. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43315. if (this._diffuseTexture) {
  43316. activeTextures.push(this._diffuseTexture);
  43317. }
  43318. if (this._ambientTexture) {
  43319. activeTextures.push(this._ambientTexture);
  43320. }
  43321. if (this._opacityTexture) {
  43322. activeTextures.push(this._opacityTexture);
  43323. }
  43324. if (this._reflectionTexture) {
  43325. activeTextures.push(this._reflectionTexture);
  43326. }
  43327. if (this._emissiveTexture) {
  43328. activeTextures.push(this._emissiveTexture);
  43329. }
  43330. if (this._specularTexture) {
  43331. activeTextures.push(this._specularTexture);
  43332. }
  43333. if (this._bumpTexture) {
  43334. activeTextures.push(this._bumpTexture);
  43335. }
  43336. if (this._lightmapTexture) {
  43337. activeTextures.push(this._lightmapTexture);
  43338. }
  43339. if (this._refractionTexture) {
  43340. activeTextures.push(this._refractionTexture);
  43341. }
  43342. return activeTextures;
  43343. };
  43344. /**
  43345. * Specifies if the material uses a texture
  43346. * @param texture defines the texture to check against the material
  43347. * @returns a boolean specifying if the material uses the texture
  43348. */
  43349. StandardMaterial.prototype.hasTexture = function (texture) {
  43350. if (_super.prototype.hasTexture.call(this, texture)) {
  43351. return true;
  43352. }
  43353. if (this._diffuseTexture === texture) {
  43354. return true;
  43355. }
  43356. if (this._ambientTexture === texture) {
  43357. return true;
  43358. }
  43359. if (this._opacityTexture === texture) {
  43360. return true;
  43361. }
  43362. if (this._reflectionTexture === texture) {
  43363. return true;
  43364. }
  43365. if (this._emissiveTexture === texture) {
  43366. return true;
  43367. }
  43368. if (this._specularTexture === texture) {
  43369. return true;
  43370. }
  43371. if (this._bumpTexture === texture) {
  43372. return true;
  43373. }
  43374. if (this._lightmapTexture === texture) {
  43375. return true;
  43376. }
  43377. if (this._refractionTexture === texture) {
  43378. return true;
  43379. }
  43380. return false;
  43381. };
  43382. /**
  43383. * Disposes the material
  43384. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43385. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43386. */
  43387. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43388. if (forceDisposeTextures) {
  43389. if (this._diffuseTexture) {
  43390. this._diffuseTexture.dispose();
  43391. }
  43392. if (this._ambientTexture) {
  43393. this._ambientTexture.dispose();
  43394. }
  43395. if (this._opacityTexture) {
  43396. this._opacityTexture.dispose();
  43397. }
  43398. if (this._reflectionTexture) {
  43399. this._reflectionTexture.dispose();
  43400. }
  43401. if (this._emissiveTexture) {
  43402. this._emissiveTexture.dispose();
  43403. }
  43404. if (this._specularTexture) {
  43405. this._specularTexture.dispose();
  43406. }
  43407. if (this._bumpTexture) {
  43408. this._bumpTexture.dispose();
  43409. }
  43410. if (this._lightmapTexture) {
  43411. this._lightmapTexture.dispose();
  43412. }
  43413. if (this._refractionTexture) {
  43414. this._refractionTexture.dispose();
  43415. }
  43416. }
  43417. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43418. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43419. }
  43420. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43421. };
  43422. /**
  43423. * Makes a duplicate of the material, and gives it a new name
  43424. * @param name defines the new name for the duplicated material
  43425. * @returns the cloned material
  43426. */
  43427. StandardMaterial.prototype.clone = function (name) {
  43428. var _this = this;
  43429. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43430. result.name = name;
  43431. result.id = name;
  43432. return result;
  43433. };
  43434. /**
  43435. * Serializes this material in a JSON representation
  43436. * @returns the serialized material object
  43437. */
  43438. StandardMaterial.prototype.serialize = function () {
  43439. return BABYLON.SerializationHelper.Serialize(this);
  43440. };
  43441. /**
  43442. * Creates a standard material from parsed material data
  43443. * @param source defines the JSON represnetation of the material
  43444. * @param scene defines the hosting scene
  43445. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43446. * @returns a new material
  43447. */
  43448. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43449. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43450. };
  43451. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43452. /**
  43453. * Are diffuse textures enabled in the application.
  43454. */
  43455. get: function () {
  43456. return StandardMaterial._DiffuseTextureEnabled;
  43457. },
  43458. set: function (value) {
  43459. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43460. return;
  43461. }
  43462. StandardMaterial._DiffuseTextureEnabled = value;
  43463. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43464. },
  43465. enumerable: true,
  43466. configurable: true
  43467. });
  43468. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43469. /**
  43470. * Are ambient textures enabled in the application.
  43471. */
  43472. get: function () {
  43473. return StandardMaterial._AmbientTextureEnabled;
  43474. },
  43475. set: function (value) {
  43476. if (StandardMaterial._AmbientTextureEnabled === value) {
  43477. return;
  43478. }
  43479. StandardMaterial._AmbientTextureEnabled = value;
  43480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43481. },
  43482. enumerable: true,
  43483. configurable: true
  43484. });
  43485. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43486. /**
  43487. * Are opacity textures enabled in the application.
  43488. */
  43489. get: function () {
  43490. return StandardMaterial._OpacityTextureEnabled;
  43491. },
  43492. set: function (value) {
  43493. if (StandardMaterial._OpacityTextureEnabled === value) {
  43494. return;
  43495. }
  43496. StandardMaterial._OpacityTextureEnabled = value;
  43497. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43498. },
  43499. enumerable: true,
  43500. configurable: true
  43501. });
  43502. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43503. /**
  43504. * Are reflection textures enabled in the application.
  43505. */
  43506. get: function () {
  43507. return StandardMaterial._ReflectionTextureEnabled;
  43508. },
  43509. set: function (value) {
  43510. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43511. return;
  43512. }
  43513. StandardMaterial._ReflectionTextureEnabled = value;
  43514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43515. },
  43516. enumerable: true,
  43517. configurable: true
  43518. });
  43519. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43520. /**
  43521. * Are emissive textures enabled in the application.
  43522. */
  43523. get: function () {
  43524. return StandardMaterial._EmissiveTextureEnabled;
  43525. },
  43526. set: function (value) {
  43527. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43528. return;
  43529. }
  43530. StandardMaterial._EmissiveTextureEnabled = value;
  43531. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43532. },
  43533. enumerable: true,
  43534. configurable: true
  43535. });
  43536. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43537. /**
  43538. * Are specular textures enabled in the application.
  43539. */
  43540. get: function () {
  43541. return StandardMaterial._SpecularTextureEnabled;
  43542. },
  43543. set: function (value) {
  43544. if (StandardMaterial._SpecularTextureEnabled === value) {
  43545. return;
  43546. }
  43547. StandardMaterial._SpecularTextureEnabled = value;
  43548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43549. },
  43550. enumerable: true,
  43551. configurable: true
  43552. });
  43553. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43554. /**
  43555. * Are bump textures enabled in the application.
  43556. */
  43557. get: function () {
  43558. return StandardMaterial._BumpTextureEnabled;
  43559. },
  43560. set: function (value) {
  43561. if (StandardMaterial._BumpTextureEnabled === value) {
  43562. return;
  43563. }
  43564. StandardMaterial._BumpTextureEnabled = value;
  43565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43571. /**
  43572. * Are lightmap textures enabled in the application.
  43573. */
  43574. get: function () {
  43575. return StandardMaterial._LightmapTextureEnabled;
  43576. },
  43577. set: function (value) {
  43578. if (StandardMaterial._LightmapTextureEnabled === value) {
  43579. return;
  43580. }
  43581. StandardMaterial._LightmapTextureEnabled = value;
  43582. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43583. },
  43584. enumerable: true,
  43585. configurable: true
  43586. });
  43587. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43588. /**
  43589. * Are refraction textures enabled in the application.
  43590. */
  43591. get: function () {
  43592. return StandardMaterial._RefractionTextureEnabled;
  43593. },
  43594. set: function (value) {
  43595. if (StandardMaterial._RefractionTextureEnabled === value) {
  43596. return;
  43597. }
  43598. StandardMaterial._RefractionTextureEnabled = value;
  43599. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43600. },
  43601. enumerable: true,
  43602. configurable: true
  43603. });
  43604. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43605. /**
  43606. * Are color grading textures enabled in the application.
  43607. */
  43608. get: function () {
  43609. return StandardMaterial._ColorGradingTextureEnabled;
  43610. },
  43611. set: function (value) {
  43612. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43613. return;
  43614. }
  43615. StandardMaterial._ColorGradingTextureEnabled = value;
  43616. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43617. },
  43618. enumerable: true,
  43619. configurable: true
  43620. });
  43621. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43622. /**
  43623. * Are fresnels enabled in the application.
  43624. */
  43625. get: function () {
  43626. return StandardMaterial._FresnelEnabled;
  43627. },
  43628. set: function (value) {
  43629. if (StandardMaterial._FresnelEnabled === value) {
  43630. return;
  43631. }
  43632. StandardMaterial._FresnelEnabled = value;
  43633. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43634. },
  43635. enumerable: true,
  43636. configurable: true
  43637. });
  43638. // Flags used to enable or disable a type of texture for all Standard Materials
  43639. StandardMaterial._DiffuseTextureEnabled = true;
  43640. StandardMaterial._AmbientTextureEnabled = true;
  43641. StandardMaterial._OpacityTextureEnabled = true;
  43642. StandardMaterial._ReflectionTextureEnabled = true;
  43643. StandardMaterial._EmissiveTextureEnabled = true;
  43644. StandardMaterial._SpecularTextureEnabled = true;
  43645. StandardMaterial._BumpTextureEnabled = true;
  43646. StandardMaterial._LightmapTextureEnabled = true;
  43647. StandardMaterial._RefractionTextureEnabled = true;
  43648. StandardMaterial._ColorGradingTextureEnabled = true;
  43649. StandardMaterial._FresnelEnabled = true;
  43650. __decorate([
  43651. BABYLON.serializeAsTexture("diffuseTexture")
  43652. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43653. __decorate([
  43654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43655. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43656. __decorate([
  43657. BABYLON.serializeAsTexture("ambientTexture")
  43658. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43659. __decorate([
  43660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43661. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43662. __decorate([
  43663. BABYLON.serializeAsTexture("opacityTexture")
  43664. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43665. __decorate([
  43666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43667. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43668. __decorate([
  43669. BABYLON.serializeAsTexture("reflectionTexture")
  43670. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43671. __decorate([
  43672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43673. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43674. __decorate([
  43675. BABYLON.serializeAsTexture("emissiveTexture")
  43676. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43677. __decorate([
  43678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43679. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43680. __decorate([
  43681. BABYLON.serializeAsTexture("specularTexture")
  43682. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43683. __decorate([
  43684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43685. ], StandardMaterial.prototype, "specularTexture", void 0);
  43686. __decorate([
  43687. BABYLON.serializeAsTexture("bumpTexture")
  43688. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43689. __decorate([
  43690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43691. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43692. __decorate([
  43693. BABYLON.serializeAsTexture("lightmapTexture")
  43694. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43695. __decorate([
  43696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43697. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43698. __decorate([
  43699. BABYLON.serializeAsTexture("refractionTexture")
  43700. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43701. __decorate([
  43702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43703. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43704. __decorate([
  43705. BABYLON.serializeAsColor3("ambient")
  43706. ], StandardMaterial.prototype, "ambientColor", void 0);
  43707. __decorate([
  43708. BABYLON.serializeAsColor3("diffuse")
  43709. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43710. __decorate([
  43711. BABYLON.serializeAsColor3("specular")
  43712. ], StandardMaterial.prototype, "specularColor", void 0);
  43713. __decorate([
  43714. BABYLON.serializeAsColor3("emissive")
  43715. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43716. __decorate([
  43717. BABYLON.serialize()
  43718. ], StandardMaterial.prototype, "specularPower", void 0);
  43719. __decorate([
  43720. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43721. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43722. __decorate([
  43723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43724. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43725. __decorate([
  43726. BABYLON.serialize("useEmissiveAsIllumination")
  43727. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43728. __decorate([
  43729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43730. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43731. __decorate([
  43732. BABYLON.serialize("linkEmissiveWithDiffuse")
  43733. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43734. __decorate([
  43735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43736. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43737. __decorate([
  43738. BABYLON.serialize("useSpecularOverAlpha")
  43739. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43740. __decorate([
  43741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43742. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43743. __decorate([
  43744. BABYLON.serialize("useReflectionOverAlpha")
  43745. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43746. __decorate([
  43747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43748. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43749. __decorate([
  43750. BABYLON.serialize("disableLighting")
  43751. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43752. __decorate([
  43753. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43754. ], StandardMaterial.prototype, "disableLighting", void 0);
  43755. __decorate([
  43756. BABYLON.serialize("useObjectSpaceNormalMap")
  43757. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43758. __decorate([
  43759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43760. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43761. __decorate([
  43762. BABYLON.serialize("useParallax")
  43763. ], StandardMaterial.prototype, "_useParallax", void 0);
  43764. __decorate([
  43765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43766. ], StandardMaterial.prototype, "useParallax", void 0);
  43767. __decorate([
  43768. BABYLON.serialize("useParallaxOcclusion")
  43769. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43770. __decorate([
  43771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43772. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43773. __decorate([
  43774. BABYLON.serialize()
  43775. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43776. __decorate([
  43777. BABYLON.serialize("roughness")
  43778. ], StandardMaterial.prototype, "_roughness", void 0);
  43779. __decorate([
  43780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43781. ], StandardMaterial.prototype, "roughness", void 0);
  43782. __decorate([
  43783. BABYLON.serialize()
  43784. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43785. __decorate([
  43786. BABYLON.serialize()
  43787. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43788. __decorate([
  43789. BABYLON.serialize()
  43790. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43791. __decorate([
  43792. BABYLON.serialize("useLightmapAsShadowmap")
  43793. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43794. __decorate([
  43795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43796. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43797. __decorate([
  43798. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43799. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43800. __decorate([
  43801. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43802. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43803. __decorate([
  43804. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43805. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43806. __decorate([
  43807. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43808. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43809. __decorate([
  43810. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43811. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43812. __decorate([
  43813. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43814. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43815. __decorate([
  43816. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43817. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43818. __decorate([
  43819. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43820. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43821. __decorate([
  43822. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43823. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43824. __decorate([
  43825. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43826. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43827. __decorate([
  43828. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43829. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43830. __decorate([
  43831. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43832. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43833. __decorate([
  43834. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43835. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43836. __decorate([
  43837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43838. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43839. __decorate([
  43840. BABYLON.serialize("maxSimultaneousLights")
  43841. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43842. __decorate([
  43843. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43844. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43845. __decorate([
  43846. BABYLON.serialize("invertNormalMapX")
  43847. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43848. __decorate([
  43849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43850. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43851. __decorate([
  43852. BABYLON.serialize("invertNormalMapY")
  43853. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43854. __decorate([
  43855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43856. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43857. __decorate([
  43858. BABYLON.serialize("twoSidedLighting")
  43859. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43860. __decorate([
  43861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43862. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43863. __decorate([
  43864. BABYLON.serialize()
  43865. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43866. return StandardMaterial;
  43867. }(BABYLON.PushMaterial));
  43868. BABYLON.StandardMaterial = StandardMaterial;
  43869. })(BABYLON || (BABYLON = {}));
  43870. //# sourceMappingURL=babylon.standardMaterial.js.map
  43871. var BABYLON;
  43872. (function (BABYLON) {
  43873. /**
  43874. * Class representing spherical polynomial coefficients to the 3rd degree
  43875. */
  43876. var SphericalPolynomial = /** @class */ (function () {
  43877. function SphericalPolynomial() {
  43878. /**
  43879. * The x coefficients of the spherical polynomial
  43880. */
  43881. this.x = BABYLON.Vector3.Zero();
  43882. /**
  43883. * The y coefficients of the spherical polynomial
  43884. */
  43885. this.y = BABYLON.Vector3.Zero();
  43886. /**
  43887. * The z coefficients of the spherical polynomial
  43888. */
  43889. this.z = BABYLON.Vector3.Zero();
  43890. /**
  43891. * The xx coefficients of the spherical polynomial
  43892. */
  43893. this.xx = BABYLON.Vector3.Zero();
  43894. /**
  43895. * The yy coefficients of the spherical polynomial
  43896. */
  43897. this.yy = BABYLON.Vector3.Zero();
  43898. /**
  43899. * The zz coefficients of the spherical polynomial
  43900. */
  43901. this.zz = BABYLON.Vector3.Zero();
  43902. /**
  43903. * The xy coefficients of the spherical polynomial
  43904. */
  43905. this.xy = BABYLON.Vector3.Zero();
  43906. /**
  43907. * The yz coefficients of the spherical polynomial
  43908. */
  43909. this.yz = BABYLON.Vector3.Zero();
  43910. /**
  43911. * The zx coefficients of the spherical polynomial
  43912. */
  43913. this.zx = BABYLON.Vector3.Zero();
  43914. }
  43915. /**
  43916. * Adds an ambient color to the spherical polynomial
  43917. * @param color the color to add
  43918. */
  43919. SphericalPolynomial.prototype.addAmbient = function (color) {
  43920. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43921. this.xx = this.xx.add(colorVector);
  43922. this.yy = this.yy.add(colorVector);
  43923. this.zz = this.zz.add(colorVector);
  43924. };
  43925. /**
  43926. * Scales the spherical polynomial by the given amount
  43927. * @param scale the amount to scale
  43928. */
  43929. SphericalPolynomial.prototype.scale = function (scale) {
  43930. this.x = this.x.scale(scale);
  43931. this.y = this.y.scale(scale);
  43932. this.z = this.z.scale(scale);
  43933. this.xx = this.xx.scale(scale);
  43934. this.yy = this.yy.scale(scale);
  43935. this.zz = this.zz.scale(scale);
  43936. this.yz = this.yz.scale(scale);
  43937. this.zx = this.zx.scale(scale);
  43938. this.xy = this.xy.scale(scale);
  43939. };
  43940. /**
  43941. * Gets the spherical polynomial from harmonics
  43942. * @param harmonics the spherical harmonics
  43943. * @returns the spherical polynomial
  43944. */
  43945. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43946. var result = new SphericalPolynomial();
  43947. result.x = harmonics.l11.scale(1.02333);
  43948. result.y = harmonics.l1_1.scale(1.02333);
  43949. result.z = harmonics.l10.scale(1.02333);
  43950. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43951. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43952. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43953. result.yz = harmonics.l2_1.scale(0.858086);
  43954. result.zx = harmonics.l21.scale(0.858086);
  43955. result.xy = harmonics.l2_2.scale(0.858086);
  43956. result.scale(1.0 / Math.PI);
  43957. return result;
  43958. };
  43959. /**
  43960. * Constructs a spherical polynomial from an array.
  43961. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43962. * @returns the spherical polynomial
  43963. */
  43964. SphericalPolynomial.FromArray = function (data) {
  43965. var sp = new SphericalPolynomial();
  43966. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43967. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43968. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43969. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43970. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43971. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43972. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43973. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43974. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43975. return sp;
  43976. };
  43977. return SphericalPolynomial;
  43978. }());
  43979. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43980. /**
  43981. * Class representing spherical harmonics coefficients to the 3rd degree
  43982. */
  43983. var SphericalHarmonics = /** @class */ (function () {
  43984. function SphericalHarmonics() {
  43985. /**
  43986. * The l0,0 coefficients of the spherical harmonics
  43987. */
  43988. this.l00 = BABYLON.Vector3.Zero();
  43989. /**
  43990. * The l1,-1 coefficients of the spherical harmonics
  43991. */
  43992. this.l1_1 = BABYLON.Vector3.Zero();
  43993. /**
  43994. * The l1,0 coefficients of the spherical harmonics
  43995. */
  43996. this.l10 = BABYLON.Vector3.Zero();
  43997. /**
  43998. * The l1,1 coefficients of the spherical harmonics
  43999. */
  44000. this.l11 = BABYLON.Vector3.Zero();
  44001. /**
  44002. * The l2,-2 coefficients of the spherical harmonics
  44003. */
  44004. this.l2_2 = BABYLON.Vector3.Zero();
  44005. /**
  44006. * The l2,-1 coefficients of the spherical harmonics
  44007. */
  44008. this.l2_1 = BABYLON.Vector3.Zero();
  44009. /**
  44010. * The l2,0 coefficients of the spherical harmonics
  44011. */
  44012. this.l20 = BABYLON.Vector3.Zero();
  44013. /**
  44014. * The l2,1 coefficients of the spherical harmonics
  44015. */
  44016. this.l21 = BABYLON.Vector3.Zero();
  44017. /**
  44018. * The l2,2 coefficients of the spherical harmonics
  44019. */
  44020. this.lL22 = BABYLON.Vector3.Zero();
  44021. }
  44022. /**
  44023. * Adds a light to the spherical harmonics
  44024. * @param direction the direction of the light
  44025. * @param color the color of the light
  44026. * @param deltaSolidAngle the delta solid angle of the light
  44027. */
  44028. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44029. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44030. var c = colorVector.scale(deltaSolidAngle);
  44031. this.l00 = this.l00.add(c.scale(0.282095));
  44032. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44033. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44034. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44035. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44036. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44037. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44038. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44039. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44040. };
  44041. /**
  44042. * Scales the spherical harmonics by the given amount
  44043. * @param scale the amount to scale
  44044. */
  44045. SphericalHarmonics.prototype.scale = function (scale) {
  44046. this.l00 = this.l00.scale(scale);
  44047. this.l1_1 = this.l1_1.scale(scale);
  44048. this.l10 = this.l10.scale(scale);
  44049. this.l11 = this.l11.scale(scale);
  44050. this.l2_2 = this.l2_2.scale(scale);
  44051. this.l2_1 = this.l2_1.scale(scale);
  44052. this.l20 = this.l20.scale(scale);
  44053. this.l21 = this.l21.scale(scale);
  44054. this.lL22 = this.lL22.scale(scale);
  44055. };
  44056. /**
  44057. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44058. *
  44059. * ```
  44060. * E_lm = A_l * L_lm
  44061. * ```
  44062. *
  44063. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44064. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44065. * the scaling factors are given in equation 9.
  44066. */
  44067. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44068. // Constant (Band 0)
  44069. this.l00 = this.l00.scale(3.141593);
  44070. // Linear (Band 1)
  44071. this.l1_1 = this.l1_1.scale(2.094395);
  44072. this.l10 = this.l10.scale(2.094395);
  44073. this.l11 = this.l11.scale(2.094395);
  44074. // Quadratic (Band 2)
  44075. this.l2_2 = this.l2_2.scale(0.785398);
  44076. this.l2_1 = this.l2_1.scale(0.785398);
  44077. this.l20 = this.l20.scale(0.785398);
  44078. this.l21 = this.l21.scale(0.785398);
  44079. this.lL22 = this.lL22.scale(0.785398);
  44080. };
  44081. /**
  44082. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44083. *
  44084. * ```
  44085. * L = (1/pi) * E * rho
  44086. * ```
  44087. *
  44088. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44089. */
  44090. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44091. this.scale(1.0 / Math.PI);
  44092. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44093. // (The pixel shader must apply albedo after texture fetches, etc).
  44094. };
  44095. /**
  44096. * Gets the spherical harmonics from polynomial
  44097. * @param polynomial the spherical polynomial
  44098. * @returns the spherical harmonics
  44099. */
  44100. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44101. var result = new SphericalHarmonics();
  44102. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44103. result.l1_1 = polynomial.y.scale(0.977204);
  44104. result.l10 = polynomial.z.scale(0.977204);
  44105. result.l11 = polynomial.x.scale(0.977204);
  44106. result.l2_2 = polynomial.xy.scale(1.16538);
  44107. result.l2_1 = polynomial.yz.scale(1.16538);
  44108. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44109. result.l21 = polynomial.zx.scale(1.16538);
  44110. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44111. result.scale(Math.PI);
  44112. return result;
  44113. };
  44114. /**
  44115. * Constructs a spherical harmonics from an array.
  44116. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44117. * @returns the spherical harmonics
  44118. */
  44119. SphericalHarmonics.FromArray = function (data) {
  44120. var sh = new SphericalHarmonics();
  44121. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44122. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44123. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44124. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44125. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44126. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44127. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44128. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44129. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44130. return sh;
  44131. };
  44132. return SphericalHarmonics;
  44133. }());
  44134. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44135. })(BABYLON || (BABYLON = {}));
  44136. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44137. var BABYLON;
  44138. (function (BABYLON) {
  44139. var FileFaceOrientation = /** @class */ (function () {
  44140. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44141. this.name = name;
  44142. this.worldAxisForNormal = worldAxisForNormal;
  44143. this.worldAxisForFileX = worldAxisForFileX;
  44144. this.worldAxisForFileY = worldAxisForFileY;
  44145. }
  44146. return FileFaceOrientation;
  44147. }());
  44148. ;
  44149. /**
  44150. * Helper class dealing with the extraction of spherical polynomial dataArray
  44151. * from a cube map.
  44152. */
  44153. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44154. function CubeMapToSphericalPolynomialTools() {
  44155. }
  44156. /**
  44157. * Converts a texture to the according Spherical Polynomial data.
  44158. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44159. *
  44160. * @param texture The texture to extract the information from.
  44161. * @return The Spherical Polynomial data.
  44162. */
  44163. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44164. if (!texture.isCube) {
  44165. // Only supports cube Textures currently.
  44166. return null;
  44167. }
  44168. var size = texture.getSize().width;
  44169. var right = texture.readPixels(0);
  44170. var left = texture.readPixels(1);
  44171. var up;
  44172. var down;
  44173. if (texture.isRenderTarget) {
  44174. up = texture.readPixels(3);
  44175. down = texture.readPixels(2);
  44176. }
  44177. else {
  44178. up = texture.readPixels(2);
  44179. down = texture.readPixels(3);
  44180. }
  44181. var front = texture.readPixels(4);
  44182. var back = texture.readPixels(5);
  44183. var gammaSpace = texture.gammaSpace;
  44184. // Always read as RGBA.
  44185. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44186. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44187. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44188. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44189. }
  44190. var cubeInfo = {
  44191. size: size,
  44192. right: right,
  44193. left: left,
  44194. up: up,
  44195. down: down,
  44196. front: front,
  44197. back: back,
  44198. format: format,
  44199. type: type,
  44200. gammaSpace: gammaSpace,
  44201. };
  44202. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44203. };
  44204. /**
  44205. * Converts a cubemap to the according Spherical Polynomial data.
  44206. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44207. *
  44208. * @param cubeInfo The Cube map to extract the information from.
  44209. * @return The Spherical Polynomial data.
  44210. */
  44211. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44212. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44213. var totalSolidAngle = 0.0;
  44214. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44215. var du = 2.0 / cubeInfo.size;
  44216. var dv = du;
  44217. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44218. var minUV = du * 0.5 - 1.0;
  44219. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44220. var fileFace = this.FileFaces[faceIndex];
  44221. var dataArray = cubeInfo[fileFace.name];
  44222. var v = minUV;
  44223. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44224. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44225. // Because SP is still linear, so summation is fine in that basis.
  44226. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44227. for (var y = 0; y < cubeInfo.size; y++) {
  44228. var u = minUV;
  44229. for (var x = 0; x < cubeInfo.size; x++) {
  44230. // World direction (not normalised)
  44231. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44232. worldDirection.normalize();
  44233. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44234. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44235. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44236. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44237. // Handle Integer types.
  44238. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44239. r /= 255;
  44240. g /= 255;
  44241. b /= 255;
  44242. }
  44243. // Handle Gamma space textures.
  44244. if (cubeInfo.gammaSpace) {
  44245. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44246. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44247. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44248. }
  44249. var color = new BABYLON.Color3(r, g, b);
  44250. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44251. totalSolidAngle += deltaSolidAngle;
  44252. u += du;
  44253. }
  44254. v += dv;
  44255. }
  44256. }
  44257. // Solid angle for entire sphere is 4*pi
  44258. var sphereSolidAngle = 4.0 * Math.PI;
  44259. // Adjust the solid angle to allow for how many faces we processed.
  44260. var facesProcessed = 6.0;
  44261. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44262. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44263. // This is needed because the numerical integration over the cube uses a
  44264. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44265. // and also to compensate for accumulative error due to float precision in the summation.
  44266. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44267. sphericalHarmonics.scale(correctionFactor);
  44268. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44269. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44270. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44271. };
  44272. CubeMapToSphericalPolynomialTools.FileFaces = [
  44273. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44274. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44275. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44276. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44277. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44278. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44279. ];
  44280. return CubeMapToSphericalPolynomialTools;
  44281. }());
  44282. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44283. })(BABYLON || (BABYLON = {}));
  44284. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44285. var BABYLON;
  44286. (function (BABYLON) {
  44287. /**
  44288. * Manages the defines for the PBR Material.
  44289. * @hiddenChildren
  44290. */
  44291. var PBRMaterialDefines = /** @class */ (function (_super) {
  44292. __extends(PBRMaterialDefines, _super);
  44293. /**
  44294. * Initializes the PBR Material defines.
  44295. */
  44296. function PBRMaterialDefines() {
  44297. var _this = _super.call(this) || this;
  44298. _this.PBR = true;
  44299. _this.MAINUV1 = false;
  44300. _this.MAINUV2 = false;
  44301. _this.UV1 = false;
  44302. _this.UV2 = false;
  44303. _this.ALBEDO = false;
  44304. _this.ALBEDODIRECTUV = 0;
  44305. _this.VERTEXCOLOR = false;
  44306. _this.AMBIENT = false;
  44307. _this.AMBIENTDIRECTUV = 0;
  44308. _this.AMBIENTINGRAYSCALE = false;
  44309. _this.OPACITY = false;
  44310. _this.VERTEXALPHA = false;
  44311. _this.OPACITYDIRECTUV = 0;
  44312. _this.OPACITYRGB = false;
  44313. _this.ALPHATEST = false;
  44314. _this.DEPTHPREPASS = false;
  44315. _this.ALPHABLEND = false;
  44316. _this.ALPHAFROMALBEDO = false;
  44317. _this.ALPHATESTVALUE = "0.5";
  44318. _this.SPECULAROVERALPHA = false;
  44319. _this.RADIANCEOVERALPHA = false;
  44320. _this.ALPHAFRESNEL = false;
  44321. _this.LINEARALPHAFRESNEL = false;
  44322. _this.PREMULTIPLYALPHA = false;
  44323. _this.EMISSIVE = false;
  44324. _this.EMISSIVEDIRECTUV = 0;
  44325. _this.REFLECTIVITY = false;
  44326. _this.REFLECTIVITYDIRECTUV = 0;
  44327. _this.SPECULARTERM = false;
  44328. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44329. _this.MICROSURFACEAUTOMATIC = false;
  44330. _this.LODBASEDMICROSFURACE = false;
  44331. _this.MICROSURFACEMAP = false;
  44332. _this.MICROSURFACEMAPDIRECTUV = 0;
  44333. _this.METALLICWORKFLOW = false;
  44334. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44335. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44336. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44337. _this.AOSTOREINMETALMAPRED = false;
  44338. _this.ENVIRONMENTBRDF = false;
  44339. _this.NORMAL = false;
  44340. _this.TANGENT = false;
  44341. _this.BUMP = false;
  44342. _this.BUMPDIRECTUV = 0;
  44343. _this.OBJECTSPACE_NORMALMAP = false;
  44344. _this.PARALLAX = false;
  44345. _this.PARALLAXOCCLUSION = false;
  44346. _this.NORMALXYSCALE = true;
  44347. _this.LIGHTMAP = false;
  44348. _this.LIGHTMAPDIRECTUV = 0;
  44349. _this.USELIGHTMAPASSHADOWMAP = false;
  44350. _this.GAMMALIGHTMAP = false;
  44351. _this.REFLECTION = false;
  44352. _this.REFLECTIONMAP_3D = false;
  44353. _this.REFLECTIONMAP_SPHERICAL = false;
  44354. _this.REFLECTIONMAP_PLANAR = false;
  44355. _this.REFLECTIONMAP_CUBIC = false;
  44356. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44357. _this.REFLECTIONMAP_PROJECTION = false;
  44358. _this.REFLECTIONMAP_SKYBOX = false;
  44359. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44360. _this.REFLECTIONMAP_EXPLICIT = false;
  44361. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44362. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44363. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44364. _this.INVERTCUBICMAP = false;
  44365. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44366. _this.USESPHERICALINVERTEX = false;
  44367. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44368. _this.LODINREFLECTIONALPHA = false;
  44369. _this.GAMMAREFLECTION = false;
  44370. _this.RGBDREFLECTION = false;
  44371. _this.RADIANCEOCCLUSION = false;
  44372. _this.HORIZONOCCLUSION = false;
  44373. _this.REFRACTION = false;
  44374. _this.REFRACTIONMAP_3D = false;
  44375. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44376. _this.LODINREFRACTIONALPHA = false;
  44377. _this.GAMMAREFRACTION = false;
  44378. _this.RGBDREFRACTION = false;
  44379. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44380. _this.INSTANCES = false;
  44381. _this.NUM_BONE_INFLUENCERS = 0;
  44382. _this.BonesPerMesh = 0;
  44383. _this.NONUNIFORMSCALING = false;
  44384. _this.MORPHTARGETS = false;
  44385. _this.MORPHTARGETS_NORMAL = false;
  44386. _this.MORPHTARGETS_TANGENT = false;
  44387. _this.NUM_MORPH_INFLUENCERS = 0;
  44388. _this.IMAGEPROCESSING = false;
  44389. _this.VIGNETTE = false;
  44390. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44391. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44392. _this.TONEMAPPING = false;
  44393. _this.TONEMAPPING_ACES = false;
  44394. _this.CONTRAST = false;
  44395. _this.COLORCURVES = false;
  44396. _this.COLORGRADING = false;
  44397. _this.COLORGRADING3D = false;
  44398. _this.SAMPLER3DGREENDEPTH = false;
  44399. _this.SAMPLER3DBGRMAP = false;
  44400. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44401. _this.EXPOSURE = false;
  44402. _this.USEPHYSICALLIGHTFALLOFF = false;
  44403. _this.USEGLTFLIGHTFALLOFF = false;
  44404. _this.TWOSIDEDLIGHTING = false;
  44405. _this.SHADOWFLOAT = false;
  44406. _this.CLIPPLANE = false;
  44407. _this.CLIPPLANE2 = false;
  44408. _this.CLIPPLANE3 = false;
  44409. _this.CLIPPLANE4 = false;
  44410. _this.POINTSIZE = false;
  44411. _this.FOG = false;
  44412. _this.LOGARITHMICDEPTH = false;
  44413. _this.FORCENORMALFORWARD = false;
  44414. _this.SPECULARAA = false;
  44415. _this.UNLIT = false;
  44416. _this.rebuild();
  44417. return _this;
  44418. }
  44419. /**
  44420. * Resets the PBR Material defines.
  44421. */
  44422. PBRMaterialDefines.prototype.reset = function () {
  44423. _super.prototype.reset.call(this);
  44424. this.ALPHATESTVALUE = "0.5";
  44425. this.PBR = true;
  44426. };
  44427. return PBRMaterialDefines;
  44428. }(BABYLON.MaterialDefines));
  44429. /**
  44430. * The Physically based material base class of BJS.
  44431. *
  44432. * This offers the main features of a standard PBR material.
  44433. * For more information, please refer to the documentation :
  44434. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44435. */
  44436. var PBRBaseMaterial = /** @class */ (function (_super) {
  44437. __extends(PBRBaseMaterial, _super);
  44438. /**
  44439. * Instantiates a new PBRMaterial instance.
  44440. *
  44441. * @param name The material name
  44442. * @param scene The scene the material will be use in.
  44443. */
  44444. function PBRBaseMaterial(name, scene) {
  44445. var _this = _super.call(this, name, scene) || this;
  44446. /**
  44447. * Intensity of the direct lights e.g. the four lights available in your scene.
  44448. * This impacts both the direct diffuse and specular highlights.
  44449. */
  44450. _this._directIntensity = 1.0;
  44451. /**
  44452. * Intensity of the emissive part of the material.
  44453. * This helps controlling the emissive effect without modifying the emissive color.
  44454. */
  44455. _this._emissiveIntensity = 1.0;
  44456. /**
  44457. * Intensity of the environment e.g. how much the environment will light the object
  44458. * either through harmonics for rough material or through the refelction for shiny ones.
  44459. */
  44460. _this._environmentIntensity = 1.0;
  44461. /**
  44462. * This is a special control allowing the reduction of the specular highlights coming from the
  44463. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44464. */
  44465. _this._specularIntensity = 1.0;
  44466. /**
  44467. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44468. */
  44469. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44470. /**
  44471. * Debug Control allowing disabling the bump map on this material.
  44472. */
  44473. _this._disableBumpMap = false;
  44474. /**
  44475. * AKA Occlusion Texture Intensity in other nomenclature.
  44476. */
  44477. _this._ambientTextureStrength = 1.0;
  44478. /**
  44479. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44480. * 1 means it completely occludes it
  44481. * 0 mean it has no impact
  44482. */
  44483. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44484. /**
  44485. * The color of a material in ambient lighting.
  44486. */
  44487. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44488. /**
  44489. * AKA Diffuse Color in other nomenclature.
  44490. */
  44491. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44492. /**
  44493. * AKA Specular Color in other nomenclature.
  44494. */
  44495. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44496. /**
  44497. * The color applied when light is reflected from a material.
  44498. */
  44499. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44500. /**
  44501. * The color applied when light is emitted from a material.
  44502. */
  44503. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44504. /**
  44505. * AKA Glossiness in other nomenclature.
  44506. */
  44507. _this._microSurface = 0.9;
  44508. /**
  44509. * source material index of refraction (IOR)' / 'destination material IOR.
  44510. */
  44511. _this._indexOfRefraction = 0.66;
  44512. /**
  44513. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44514. */
  44515. _this._invertRefractionY = false;
  44516. /**
  44517. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44518. * Materials half opaque for instance using refraction could benefit from this control.
  44519. */
  44520. _this._linkRefractionWithTransparency = false;
  44521. /**
  44522. * Specifies that the material will use the light map as a show map.
  44523. */
  44524. _this._useLightmapAsShadowmap = false;
  44525. /**
  44526. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44527. * makes the reflect vector face the model (under horizon).
  44528. */
  44529. _this._useHorizonOcclusion = true;
  44530. /**
  44531. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44532. * too much the area relying on ambient texture to define their ambient occlusion.
  44533. */
  44534. _this._useRadianceOcclusion = true;
  44535. /**
  44536. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44537. */
  44538. _this._useAlphaFromAlbedoTexture = false;
  44539. /**
  44540. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44541. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44542. */
  44543. _this._useSpecularOverAlpha = true;
  44544. /**
  44545. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44546. */
  44547. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44548. /**
  44549. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44550. */
  44551. _this._useRoughnessFromMetallicTextureAlpha = true;
  44552. /**
  44553. * Specifies if the metallic texture contains the roughness information in its green channel.
  44554. */
  44555. _this._useRoughnessFromMetallicTextureGreen = false;
  44556. /**
  44557. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44558. */
  44559. _this._useMetallnessFromMetallicTextureBlue = false;
  44560. /**
  44561. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44562. */
  44563. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44564. /**
  44565. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44566. */
  44567. _this._useAmbientInGrayScale = false;
  44568. /**
  44569. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44570. * The material will try to infer what glossiness each pixel should be.
  44571. */
  44572. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44573. /**
  44574. * Defines the falloff type used in this material.
  44575. * It by default is Physical.
  44576. */
  44577. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44578. /**
  44579. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44580. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44581. */
  44582. _this._useRadianceOverAlpha = true;
  44583. /**
  44584. * Allows using an object space normal map (instead of tangent space).
  44585. */
  44586. _this._useObjectSpaceNormalMap = false;
  44587. /**
  44588. * Allows using the bump map in parallax mode.
  44589. */
  44590. _this._useParallax = false;
  44591. /**
  44592. * Allows using the bump map in parallax occlusion mode.
  44593. */
  44594. _this._useParallaxOcclusion = false;
  44595. /**
  44596. * Controls the scale bias of the parallax mode.
  44597. */
  44598. _this._parallaxScaleBias = 0.05;
  44599. /**
  44600. * If sets to true, disables all the lights affecting the material.
  44601. */
  44602. _this._disableLighting = false;
  44603. /**
  44604. * Number of Simultaneous lights allowed on the material.
  44605. */
  44606. _this._maxSimultaneousLights = 4;
  44607. /**
  44608. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44609. */
  44610. _this._invertNormalMapX = false;
  44611. /**
  44612. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44613. */
  44614. _this._invertNormalMapY = false;
  44615. /**
  44616. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44617. */
  44618. _this._twoSidedLighting = false;
  44619. /**
  44620. * Defines the alpha limits in alpha test mode.
  44621. */
  44622. _this._alphaCutOff = 0.4;
  44623. /**
  44624. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44625. */
  44626. _this._forceAlphaTest = false;
  44627. /**
  44628. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44629. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44630. */
  44631. _this._useAlphaFresnel = false;
  44632. /**
  44633. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44634. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44635. */
  44636. _this._useLinearAlphaFresnel = false;
  44637. /**
  44638. * The transparency mode of the material.
  44639. */
  44640. _this._transparencyMode = null;
  44641. /**
  44642. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44643. * from cos thetav and roughness:
  44644. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44645. */
  44646. _this._environmentBRDFTexture = null;
  44647. /**
  44648. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44649. */
  44650. _this._forceIrradianceInFragment = false;
  44651. /**
  44652. * Force normal to face away from face.
  44653. */
  44654. _this._forceNormalForward = false;
  44655. /**
  44656. * Enables specular anti aliasing in the PBR shader.
  44657. * It will both interacts on the Geometry for analytical and IBL lighting.
  44658. * It also prefilter the roughness map based on the bump values.
  44659. */
  44660. _this._enableSpecularAntiAliasing = false;
  44661. /**
  44662. * Stores the available render targets.
  44663. */
  44664. _this._renderTargets = new BABYLON.SmartArray(16);
  44665. /**
  44666. * Sets the global ambient color for the material used in lighting calculations.
  44667. */
  44668. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44669. /**
  44670. * If set to true, no lighting calculations will be applied.
  44671. */
  44672. _this._unlit = false;
  44673. // Setup the default processing configuration to the scene.
  44674. _this._attachImageProcessingConfiguration(null);
  44675. _this.getRenderTargetTextures = function () {
  44676. _this._renderTargets.reset();
  44677. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44678. _this._renderTargets.push(_this._reflectionTexture);
  44679. }
  44680. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44681. _this._renderTargets.push(_this._refractionTexture);
  44682. }
  44683. return _this._renderTargets;
  44684. };
  44685. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44686. return _this;
  44687. }
  44688. /**
  44689. * Attaches a new image processing configuration to the PBR Material.
  44690. * @param configuration
  44691. */
  44692. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44693. var _this = this;
  44694. if (configuration === this._imageProcessingConfiguration) {
  44695. return;
  44696. }
  44697. // Detaches observer.
  44698. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44699. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44700. }
  44701. // Pick the scene configuration if needed.
  44702. if (!configuration) {
  44703. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44704. }
  44705. else {
  44706. this._imageProcessingConfiguration = configuration;
  44707. }
  44708. // Attaches observer.
  44709. if (this._imageProcessingConfiguration) {
  44710. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44711. _this._markAllSubMeshesAsImageProcessingDirty();
  44712. });
  44713. }
  44714. };
  44715. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44716. /**
  44717. * Gets a boolean indicating that current material needs to register RTT
  44718. */
  44719. get: function () {
  44720. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44721. return true;
  44722. }
  44723. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44724. return true;
  44725. }
  44726. return false;
  44727. },
  44728. enumerable: true,
  44729. configurable: true
  44730. });
  44731. /**
  44732. * Gets the name of the material class.
  44733. */
  44734. PBRBaseMaterial.prototype.getClassName = function () {
  44735. return "PBRBaseMaterial";
  44736. };
  44737. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44738. /**
  44739. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44740. */
  44741. get: function () {
  44742. return this._useLogarithmicDepth;
  44743. },
  44744. /**
  44745. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44746. */
  44747. set: function (value) {
  44748. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44749. },
  44750. enumerable: true,
  44751. configurable: true
  44752. });
  44753. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44754. /**
  44755. * Gets the current transparency mode.
  44756. */
  44757. get: function () {
  44758. return this._transparencyMode;
  44759. },
  44760. /**
  44761. * Sets the transparency mode of the material.
  44762. *
  44763. * | Value | Type | Description |
  44764. * | ----- | ----------------------------------- | ----------- |
  44765. * | 0 | OPAQUE | |
  44766. * | 1 | ALPHATEST | |
  44767. * | 2 | ALPHABLEND | |
  44768. * | 3 | ALPHATESTANDBLEND | |
  44769. *
  44770. */
  44771. set: function (value) {
  44772. if (this._transparencyMode === value) {
  44773. return;
  44774. }
  44775. this._transparencyMode = value;
  44776. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44777. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44778. },
  44779. enumerable: true,
  44780. configurable: true
  44781. });
  44782. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44783. /**
  44784. * Returns true if alpha blending should be disabled.
  44785. */
  44786. get: function () {
  44787. return (this._linkRefractionWithTransparency ||
  44788. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44789. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44790. },
  44791. enumerable: true,
  44792. configurable: true
  44793. });
  44794. /**
  44795. * Specifies whether or not this material should be rendered in alpha blend mode.
  44796. */
  44797. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44798. if (this._disableAlphaBlending) {
  44799. return false;
  44800. }
  44801. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44802. };
  44803. /**
  44804. * Specifies if the mesh will require alpha blending.
  44805. * @param mesh - BJS mesh.
  44806. */
  44807. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44808. if (this._disableAlphaBlending) {
  44809. return false;
  44810. }
  44811. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44812. };
  44813. /**
  44814. * Specifies whether or not this material should be rendered in alpha test mode.
  44815. */
  44816. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44817. if (this._forceAlphaTest) {
  44818. return true;
  44819. }
  44820. if (this._linkRefractionWithTransparency) {
  44821. return false;
  44822. }
  44823. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44824. };
  44825. /**
  44826. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44827. */
  44828. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44829. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44830. };
  44831. /**
  44832. * Gets the texture used for the alpha test.
  44833. */
  44834. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44835. return this._albedoTexture;
  44836. };
  44837. /**
  44838. * Specifies that the submesh is ready to be used.
  44839. * @param mesh - BJS mesh.
  44840. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44841. * @param useInstances - Specifies that instances should be used.
  44842. * @returns - boolean indicating that the submesh is ready or not.
  44843. */
  44844. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44845. if (subMesh.effect && this.isFrozen) {
  44846. if (this._wasPreviouslyReady) {
  44847. return true;
  44848. }
  44849. }
  44850. if (!subMesh._materialDefines) {
  44851. subMesh._materialDefines = new PBRMaterialDefines();
  44852. }
  44853. var defines = subMesh._materialDefines;
  44854. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44855. if (defines._renderId === this.getScene().getRenderId()) {
  44856. return true;
  44857. }
  44858. }
  44859. var scene = this.getScene();
  44860. var engine = scene.getEngine();
  44861. if (defines._areTexturesDirty) {
  44862. if (scene.texturesEnabled) {
  44863. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44864. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44865. return false;
  44866. }
  44867. }
  44868. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44869. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44870. return false;
  44871. }
  44872. }
  44873. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44874. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44875. return false;
  44876. }
  44877. }
  44878. var reflectionTexture = this._getReflectionTexture();
  44879. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44880. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44881. return false;
  44882. }
  44883. }
  44884. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44885. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44886. return false;
  44887. }
  44888. }
  44889. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44890. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44891. return false;
  44892. }
  44893. }
  44894. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44895. if (this._metallicTexture) {
  44896. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44897. return false;
  44898. }
  44899. }
  44900. else if (this._reflectivityTexture) {
  44901. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44902. return false;
  44903. }
  44904. }
  44905. if (this._microSurfaceTexture) {
  44906. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44907. return false;
  44908. }
  44909. }
  44910. }
  44911. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44912. // Bump texture cannot be not blocking.
  44913. if (!this._bumpTexture.isReady()) {
  44914. return false;
  44915. }
  44916. }
  44917. var refractionTexture = this._getRefractionTexture();
  44918. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44919. if (!refractionTexture.isReadyOrNotBlocking()) {
  44920. return false;
  44921. }
  44922. }
  44923. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44924. // This is blocking.
  44925. if (!this._environmentBRDFTexture.isReady()) {
  44926. return false;
  44927. }
  44928. }
  44929. }
  44930. }
  44931. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44932. if (!this._imageProcessingConfiguration.isReady()) {
  44933. return false;
  44934. }
  44935. }
  44936. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44937. mesh.createNormals(true);
  44938. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44939. }
  44940. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44941. if (effect) {
  44942. scene.resetCachedMaterial();
  44943. subMesh.setEffect(effect, defines);
  44944. this.buildUniformLayout();
  44945. }
  44946. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44947. return false;
  44948. }
  44949. defines._renderId = scene.getRenderId();
  44950. this._wasPreviouslyReady = true;
  44951. return true;
  44952. };
  44953. /**
  44954. * Specifies if the material uses metallic roughness workflow.
  44955. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44956. */
  44957. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44958. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44959. return true;
  44960. }
  44961. return false;
  44962. };
  44963. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44964. if (onCompiled === void 0) { onCompiled = null; }
  44965. if (onError === void 0) { onError = null; }
  44966. if (useInstances === void 0) { useInstances = null; }
  44967. if (useClipPlane === void 0) { useClipPlane = null; }
  44968. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44969. if (!defines.isDirty) {
  44970. return null;
  44971. }
  44972. defines.markAsProcessed();
  44973. var scene = this.getScene();
  44974. var engine = scene.getEngine();
  44975. // Fallbacks
  44976. var fallbacks = new BABYLON.EffectFallbacks();
  44977. var fallbackRank = 0;
  44978. if (defines.USESPHERICALINVERTEX) {
  44979. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44980. }
  44981. if (defines.FOG) {
  44982. fallbacks.addFallback(fallbackRank, "FOG");
  44983. }
  44984. if (defines.SPECULARAA) {
  44985. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44986. }
  44987. if (defines.POINTSIZE) {
  44988. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44989. }
  44990. if (defines.LOGARITHMICDEPTH) {
  44991. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44992. }
  44993. if (defines.PARALLAX) {
  44994. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44995. }
  44996. if (defines.PARALLAXOCCLUSION) {
  44997. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44998. }
  44999. if (defines.ENVIRONMENTBRDF) {
  45000. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45001. }
  45002. if (defines.TANGENT) {
  45003. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45004. }
  45005. if (defines.BUMP) {
  45006. fallbacks.addFallback(fallbackRank++, "BUMP");
  45007. }
  45008. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45009. if (defines.SPECULARTERM) {
  45010. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45011. }
  45012. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45013. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45014. }
  45015. if (defines.LIGHTMAP) {
  45016. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45017. }
  45018. if (defines.NORMAL) {
  45019. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45020. }
  45021. if (defines.AMBIENT) {
  45022. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45023. }
  45024. if (defines.EMISSIVE) {
  45025. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45026. }
  45027. if (defines.VERTEXCOLOR) {
  45028. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45029. }
  45030. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45031. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45032. }
  45033. if (defines.MORPHTARGETS) {
  45034. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45035. }
  45036. //Attributes
  45037. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45038. if (defines.NORMAL) {
  45039. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45040. }
  45041. if (defines.TANGENT) {
  45042. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45043. }
  45044. if (defines.UV1) {
  45045. attribs.push(BABYLON.VertexBuffer.UVKind);
  45046. }
  45047. if (defines.UV2) {
  45048. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45049. }
  45050. if (defines.VERTEXCOLOR) {
  45051. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45052. }
  45053. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45054. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45055. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45056. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45057. "vFogInfos", "vFogColor", "pointSize",
  45058. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45059. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45060. "mBones",
  45061. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45062. "vLightingIntensity",
  45063. "logarithmicDepthConstant",
  45064. "vSphericalX", "vSphericalY", "vSphericalZ",
  45065. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45066. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45067. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45068. "vTangentSpaceParams"
  45069. ];
  45070. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45071. "bumpSampler", "lightmapSampler", "opacitySampler",
  45072. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45073. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45074. "microSurfaceSampler", "environmentBrdfSampler"];
  45075. var uniformBuffers = ["Material", "Scene"];
  45076. if (BABYLON.ImageProcessingConfiguration) {
  45077. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45078. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45079. }
  45080. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45081. uniformsNames: uniforms,
  45082. uniformBuffersNames: uniformBuffers,
  45083. samplers: samplers,
  45084. defines: defines,
  45085. maxSimultaneousLights: this._maxSimultaneousLights
  45086. });
  45087. var join = defines.toString();
  45088. return engine.createEffect("pbr", {
  45089. attributes: attribs,
  45090. uniformsNames: uniforms,
  45091. uniformBuffersNames: uniformBuffers,
  45092. samplers: samplers,
  45093. defines: join,
  45094. fallbacks: fallbacks,
  45095. onCompiled: onCompiled,
  45096. onError: onError,
  45097. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45098. }, engine);
  45099. };
  45100. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45101. if (useInstances === void 0) { useInstances = null; }
  45102. if (useClipPlane === void 0) { useClipPlane = null; }
  45103. var scene = this.getScene();
  45104. var engine = scene.getEngine();
  45105. // Lights
  45106. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45107. defines._needNormals = true;
  45108. // Textures
  45109. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45110. if (defines._areTexturesDirty) {
  45111. defines._needUVs = false;
  45112. if (scene.texturesEnabled) {
  45113. if (scene.getEngine().getCaps().textureLOD) {
  45114. defines.LODBASEDMICROSFURACE = true;
  45115. }
  45116. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45118. }
  45119. else {
  45120. defines.ALBEDO = false;
  45121. }
  45122. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45124. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45125. }
  45126. else {
  45127. defines.AMBIENT = false;
  45128. }
  45129. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45130. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45131. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45132. }
  45133. else {
  45134. defines.OPACITY = false;
  45135. }
  45136. var reflectionTexture = this._getReflectionTexture();
  45137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45138. defines.REFLECTION = true;
  45139. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45140. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45141. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45142. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45143. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45144. defines.INVERTCUBICMAP = true;
  45145. }
  45146. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45147. switch (reflectionTexture.coordinatesMode) {
  45148. case BABYLON.Texture.EXPLICIT_MODE:
  45149. defines.REFLECTIONMAP_EXPLICIT = true;
  45150. break;
  45151. case BABYLON.Texture.PLANAR_MODE:
  45152. defines.REFLECTIONMAP_PLANAR = true;
  45153. break;
  45154. case BABYLON.Texture.PROJECTION_MODE:
  45155. defines.REFLECTIONMAP_PROJECTION = true;
  45156. break;
  45157. case BABYLON.Texture.SKYBOX_MODE:
  45158. defines.REFLECTIONMAP_SKYBOX = true;
  45159. break;
  45160. case BABYLON.Texture.SPHERICAL_MODE:
  45161. defines.REFLECTIONMAP_SPHERICAL = true;
  45162. break;
  45163. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45164. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45165. break;
  45166. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45167. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45168. break;
  45169. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45170. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45171. break;
  45172. case BABYLON.Texture.CUBIC_MODE:
  45173. case BABYLON.Texture.INVCUBIC_MODE:
  45174. default:
  45175. defines.REFLECTIONMAP_CUBIC = true;
  45176. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45177. break;
  45178. }
  45179. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45180. if (reflectionTexture.sphericalPolynomial) {
  45181. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45182. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45183. defines.USESPHERICALINVERTEX = false;
  45184. }
  45185. else {
  45186. defines.USESPHERICALINVERTEX = true;
  45187. }
  45188. }
  45189. }
  45190. else {
  45191. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45192. }
  45193. }
  45194. else {
  45195. defines.REFLECTION = false;
  45196. defines.REFLECTIONMAP_3D = false;
  45197. defines.REFLECTIONMAP_SPHERICAL = false;
  45198. defines.REFLECTIONMAP_PLANAR = false;
  45199. defines.REFLECTIONMAP_CUBIC = false;
  45200. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45201. defines.REFLECTIONMAP_PROJECTION = false;
  45202. defines.REFLECTIONMAP_SKYBOX = false;
  45203. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45204. defines.REFLECTIONMAP_EXPLICIT = false;
  45205. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45207. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45208. defines.INVERTCUBICMAP = false;
  45209. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45210. defines.USESPHERICALINVERTEX = false;
  45211. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45212. defines.LODINREFLECTIONALPHA = false;
  45213. defines.GAMMAREFLECTION = false;
  45214. defines.RGBDREFLECTION = false;
  45215. }
  45216. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45218. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45219. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45220. }
  45221. else {
  45222. defines.LIGHTMAP = false;
  45223. }
  45224. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45226. }
  45227. else {
  45228. defines.EMISSIVE = false;
  45229. }
  45230. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45231. if (this._metallicTexture) {
  45232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45233. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45234. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45235. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45236. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45237. }
  45238. else if (this._reflectivityTexture) {
  45239. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45240. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45241. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45242. }
  45243. else {
  45244. defines.REFLECTIVITY = false;
  45245. }
  45246. if (this._microSurfaceTexture) {
  45247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45248. }
  45249. else {
  45250. defines.MICROSURFACEMAP = false;
  45251. }
  45252. }
  45253. else {
  45254. defines.REFLECTIVITY = false;
  45255. defines.MICROSURFACEMAP = false;
  45256. }
  45257. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45259. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45260. defines.PARALLAX = true;
  45261. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45262. }
  45263. else {
  45264. defines.PARALLAX = false;
  45265. }
  45266. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45267. }
  45268. else {
  45269. defines.BUMP = false;
  45270. }
  45271. var refractionTexture = this._getRefractionTexture();
  45272. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45273. defines.REFRACTION = true;
  45274. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45275. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45276. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45277. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45278. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45279. if (this._linkRefractionWithTransparency) {
  45280. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45281. }
  45282. }
  45283. else {
  45284. defines.REFRACTION = false;
  45285. }
  45286. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45287. defines.ENVIRONMENTBRDF = true;
  45288. }
  45289. else {
  45290. defines.ENVIRONMENTBRDF = false;
  45291. }
  45292. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45293. defines.ALPHAFROMALBEDO = true;
  45294. }
  45295. else {
  45296. defines.ALPHAFROMALBEDO = false;
  45297. }
  45298. }
  45299. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45300. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45301. defines.USEPHYSICALLIGHTFALLOFF = false;
  45302. defines.USEGLTFLIGHTFALLOFF = false;
  45303. }
  45304. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45305. defines.USEPHYSICALLIGHTFALLOFF = false;
  45306. defines.USEGLTFLIGHTFALLOFF = true;
  45307. }
  45308. else {
  45309. defines.USEPHYSICALLIGHTFALLOFF = true;
  45310. defines.USEGLTFLIGHTFALLOFF = false;
  45311. }
  45312. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45313. if (!this.backFaceCulling && this._twoSidedLighting) {
  45314. defines.TWOSIDEDLIGHTING = true;
  45315. }
  45316. else {
  45317. defines.TWOSIDEDLIGHTING = false;
  45318. }
  45319. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45320. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45321. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45322. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45323. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45324. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45325. }
  45326. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45327. this._imageProcessingConfiguration.prepareDefines(defines);
  45328. }
  45329. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45330. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45331. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45332. // Misc.
  45333. if (defines._areMiscDirty) {
  45334. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45335. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45336. }
  45337. // Values that need to be evaluated on every frame
  45338. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45339. // Attribs
  45340. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45341. };
  45342. /**
  45343. * Force shader compilation
  45344. */
  45345. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45346. var _this = this;
  45347. var localOptions = __assign({ clipPlane: false }, options);
  45348. var defines = new PBRMaterialDefines();
  45349. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45350. if (effect.isReady()) {
  45351. if (onCompiled) {
  45352. onCompiled(this);
  45353. }
  45354. }
  45355. else {
  45356. effect.onCompileObservable.add(function () {
  45357. if (onCompiled) {
  45358. onCompiled(_this);
  45359. }
  45360. });
  45361. }
  45362. };
  45363. /**
  45364. * Initializes the uniform buffer layout for the shader.
  45365. */
  45366. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45367. // Order is important !
  45368. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45369. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45370. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45371. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45372. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45373. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45374. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45375. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45376. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45377. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45378. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45379. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45380. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45381. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45382. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45383. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45384. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45385. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45386. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45387. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45388. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45389. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45390. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45391. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45392. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45393. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45394. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45395. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45396. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45397. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45398. this._uniformBuffer.addUniform("pointSize", 1);
  45399. this._uniformBuffer.create();
  45400. };
  45401. /**
  45402. * Unbinds the textures.
  45403. */
  45404. PBRBaseMaterial.prototype.unbind = function () {
  45405. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45406. this._uniformBuffer.setTexture("reflectionSampler", null);
  45407. }
  45408. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45409. this._uniformBuffer.setTexture("refractionSampler", null);
  45410. }
  45411. _super.prototype.unbind.call(this);
  45412. };
  45413. /**
  45414. * Binds the submesh data.
  45415. * @param world - The world matrix.
  45416. * @param mesh - The BJS mesh.
  45417. * @param subMesh - A submesh of the BJS mesh.
  45418. */
  45419. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45420. var scene = this.getScene();
  45421. var defines = subMesh._materialDefines;
  45422. if (!defines) {
  45423. return;
  45424. }
  45425. var effect = subMesh.effect;
  45426. if (!effect) {
  45427. return;
  45428. }
  45429. this._activeEffect = effect;
  45430. // Matrices
  45431. this.bindOnlyWorldMatrix(world);
  45432. // Normal Matrix
  45433. if (defines.OBJECTSPACE_NORMALMAP) {
  45434. world.toNormalMatrix(this._normalMatrix);
  45435. this.bindOnlyNormalMatrix(this._normalMatrix);
  45436. }
  45437. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45438. // Bones
  45439. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45440. var reflectionTexture = null;
  45441. if (mustRebind) {
  45442. this._uniformBuffer.bindToEffect(effect, "Material");
  45443. this.bindViewProjection(effect);
  45444. reflectionTexture = this._getReflectionTexture();
  45445. var refractionTexture = this._getRefractionTexture();
  45446. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45447. // Texture uniforms
  45448. if (scene.texturesEnabled) {
  45449. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45450. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45451. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45452. }
  45453. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45454. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45455. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45456. }
  45457. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45458. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45459. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45460. }
  45461. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45462. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45463. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45464. if (reflectionTexture.boundingBoxSize) {
  45465. var cubeTexture = reflectionTexture;
  45466. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45467. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45468. }
  45469. var polynomials = reflectionTexture.sphericalPolynomial;
  45470. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45471. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45472. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45473. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45474. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45475. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45476. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45477. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45478. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45479. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45480. }
  45481. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45482. }
  45483. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45484. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45485. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45486. }
  45487. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45488. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45489. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45490. }
  45491. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45492. if (this._metallicTexture) {
  45493. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45494. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45495. }
  45496. else if (this._reflectivityTexture) {
  45497. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45498. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45499. }
  45500. if (this._microSurfaceTexture) {
  45501. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45502. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45503. }
  45504. }
  45505. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45506. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45507. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45508. if (scene._mirroredCameraPosition) {
  45509. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45510. }
  45511. else {
  45512. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45513. }
  45514. }
  45515. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45516. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45517. var depth = 1.0;
  45518. if (!refractionTexture.isCube) {
  45519. if (refractionTexture.depth) {
  45520. depth = refractionTexture.depth;
  45521. }
  45522. }
  45523. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45524. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45525. }
  45526. }
  45527. // Point size
  45528. if (this.pointsCloud) {
  45529. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45530. }
  45531. // Colors
  45532. if (defines.METALLICWORKFLOW) {
  45533. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45534. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45535. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45536. }
  45537. else {
  45538. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45539. }
  45540. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45541. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45542. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45543. // Misc
  45544. this._lightingInfos.x = this._directIntensity;
  45545. this._lightingInfos.y = this._emissiveIntensity;
  45546. this._lightingInfos.z = this._environmentIntensity;
  45547. this._lightingInfos.w = this._specularIntensity;
  45548. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45549. }
  45550. // Textures
  45551. if (scene.texturesEnabled) {
  45552. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45553. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45554. }
  45555. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45556. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45557. }
  45558. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45559. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45560. }
  45561. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45562. if (defines.LODBASEDMICROSFURACE) {
  45563. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45564. }
  45565. else {
  45566. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45567. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45568. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45569. }
  45570. }
  45571. if (defines.ENVIRONMENTBRDF) {
  45572. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45573. }
  45574. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45575. if (defines.LODBASEDMICROSFURACE) {
  45576. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45577. }
  45578. else {
  45579. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45580. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45581. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45582. }
  45583. }
  45584. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45585. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45586. }
  45587. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45588. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45589. }
  45590. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45591. if (this._metallicTexture) {
  45592. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45593. }
  45594. else if (this._reflectivityTexture) {
  45595. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45596. }
  45597. if (this._microSurfaceTexture) {
  45598. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45599. }
  45600. }
  45601. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45602. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45603. }
  45604. }
  45605. // Clip plane
  45606. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45607. // Colors
  45608. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45609. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45610. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45611. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45612. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45613. }
  45614. if (mustRebind || !this.isFrozen) {
  45615. // Lights
  45616. if (scene.lightsEnabled && !this._disableLighting) {
  45617. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45618. }
  45619. // View
  45620. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45621. this.bindView(effect);
  45622. }
  45623. // Fog
  45624. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45625. // Morph targets
  45626. if (defines.NUM_MORPH_INFLUENCERS) {
  45627. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45628. }
  45629. // image processing
  45630. this._imageProcessingConfiguration.bind(this._activeEffect);
  45631. // Log. depth
  45632. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45633. }
  45634. this._uniformBuffer.update();
  45635. this._afterBind(mesh, this._activeEffect);
  45636. };
  45637. /**
  45638. * Returns the animatable textures.
  45639. * @returns - Array of animatable textures.
  45640. */
  45641. PBRBaseMaterial.prototype.getAnimatables = function () {
  45642. var results = [];
  45643. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45644. results.push(this._albedoTexture);
  45645. }
  45646. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45647. results.push(this._ambientTexture);
  45648. }
  45649. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45650. results.push(this._opacityTexture);
  45651. }
  45652. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45653. results.push(this._reflectionTexture);
  45654. }
  45655. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45656. results.push(this._emissiveTexture);
  45657. }
  45658. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45659. results.push(this._metallicTexture);
  45660. }
  45661. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45662. results.push(this._reflectivityTexture);
  45663. }
  45664. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45665. results.push(this._bumpTexture);
  45666. }
  45667. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45668. results.push(this._lightmapTexture);
  45669. }
  45670. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45671. results.push(this._refractionTexture);
  45672. }
  45673. return results;
  45674. };
  45675. /**
  45676. * Returns the texture used for reflections.
  45677. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45678. */
  45679. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45680. if (this._reflectionTexture) {
  45681. return this._reflectionTexture;
  45682. }
  45683. return this.getScene().environmentTexture;
  45684. };
  45685. /**
  45686. * Returns the texture used for refraction or null if none is used.
  45687. * @returns - Refection texture if present. If no refraction texture and refraction
  45688. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45689. */
  45690. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45691. if (this._refractionTexture) {
  45692. return this._refractionTexture;
  45693. }
  45694. if (this._linkRefractionWithTransparency) {
  45695. return this.getScene().environmentTexture;
  45696. }
  45697. return null;
  45698. };
  45699. /**
  45700. * Disposes the resources of the material.
  45701. * @param forceDisposeEffect - Forces the disposal of effects.
  45702. * @param forceDisposeTextures - Forces the disposal of all textures.
  45703. */
  45704. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45705. if (forceDisposeTextures) {
  45706. if (this._albedoTexture) {
  45707. this._albedoTexture.dispose();
  45708. }
  45709. if (this._ambientTexture) {
  45710. this._ambientTexture.dispose();
  45711. }
  45712. if (this._opacityTexture) {
  45713. this._opacityTexture.dispose();
  45714. }
  45715. if (this._reflectionTexture) {
  45716. this._reflectionTexture.dispose();
  45717. }
  45718. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45719. this._environmentBRDFTexture.dispose();
  45720. }
  45721. if (this._emissiveTexture) {
  45722. this._emissiveTexture.dispose();
  45723. }
  45724. if (this._metallicTexture) {
  45725. this._metallicTexture.dispose();
  45726. }
  45727. if (this._reflectivityTexture) {
  45728. this._reflectivityTexture.dispose();
  45729. }
  45730. if (this._bumpTexture) {
  45731. this._bumpTexture.dispose();
  45732. }
  45733. if (this._lightmapTexture) {
  45734. this._lightmapTexture.dispose();
  45735. }
  45736. if (this._refractionTexture) {
  45737. this._refractionTexture.dispose();
  45738. }
  45739. }
  45740. this._renderTargets.dispose();
  45741. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45742. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45743. }
  45744. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45745. };
  45746. /**
  45747. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45748. */
  45749. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45750. /**
  45751. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45752. * to enhance interoperability with other engines.
  45753. */
  45754. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45755. /**
  45756. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45757. * to enhance interoperability with other materials.
  45758. */
  45759. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45760. /**
  45761. * Stores the reflectivity values based on metallic roughness workflow.
  45762. */
  45763. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45764. __decorate([
  45765. BABYLON.serializeAsImageProcessingConfiguration()
  45766. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45767. __decorate([
  45768. BABYLON.serialize()
  45769. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45770. __decorate([
  45771. BABYLON.serialize()
  45772. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45773. return PBRBaseMaterial;
  45774. }(BABYLON.PushMaterial));
  45775. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45776. })(BABYLON || (BABYLON = {}));
  45777. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45778. var BABYLON;
  45779. (function (BABYLON) {
  45780. /**
  45781. * The Physically based simple base material of BJS.
  45782. *
  45783. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45784. * It is used as the base class for both the specGloss and metalRough conventions.
  45785. */
  45786. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45787. __extends(PBRBaseSimpleMaterial, _super);
  45788. /**
  45789. * Instantiates a new PBRMaterial instance.
  45790. *
  45791. * @param name The material name
  45792. * @param scene The scene the material will be use in.
  45793. */
  45794. function PBRBaseSimpleMaterial(name, scene) {
  45795. var _this = _super.call(this, name, scene) || this;
  45796. /**
  45797. * Number of Simultaneous lights allowed on the material.
  45798. */
  45799. _this.maxSimultaneousLights = 4;
  45800. /**
  45801. * If sets to true, disables all the lights affecting the material.
  45802. */
  45803. _this.disableLighting = false;
  45804. /**
  45805. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45806. */
  45807. _this.invertNormalMapX = false;
  45808. /**
  45809. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45810. */
  45811. _this.invertNormalMapY = false;
  45812. /**
  45813. * Emissivie color used to self-illuminate the model.
  45814. */
  45815. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45816. /**
  45817. * Occlusion Channel Strenght.
  45818. */
  45819. _this.occlusionStrength = 1.0;
  45820. /**
  45821. * If true, the light map contains occlusion information instead of lighting info.
  45822. */
  45823. _this.useLightmapAsShadowmap = false;
  45824. _this._useAlphaFromAlbedoTexture = true;
  45825. _this._useAmbientInGrayScale = true;
  45826. return _this;
  45827. }
  45828. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45829. /**
  45830. * Gets the current double sided mode.
  45831. */
  45832. get: function () {
  45833. return this._twoSidedLighting;
  45834. },
  45835. /**
  45836. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45837. */
  45838. set: function (value) {
  45839. if (this._twoSidedLighting === value) {
  45840. return;
  45841. }
  45842. this._twoSidedLighting = value;
  45843. this.backFaceCulling = !value;
  45844. this._markAllSubMeshesAsTexturesDirty();
  45845. },
  45846. enumerable: true,
  45847. configurable: true
  45848. });
  45849. /**
  45850. * Return the active textures of the material.
  45851. */
  45852. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45853. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45854. if (this.environmentTexture) {
  45855. activeTextures.push(this.environmentTexture);
  45856. }
  45857. if (this.normalTexture) {
  45858. activeTextures.push(this.normalTexture);
  45859. }
  45860. if (this.emissiveTexture) {
  45861. activeTextures.push(this.emissiveTexture);
  45862. }
  45863. if (this.occlusionTexture) {
  45864. activeTextures.push(this.occlusionTexture);
  45865. }
  45866. if (this.lightmapTexture) {
  45867. activeTextures.push(this.lightmapTexture);
  45868. }
  45869. return activeTextures;
  45870. };
  45871. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45872. if (_super.prototype.hasTexture.call(this, texture)) {
  45873. return true;
  45874. }
  45875. if (this.lightmapTexture === texture) {
  45876. return true;
  45877. }
  45878. return false;
  45879. };
  45880. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45881. return "PBRBaseSimpleMaterial";
  45882. };
  45883. __decorate([
  45884. BABYLON.serialize(),
  45885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45886. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45887. __decorate([
  45888. BABYLON.serialize(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45890. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45891. __decorate([
  45892. BABYLON.serializeAsTexture(),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45894. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45895. __decorate([
  45896. BABYLON.serialize(),
  45897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45898. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45899. __decorate([
  45900. BABYLON.serialize(),
  45901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45902. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45903. __decorate([
  45904. BABYLON.serializeAsTexture(),
  45905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45906. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45907. __decorate([
  45908. BABYLON.serializeAsColor3("emissive"),
  45909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45910. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45911. __decorate([
  45912. BABYLON.serializeAsTexture(),
  45913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45914. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45915. __decorate([
  45916. BABYLON.serialize(),
  45917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45918. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45919. __decorate([
  45920. BABYLON.serializeAsTexture(),
  45921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45922. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45923. __decorate([
  45924. BABYLON.serialize(),
  45925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45926. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45927. __decorate([
  45928. BABYLON.serialize()
  45929. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45930. __decorate([
  45931. BABYLON.serializeAsTexture(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45933. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45934. __decorate([
  45935. BABYLON.serialize(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45938. return PBRBaseSimpleMaterial;
  45939. }(BABYLON.PBRBaseMaterial));
  45940. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45941. })(BABYLON || (BABYLON = {}));
  45942. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45943. var BABYLON;
  45944. (function (BABYLON) {
  45945. /**
  45946. * The Physically based material of BJS.
  45947. *
  45948. * This offers the main features of a standard PBR material.
  45949. * For more information, please refer to the documentation :
  45950. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45951. */
  45952. var PBRMaterial = /** @class */ (function (_super) {
  45953. __extends(PBRMaterial, _super);
  45954. /**
  45955. * Instantiates a new PBRMaterial instance.
  45956. *
  45957. * @param name The material name
  45958. * @param scene The scene the material will be use in.
  45959. */
  45960. function PBRMaterial(name, scene) {
  45961. var _this = _super.call(this, name, scene) || this;
  45962. /**
  45963. * Intensity of the direct lights e.g. the four lights available in your scene.
  45964. * This impacts both the direct diffuse and specular highlights.
  45965. */
  45966. _this.directIntensity = 1.0;
  45967. /**
  45968. * Intensity of the emissive part of the material.
  45969. * This helps controlling the emissive effect without modifying the emissive color.
  45970. */
  45971. _this.emissiveIntensity = 1.0;
  45972. /**
  45973. * Intensity of the environment e.g. how much the environment will light the object
  45974. * either through harmonics for rough material or through the refelction for shiny ones.
  45975. */
  45976. _this.environmentIntensity = 1.0;
  45977. /**
  45978. * This is a special control allowing the reduction of the specular highlights coming from the
  45979. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45980. */
  45981. _this.specularIntensity = 1.0;
  45982. /**
  45983. * Debug Control allowing disabling the bump map on this material.
  45984. */
  45985. _this.disableBumpMap = false;
  45986. /**
  45987. * AKA Occlusion Texture Intensity in other nomenclature.
  45988. */
  45989. _this.ambientTextureStrength = 1.0;
  45990. /**
  45991. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45992. * 1 means it completely occludes it
  45993. * 0 mean it has no impact
  45994. */
  45995. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45996. /**
  45997. * The color of a material in ambient lighting.
  45998. */
  45999. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46000. /**
  46001. * AKA Diffuse Color in other nomenclature.
  46002. */
  46003. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46004. /**
  46005. * AKA Specular Color in other nomenclature.
  46006. */
  46007. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46008. /**
  46009. * The color reflected from the material.
  46010. */
  46011. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46012. /**
  46013. * The color emitted from the material.
  46014. */
  46015. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46016. /**
  46017. * AKA Glossiness in other nomenclature.
  46018. */
  46019. _this.microSurface = 1.0;
  46020. /**
  46021. * source material index of refraction (IOR)' / 'destination material IOR.
  46022. */
  46023. _this.indexOfRefraction = 0.66;
  46024. /**
  46025. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46026. */
  46027. _this.invertRefractionY = false;
  46028. /**
  46029. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46030. * Materials half opaque for instance using refraction could benefit from this control.
  46031. */
  46032. _this.linkRefractionWithTransparency = false;
  46033. /**
  46034. * If true, the light map contains occlusion information instead of lighting info.
  46035. */
  46036. _this.useLightmapAsShadowmap = false;
  46037. /**
  46038. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46039. */
  46040. _this.useAlphaFromAlbedoTexture = false;
  46041. /**
  46042. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46043. */
  46044. _this.forceAlphaTest = false;
  46045. /**
  46046. * Defines the alpha limits in alpha test mode.
  46047. */
  46048. _this.alphaCutOff = 0.4;
  46049. /**
  46050. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46051. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46052. */
  46053. _this.useSpecularOverAlpha = true;
  46054. /**
  46055. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46056. */
  46057. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46058. /**
  46059. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46060. */
  46061. _this.useRoughnessFromMetallicTextureAlpha = true;
  46062. /**
  46063. * Specifies if the metallic texture contains the roughness information in its green channel.
  46064. */
  46065. _this.useRoughnessFromMetallicTextureGreen = false;
  46066. /**
  46067. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46068. */
  46069. _this.useMetallnessFromMetallicTextureBlue = false;
  46070. /**
  46071. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46072. */
  46073. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46074. /**
  46075. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46076. */
  46077. _this.useAmbientInGrayScale = false;
  46078. /**
  46079. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46080. * The material will try to infer what glossiness each pixel should be.
  46081. */
  46082. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46083. /**
  46084. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46085. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46086. */
  46087. _this.useRadianceOverAlpha = true;
  46088. /**
  46089. * Allows using an object space normal map (instead of tangent space).
  46090. */
  46091. _this.useObjectSpaceNormalMap = false;
  46092. /**
  46093. * Allows using the bump map in parallax mode.
  46094. */
  46095. _this.useParallax = false;
  46096. /**
  46097. * Allows using the bump map in parallax occlusion mode.
  46098. */
  46099. _this.useParallaxOcclusion = false;
  46100. /**
  46101. * Controls the scale bias of the parallax mode.
  46102. */
  46103. _this.parallaxScaleBias = 0.05;
  46104. /**
  46105. * If sets to true, disables all the lights affecting the material.
  46106. */
  46107. _this.disableLighting = false;
  46108. /**
  46109. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46110. */
  46111. _this.forceIrradianceInFragment = false;
  46112. /**
  46113. * Number of Simultaneous lights allowed on the material.
  46114. */
  46115. _this.maxSimultaneousLights = 4;
  46116. /**
  46117. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46118. */
  46119. _this.invertNormalMapX = false;
  46120. /**
  46121. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46122. */
  46123. _this.invertNormalMapY = false;
  46124. /**
  46125. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46126. */
  46127. _this.twoSidedLighting = false;
  46128. /**
  46129. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46130. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46131. */
  46132. _this.useAlphaFresnel = false;
  46133. /**
  46134. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46135. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46136. */
  46137. _this.useLinearAlphaFresnel = false;
  46138. /**
  46139. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46140. * And/Or occlude the blended part.
  46141. */
  46142. _this.environmentBRDFTexture = null;
  46143. /**
  46144. * Force normal to face away from face.
  46145. */
  46146. _this.forceNormalForward = false;
  46147. /**
  46148. * Enables specular anti aliasing in the PBR shader.
  46149. * It will both interacts on the Geometry for analytical and IBL lighting.
  46150. * It also prefilter the roughness map based on the bump values.
  46151. */
  46152. _this.enableSpecularAntiAliasing = false;
  46153. /**
  46154. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46155. * makes the reflect vector face the model (under horizon).
  46156. */
  46157. _this.useHorizonOcclusion = true;
  46158. /**
  46159. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46160. * too much the area relying on ambient texture to define their ambient occlusion.
  46161. */
  46162. _this.useRadianceOcclusion = true;
  46163. /**
  46164. * If set to true, no lighting calculations will be applied.
  46165. */
  46166. _this.unlit = false;
  46167. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46168. return _this;
  46169. }
  46170. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46171. /**
  46172. * BJS is using an harcoded light falloff based on a manually sets up range.
  46173. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46174. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46175. */
  46176. get: function () {
  46177. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46178. },
  46179. /**
  46180. * BJS is using an harcoded light falloff based on a manually sets up range.
  46181. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46182. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46183. */
  46184. set: function (value) {
  46185. if (value !== this.usePhysicalLightFalloff) {
  46186. // Ensure the effect will be rebuilt.
  46187. this._markAllSubMeshesAsTexturesDirty();
  46188. if (value) {
  46189. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46190. }
  46191. else {
  46192. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46193. }
  46194. }
  46195. },
  46196. enumerable: true,
  46197. configurable: true
  46198. });
  46199. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46200. /**
  46201. * In order to support the falloff compatibility with gltf, a special mode has been added
  46202. * to reproduce the gltf light falloff.
  46203. */
  46204. get: function () {
  46205. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46206. },
  46207. /**
  46208. * In order to support the falloff compatibility with gltf, a special mode has been added
  46209. * to reproduce the gltf light falloff.
  46210. */
  46211. set: function (value) {
  46212. if (value !== this.useGLTFLightFalloff) {
  46213. // Ensure the effect will be rebuilt.
  46214. this._markAllSubMeshesAsTexturesDirty();
  46215. if (value) {
  46216. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46217. }
  46218. else {
  46219. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46220. }
  46221. }
  46222. },
  46223. enumerable: true,
  46224. configurable: true
  46225. });
  46226. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46227. /**
  46228. * Gets the image processing configuration used either in this material.
  46229. */
  46230. get: function () {
  46231. return this._imageProcessingConfiguration;
  46232. },
  46233. /**
  46234. * Sets the Default image processing configuration used either in the this material.
  46235. *
  46236. * If sets to null, the scene one is in use.
  46237. */
  46238. set: function (value) {
  46239. this._attachImageProcessingConfiguration(value);
  46240. // Ensure the effect will be rebuilt.
  46241. this._markAllSubMeshesAsTexturesDirty();
  46242. },
  46243. enumerable: true,
  46244. configurable: true
  46245. });
  46246. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46247. /**
  46248. * Gets wether the color curves effect is enabled.
  46249. */
  46250. get: function () {
  46251. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46252. },
  46253. /**
  46254. * Sets wether the color curves effect is enabled.
  46255. */
  46256. set: function (value) {
  46257. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46258. },
  46259. enumerable: true,
  46260. configurable: true
  46261. });
  46262. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46263. /**
  46264. * Gets wether the color grading effect is enabled.
  46265. */
  46266. get: function () {
  46267. return this.imageProcessingConfiguration.colorGradingEnabled;
  46268. },
  46269. /**
  46270. * Gets wether the color grading effect is enabled.
  46271. */
  46272. set: function (value) {
  46273. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46274. },
  46275. enumerable: true,
  46276. configurable: true
  46277. });
  46278. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46279. /**
  46280. * Gets wether tonemapping is enabled or not.
  46281. */
  46282. get: function () {
  46283. return this._imageProcessingConfiguration.toneMappingEnabled;
  46284. },
  46285. /**
  46286. * Sets wether tonemapping is enabled or not
  46287. */
  46288. set: function (value) {
  46289. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46290. },
  46291. enumerable: true,
  46292. configurable: true
  46293. });
  46294. ;
  46295. ;
  46296. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46297. /**
  46298. * The camera exposure used on this material.
  46299. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46300. * This corresponds to a photographic exposure.
  46301. */
  46302. get: function () {
  46303. return this._imageProcessingConfiguration.exposure;
  46304. },
  46305. /**
  46306. * The camera exposure used on this material.
  46307. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46308. * This corresponds to a photographic exposure.
  46309. */
  46310. set: function (value) {
  46311. this._imageProcessingConfiguration.exposure = value;
  46312. },
  46313. enumerable: true,
  46314. configurable: true
  46315. });
  46316. ;
  46317. ;
  46318. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46319. /**
  46320. * Gets The camera contrast used on this material.
  46321. */
  46322. get: function () {
  46323. return this._imageProcessingConfiguration.contrast;
  46324. },
  46325. /**
  46326. * Sets The camera contrast used on this material.
  46327. */
  46328. set: function (value) {
  46329. this._imageProcessingConfiguration.contrast = value;
  46330. },
  46331. enumerable: true,
  46332. configurable: true
  46333. });
  46334. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46335. /**
  46336. * Gets the Color Grading 2D Lookup Texture.
  46337. */
  46338. get: function () {
  46339. return this._imageProcessingConfiguration.colorGradingTexture;
  46340. },
  46341. /**
  46342. * Sets the Color Grading 2D Lookup Texture.
  46343. */
  46344. set: function (value) {
  46345. this._imageProcessingConfiguration.colorGradingTexture = value;
  46346. },
  46347. enumerable: true,
  46348. configurable: true
  46349. });
  46350. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46351. /**
  46352. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46353. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46354. * 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;
  46355. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46356. */
  46357. get: function () {
  46358. return this._imageProcessingConfiguration.colorCurves;
  46359. },
  46360. /**
  46361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46363. * 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;
  46364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46365. */
  46366. set: function (value) {
  46367. this._imageProcessingConfiguration.colorCurves = value;
  46368. },
  46369. enumerable: true,
  46370. configurable: true
  46371. });
  46372. /**
  46373. * Returns the name of this material class.
  46374. */
  46375. PBRMaterial.prototype.getClassName = function () {
  46376. return "PBRMaterial";
  46377. };
  46378. /**
  46379. * Returns an array of the actively used textures.
  46380. * @returns - Array of BaseTextures
  46381. */
  46382. PBRMaterial.prototype.getActiveTextures = function () {
  46383. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46384. if (this._albedoTexture) {
  46385. activeTextures.push(this._albedoTexture);
  46386. }
  46387. if (this._ambientTexture) {
  46388. activeTextures.push(this._ambientTexture);
  46389. }
  46390. if (this._opacityTexture) {
  46391. activeTextures.push(this._opacityTexture);
  46392. }
  46393. if (this._reflectionTexture) {
  46394. activeTextures.push(this._reflectionTexture);
  46395. }
  46396. if (this._emissiveTexture) {
  46397. activeTextures.push(this._emissiveTexture);
  46398. }
  46399. if (this._reflectivityTexture) {
  46400. activeTextures.push(this._reflectivityTexture);
  46401. }
  46402. if (this._metallicTexture) {
  46403. activeTextures.push(this._metallicTexture);
  46404. }
  46405. if (this._microSurfaceTexture) {
  46406. activeTextures.push(this._microSurfaceTexture);
  46407. }
  46408. if (this._bumpTexture) {
  46409. activeTextures.push(this._bumpTexture);
  46410. }
  46411. if (this._lightmapTexture) {
  46412. activeTextures.push(this._lightmapTexture);
  46413. }
  46414. if (this._refractionTexture) {
  46415. activeTextures.push(this._refractionTexture);
  46416. }
  46417. return activeTextures;
  46418. };
  46419. /**
  46420. * Checks to see if a texture is used in the material.
  46421. * @param texture - Base texture to use.
  46422. * @returns - Boolean specifying if a texture is used in the material.
  46423. */
  46424. PBRMaterial.prototype.hasTexture = function (texture) {
  46425. if (_super.prototype.hasTexture.call(this, texture)) {
  46426. return true;
  46427. }
  46428. if (this._albedoTexture === texture) {
  46429. return true;
  46430. }
  46431. if (this._ambientTexture === texture) {
  46432. return true;
  46433. }
  46434. if (this._opacityTexture === texture) {
  46435. return true;
  46436. }
  46437. if (this._reflectionTexture === texture) {
  46438. return true;
  46439. }
  46440. if (this._reflectivityTexture === texture) {
  46441. return true;
  46442. }
  46443. if (this._metallicTexture === texture) {
  46444. return true;
  46445. }
  46446. if (this._microSurfaceTexture === texture) {
  46447. return true;
  46448. }
  46449. if (this._bumpTexture === texture) {
  46450. return true;
  46451. }
  46452. if (this._lightmapTexture === texture) {
  46453. return true;
  46454. }
  46455. if (this._refractionTexture === texture) {
  46456. return true;
  46457. }
  46458. return false;
  46459. };
  46460. /**
  46461. * Makes a duplicate of the current material.
  46462. * @param name - name to use for the new material.
  46463. */
  46464. PBRMaterial.prototype.clone = function (name) {
  46465. var _this = this;
  46466. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46467. clone.id = name;
  46468. clone.name = name;
  46469. return clone;
  46470. };
  46471. /**
  46472. * Serializes this PBR Material.
  46473. * @returns - An object with the serialized material.
  46474. */
  46475. PBRMaterial.prototype.serialize = function () {
  46476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46477. serializationObject.customType = "BABYLON.PBRMaterial";
  46478. return serializationObject;
  46479. };
  46480. // Statics
  46481. /**
  46482. * Parses a PBR Material from a serialized object.
  46483. * @param source - Serialized object.
  46484. * @param scene - BJS scene instance.
  46485. * @param rootUrl - url for the scene object
  46486. * @returns - PBRMaterial
  46487. */
  46488. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46489. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46490. };
  46491. /**
  46492. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46493. */
  46494. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46495. /**
  46496. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46497. */
  46498. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46499. /**
  46500. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46501. */
  46502. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46503. /**
  46504. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46505. * They are also discarded below the alpha cutoff threshold to improve performances.
  46506. */
  46507. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46508. /**
  46509. * Defines the default value of how much AO map is occluding the analytical lights
  46510. * (point spot...).
  46511. */
  46512. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46513. __decorate([
  46514. BABYLON.serialize(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46516. ], PBRMaterial.prototype, "directIntensity", void 0);
  46517. __decorate([
  46518. BABYLON.serialize(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46520. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46521. __decorate([
  46522. BABYLON.serialize(),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46524. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46525. __decorate([
  46526. BABYLON.serialize(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46528. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46529. __decorate([
  46530. BABYLON.serialize(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46532. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46533. __decorate([
  46534. BABYLON.serializeAsTexture(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46537. __decorate([
  46538. BABYLON.serializeAsTexture(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46541. __decorate([
  46542. BABYLON.serialize(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46544. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46545. __decorate([
  46546. BABYLON.serialize(),
  46547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46548. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46549. __decorate([
  46550. BABYLON.serializeAsTexture(),
  46551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46552. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46553. __decorate([
  46554. BABYLON.serializeAsTexture(),
  46555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46556. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46557. __decorate([
  46558. BABYLON.serializeAsTexture(),
  46559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46560. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46561. __decorate([
  46562. BABYLON.serializeAsTexture(),
  46563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46564. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46565. __decorate([
  46566. BABYLON.serializeAsTexture(),
  46567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46568. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46569. __decorate([
  46570. BABYLON.serialize(),
  46571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46572. ], PBRMaterial.prototype, "metallic", void 0);
  46573. __decorate([
  46574. BABYLON.serialize(),
  46575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46576. ], PBRMaterial.prototype, "roughness", void 0);
  46577. __decorate([
  46578. BABYLON.serializeAsTexture(),
  46579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46580. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46581. __decorate([
  46582. BABYLON.serializeAsTexture(),
  46583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46584. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46585. __decorate([
  46586. BABYLON.serializeAsTexture(),
  46587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46588. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46589. __decorate([
  46590. BABYLON.serializeAsTexture(),
  46591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46592. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46593. __decorate([
  46594. BABYLON.serializeAsColor3("ambient"),
  46595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46596. ], PBRMaterial.prototype, "ambientColor", void 0);
  46597. __decorate([
  46598. BABYLON.serializeAsColor3("albedo"),
  46599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46600. ], PBRMaterial.prototype, "albedoColor", void 0);
  46601. __decorate([
  46602. BABYLON.serializeAsColor3("reflectivity"),
  46603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46604. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46605. __decorate([
  46606. BABYLON.serializeAsColor3("reflection"),
  46607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46608. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46609. __decorate([
  46610. BABYLON.serializeAsColor3("emissive"),
  46611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46612. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46613. __decorate([
  46614. BABYLON.serialize(),
  46615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46616. ], PBRMaterial.prototype, "microSurface", void 0);
  46617. __decorate([
  46618. BABYLON.serialize(),
  46619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46620. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46621. __decorate([
  46622. BABYLON.serialize(),
  46623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46624. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46625. __decorate([
  46626. BABYLON.serialize(),
  46627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46628. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46629. __decorate([
  46630. BABYLON.serialize(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46632. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46633. __decorate([
  46634. BABYLON.serialize(),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46636. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46637. __decorate([
  46638. BABYLON.serialize(),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46640. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46641. __decorate([
  46642. BABYLON.serialize(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46644. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46645. __decorate([
  46646. BABYLON.serialize(),
  46647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46648. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46649. __decorate([
  46650. BABYLON.serialize(),
  46651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46652. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46653. __decorate([
  46654. BABYLON.serialize(),
  46655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46656. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46657. __decorate([
  46658. BABYLON.serialize(),
  46659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46660. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46661. __decorate([
  46662. BABYLON.serialize(),
  46663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46664. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46665. __decorate([
  46666. BABYLON.serialize(),
  46667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46668. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46669. __decorate([
  46670. BABYLON.serialize(),
  46671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46672. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46673. __decorate([
  46674. BABYLON.serialize(),
  46675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46676. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46677. __decorate([
  46678. BABYLON.serialize()
  46679. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46680. __decorate([
  46681. BABYLON.serialize()
  46682. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46683. __decorate([
  46684. BABYLON.serialize(),
  46685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46686. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46687. __decorate([
  46688. BABYLON.serialize(),
  46689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46690. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46691. __decorate([
  46692. BABYLON.serialize(),
  46693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46694. ], PBRMaterial.prototype, "useParallax", void 0);
  46695. __decorate([
  46696. BABYLON.serialize(),
  46697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46698. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46699. __decorate([
  46700. BABYLON.serialize(),
  46701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46702. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46703. __decorate([
  46704. BABYLON.serialize(),
  46705. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46706. ], PBRMaterial.prototype, "disableLighting", void 0);
  46707. __decorate([
  46708. BABYLON.serialize(),
  46709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46710. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46711. __decorate([
  46712. BABYLON.serialize(),
  46713. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46714. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46715. __decorate([
  46716. BABYLON.serialize(),
  46717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46718. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46719. __decorate([
  46720. BABYLON.serialize(),
  46721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46722. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46723. __decorate([
  46724. BABYLON.serialize(),
  46725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46726. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46727. __decorate([
  46728. BABYLON.serialize(),
  46729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46730. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46731. __decorate([
  46732. BABYLON.serialize(),
  46733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46734. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46735. __decorate([
  46736. BABYLON.serializeAsTexture(),
  46737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46738. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46739. __decorate([
  46740. BABYLON.serialize(),
  46741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46742. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46743. __decorate([
  46744. BABYLON.serialize(),
  46745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46746. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46747. __decorate([
  46748. BABYLON.serialize(),
  46749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46750. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46751. __decorate([
  46752. BABYLON.serialize(),
  46753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46754. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46755. __decorate([
  46756. BABYLON.serialize(),
  46757. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46758. ], PBRMaterial.prototype, "unlit", void 0);
  46759. return PBRMaterial;
  46760. }(BABYLON.PBRBaseMaterial));
  46761. BABYLON.PBRMaterial = PBRMaterial;
  46762. })(BABYLON || (BABYLON = {}));
  46763. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46764. var BABYLON;
  46765. (function (BABYLON) {
  46766. /**
  46767. * The PBR material of BJS following the metal roughness convention.
  46768. *
  46769. * This fits to the PBR convention in the GLTF definition:
  46770. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46771. */
  46772. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46773. __extends(PBRMetallicRoughnessMaterial, _super);
  46774. /**
  46775. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46776. *
  46777. * @param name The material name
  46778. * @param scene The scene the material will be use in.
  46779. */
  46780. function PBRMetallicRoughnessMaterial(name, scene) {
  46781. var _this = _super.call(this, name, scene) || this;
  46782. _this._useRoughnessFromMetallicTextureAlpha = false;
  46783. _this._useRoughnessFromMetallicTextureGreen = true;
  46784. _this._useMetallnessFromMetallicTextureBlue = true;
  46785. _this.metallic = 1.0;
  46786. _this.roughness = 1.0;
  46787. return _this;
  46788. }
  46789. /**
  46790. * Return the currrent class name of the material.
  46791. */
  46792. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46793. return "PBRMetallicRoughnessMaterial";
  46794. };
  46795. /**
  46796. * Return the active textures of the material.
  46797. */
  46798. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46799. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46800. if (this.baseTexture) {
  46801. activeTextures.push(this.baseTexture);
  46802. }
  46803. if (this.metallicRoughnessTexture) {
  46804. activeTextures.push(this.metallicRoughnessTexture);
  46805. }
  46806. return activeTextures;
  46807. };
  46808. /**
  46809. * Checks to see if a texture is used in the material.
  46810. * @param texture - Base texture to use.
  46811. * @returns - Boolean specifying if a texture is used in the material.
  46812. */
  46813. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46814. if (_super.prototype.hasTexture.call(this, texture)) {
  46815. return true;
  46816. }
  46817. if (this.baseTexture === texture) {
  46818. return true;
  46819. }
  46820. if (this.metallicRoughnessTexture === texture) {
  46821. return true;
  46822. }
  46823. return false;
  46824. };
  46825. /**
  46826. * Makes a duplicate of the current material.
  46827. * @param name - name to use for the new material.
  46828. */
  46829. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46830. var _this = this;
  46831. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46832. clone.id = name;
  46833. clone.name = name;
  46834. return clone;
  46835. };
  46836. /**
  46837. * Serialize the material to a parsable JSON object.
  46838. */
  46839. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46841. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46842. return serializationObject;
  46843. };
  46844. /**
  46845. * Parses a JSON object correponding to the serialize function.
  46846. */
  46847. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46848. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46849. };
  46850. __decorate([
  46851. BABYLON.serializeAsColor3(),
  46852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46853. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46854. __decorate([
  46855. BABYLON.serializeAsTexture(),
  46856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46857. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46858. __decorate([
  46859. BABYLON.serialize(),
  46860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46861. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46862. __decorate([
  46863. BABYLON.serialize(),
  46864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46865. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46866. __decorate([
  46867. BABYLON.serializeAsTexture(),
  46868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46869. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46870. return PBRMetallicRoughnessMaterial;
  46871. }(BABYLON.PBRBaseSimpleMaterial));
  46872. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46873. })(BABYLON || (BABYLON = {}));
  46874. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46875. var BABYLON;
  46876. (function (BABYLON) {
  46877. /**
  46878. * The PBR material of BJS following the specular glossiness convention.
  46879. *
  46880. * This fits to the PBR convention in the GLTF definition:
  46881. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46882. */
  46883. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46884. __extends(PBRSpecularGlossinessMaterial, _super);
  46885. /**
  46886. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46887. *
  46888. * @param name The material name
  46889. * @param scene The scene the material will be use in.
  46890. */
  46891. function PBRSpecularGlossinessMaterial(name, scene) {
  46892. var _this = _super.call(this, name, scene) || this;
  46893. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46894. return _this;
  46895. }
  46896. /**
  46897. * Return the currrent class name of the material.
  46898. */
  46899. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46900. return "PBRSpecularGlossinessMaterial";
  46901. };
  46902. /**
  46903. * Return the active textures of the material.
  46904. */
  46905. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46906. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46907. if (this.diffuseTexture) {
  46908. activeTextures.push(this.diffuseTexture);
  46909. }
  46910. if (this.specularGlossinessTexture) {
  46911. activeTextures.push(this.specularGlossinessTexture);
  46912. }
  46913. return activeTextures;
  46914. };
  46915. /**
  46916. * Checks to see if a texture is used in the material.
  46917. * @param texture - Base texture to use.
  46918. * @returns - Boolean specifying if a texture is used in the material.
  46919. */
  46920. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46921. if (_super.prototype.hasTexture.call(this, texture)) {
  46922. return true;
  46923. }
  46924. if (this.diffuseTexture === texture) {
  46925. return true;
  46926. }
  46927. if (this.specularGlossinessTexture === texture) {
  46928. return true;
  46929. }
  46930. return false;
  46931. };
  46932. /**
  46933. * Makes a duplicate of the current material.
  46934. * @param name - name to use for the new material.
  46935. */
  46936. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46937. var _this = this;
  46938. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46939. clone.id = name;
  46940. clone.name = name;
  46941. return clone;
  46942. };
  46943. /**
  46944. * Serialize the material to a parsable JSON object.
  46945. */
  46946. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46947. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46948. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46949. return serializationObject;
  46950. };
  46951. /**
  46952. * Parses a JSON object correponding to the serialize function.
  46953. */
  46954. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46955. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46956. };
  46957. __decorate([
  46958. BABYLON.serializeAsColor3("diffuse"),
  46959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46960. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46961. __decorate([
  46962. BABYLON.serializeAsTexture(),
  46963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46964. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46965. __decorate([
  46966. BABYLON.serializeAsColor3("specular"),
  46967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46968. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46969. __decorate([
  46970. BABYLON.serialize(),
  46971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46972. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46973. __decorate([
  46974. BABYLON.serializeAsTexture(),
  46975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46976. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46977. return PBRSpecularGlossinessMaterial;
  46978. }(BABYLON.PBRBaseSimpleMaterial));
  46979. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46980. })(BABYLON || (BABYLON = {}));
  46981. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46982. var BABYLON;
  46983. (function (BABYLON) {
  46984. /**
  46985. * This is a list of all the different input types that are available in the application.
  46986. * Fo instance: ArcRotateCameraGamepadInput...
  46987. */
  46988. BABYLON.CameraInputTypes = {};
  46989. /**
  46990. * This represents the input manager used within a camera.
  46991. * It helps dealing with all the different kind of input attached to a camera.
  46992. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46993. */
  46994. var CameraInputsManager = /** @class */ (function () {
  46995. /**
  46996. * Instantiate a new Camera Input Manager.
  46997. * @param camera Defines the camera the input manager blongs to
  46998. */
  46999. function CameraInputsManager(camera) {
  47000. this.attached = {};
  47001. this.camera = camera;
  47002. this.checkInputs = function () { };
  47003. }
  47004. /**
  47005. * Add an input method to a camera
  47006. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47007. * @param input camera input method
  47008. */
  47009. CameraInputsManager.prototype.add = function (input) {
  47010. var type = input.getSimpleName();
  47011. if (this.attached[type]) {
  47012. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47013. return;
  47014. }
  47015. this.attached[type] = input;
  47016. input.camera = this.camera;
  47017. //for checkInputs, we are dynamically creating a function
  47018. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47019. if (input.checkInputs) {
  47020. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47021. }
  47022. if (this.attachedElement) {
  47023. input.attachControl(this.attachedElement);
  47024. }
  47025. };
  47026. /**
  47027. * Remove a specific input method from a camera
  47028. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47029. * @param inputToRemove camera input method
  47030. */
  47031. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47032. for (var cam in this.attached) {
  47033. var input = this.attached[cam];
  47034. if (input === inputToRemove) {
  47035. input.detachControl(this.attachedElement);
  47036. input.camera = null;
  47037. delete this.attached[cam];
  47038. this.rebuildInputCheck();
  47039. }
  47040. }
  47041. };
  47042. /**
  47043. * Remove a specific input type from a camera
  47044. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47045. * @param inputType the type of the input to remove
  47046. */
  47047. CameraInputsManager.prototype.removeByType = function (inputType) {
  47048. for (var cam in this.attached) {
  47049. var input = this.attached[cam];
  47050. if (input.getClassName() === inputType) {
  47051. input.detachControl(this.attachedElement);
  47052. input.camera = null;
  47053. delete this.attached[cam];
  47054. this.rebuildInputCheck();
  47055. }
  47056. }
  47057. };
  47058. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47059. var current = this.checkInputs;
  47060. return function () {
  47061. current();
  47062. fn();
  47063. };
  47064. };
  47065. /**
  47066. * Attach the input controls to the currently attached dom element to listen the events from.
  47067. * @param input Defines the input to attach
  47068. */
  47069. CameraInputsManager.prototype.attachInput = function (input) {
  47070. if (this.attachedElement) {
  47071. input.attachControl(this.attachedElement, this.noPreventDefault);
  47072. }
  47073. };
  47074. /**
  47075. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47076. * @param element Defines the dom element to collect the events from
  47077. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47078. */
  47079. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47080. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47081. if (this.attachedElement) {
  47082. return;
  47083. }
  47084. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47085. this.attachedElement = element;
  47086. this.noPreventDefault = noPreventDefault;
  47087. for (var cam in this.attached) {
  47088. this.attached[cam].attachControl(element, noPreventDefault);
  47089. }
  47090. };
  47091. /**
  47092. * Detach the current manager inputs controls from a specific dom element.
  47093. * @param element Defines the dom element to collect the events from
  47094. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47095. */
  47096. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47097. if (disconnect === void 0) { disconnect = false; }
  47098. if (this.attachedElement !== element) {
  47099. return;
  47100. }
  47101. for (var cam in this.attached) {
  47102. this.attached[cam].detachControl(element);
  47103. if (disconnect) {
  47104. this.attached[cam].camera = null;
  47105. }
  47106. }
  47107. this.attachedElement = null;
  47108. };
  47109. /**
  47110. * Rebuild the dynamic inputCheck function from the current list of
  47111. * defined inputs in the manager.
  47112. */
  47113. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47114. this.checkInputs = function () { };
  47115. for (var cam in this.attached) {
  47116. var input = this.attached[cam];
  47117. if (input.checkInputs) {
  47118. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47119. }
  47120. }
  47121. };
  47122. /**
  47123. * Remove all attached input methods from a camera
  47124. */
  47125. CameraInputsManager.prototype.clear = function () {
  47126. if (this.attachedElement) {
  47127. this.detachElement(this.attachedElement, true);
  47128. }
  47129. this.attached = {};
  47130. this.attachedElement = null;
  47131. this.checkInputs = function () { };
  47132. };
  47133. /**
  47134. * Serialize the current input manager attached to a camera.
  47135. * This ensures than once parsed,
  47136. * the input associated to the camera will be identical to the current ones
  47137. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47138. */
  47139. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47140. var inputs = {};
  47141. for (var cam in this.attached) {
  47142. var input = this.attached[cam];
  47143. var res = BABYLON.SerializationHelper.Serialize(input);
  47144. inputs[input.getClassName()] = res;
  47145. }
  47146. serializedCamera.inputsmgr = inputs;
  47147. };
  47148. /**
  47149. * Parses an input manager serialized JSON to restore the previous list of inputs
  47150. * and states associated to a camera.
  47151. * @param parsedCamera Defines the JSON to parse
  47152. */
  47153. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47154. var parsedInputs = parsedCamera.inputsmgr;
  47155. if (parsedInputs) {
  47156. this.clear();
  47157. for (var n in parsedInputs) {
  47158. var construct = BABYLON.CameraInputTypes[n];
  47159. if (construct) {
  47160. var parsedinput = parsedInputs[n];
  47161. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47162. this.add(input);
  47163. }
  47164. }
  47165. }
  47166. else {
  47167. //2016-03-08 this part is for managing backward compatibility
  47168. for (var n in this.attached) {
  47169. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47170. if (construct) {
  47171. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47172. this.remove(this.attached[n]);
  47173. this.add(input);
  47174. }
  47175. }
  47176. }
  47177. };
  47178. return CameraInputsManager;
  47179. }());
  47180. BABYLON.CameraInputsManager = CameraInputsManager;
  47181. })(BABYLON || (BABYLON = {}));
  47182. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47183. var BABYLON;
  47184. (function (BABYLON) {
  47185. /**
  47186. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47187. * This is the base of the follow, arc rotate cameras and Free camera
  47188. * @see http://doc.babylonjs.com/features/cameras
  47189. */
  47190. var TargetCamera = /** @class */ (function (_super) {
  47191. __extends(TargetCamera, _super);
  47192. /**
  47193. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47194. * This is the base of the follow, arc rotate cameras and Free camera
  47195. * @see http://doc.babylonjs.com/features/cameras
  47196. * @param name Defines the name of the camera in the scene
  47197. * @param position Defines the start position of the camera in the scene
  47198. * @param scene Defines the scene the camera belongs to
  47199. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47200. */
  47201. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47202. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47203. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47204. /**
  47205. * Define the current direction the camera is moving to
  47206. */
  47207. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47208. /**
  47209. * Define the current rotation the camera is rotating to
  47210. */
  47211. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47212. /**
  47213. * Define the current rotation of the camera
  47214. */
  47215. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47216. /**
  47217. * Define the current speed of the camera
  47218. */
  47219. _this.speed = 2.0;
  47220. /**
  47221. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47222. * around all axis.
  47223. */
  47224. _this.noRotationConstraint = false;
  47225. /**
  47226. * Define the current target of the camera as an object or a position.
  47227. */
  47228. _this.lockedTarget = null;
  47229. /** @hidden */
  47230. _this._currentTarget = BABYLON.Vector3.Zero();
  47231. /** @hidden */
  47232. _this._viewMatrix = BABYLON.Matrix.Zero();
  47233. /** @hidden */
  47234. _this._camMatrix = BABYLON.Matrix.Zero();
  47235. /** @hidden */
  47236. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47237. /** @hidden */
  47238. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47239. /** @hidden */
  47240. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47241. /** @hidden */
  47242. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47243. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47244. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47245. _this._defaultUp = BABYLON.Vector3.Up();
  47246. _this._cachedRotationZ = 0;
  47247. return _this;
  47248. }
  47249. /**
  47250. * Gets the position in front of the camera at a given distance.
  47251. * @param distance The distance from the camera we want the position to be
  47252. * @returns the position
  47253. */
  47254. TargetCamera.prototype.getFrontPosition = function (distance) {
  47255. this.getWorldMatrix();
  47256. var direction = this.getTarget().subtract(this.position);
  47257. direction.normalize();
  47258. direction.scaleInPlace(distance);
  47259. return this.globalPosition.add(direction);
  47260. };
  47261. /** @hidden */
  47262. TargetCamera.prototype._getLockedTargetPosition = function () {
  47263. if (!this.lockedTarget) {
  47264. return null;
  47265. }
  47266. if (this.lockedTarget.absolutePosition) {
  47267. this.lockedTarget.computeWorldMatrix();
  47268. }
  47269. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47270. };
  47271. /**
  47272. * Store current camera state of the camera (fov, position, rotation, etc..)
  47273. * @returns the camera
  47274. */
  47275. TargetCamera.prototype.storeState = function () {
  47276. this._storedPosition = this.position.clone();
  47277. this._storedRotation = this.rotation.clone();
  47278. if (this.rotationQuaternion) {
  47279. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47280. }
  47281. return _super.prototype.storeState.call(this);
  47282. };
  47283. /**
  47284. * Restored camera state. You must call storeState() first
  47285. * @returns whether it was successful or not
  47286. * @hidden
  47287. */
  47288. TargetCamera.prototype._restoreStateValues = function () {
  47289. if (!_super.prototype._restoreStateValues.call(this)) {
  47290. return false;
  47291. }
  47292. this.position = this._storedPosition.clone();
  47293. this.rotation = this._storedRotation.clone();
  47294. if (this.rotationQuaternion) {
  47295. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47296. }
  47297. this.cameraDirection.copyFromFloats(0, 0, 0);
  47298. this.cameraRotation.copyFromFloats(0, 0);
  47299. return true;
  47300. };
  47301. /** @hidden */
  47302. TargetCamera.prototype._initCache = function () {
  47303. _super.prototype._initCache.call(this);
  47304. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47305. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47306. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47307. };
  47308. /** @hidden */
  47309. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47310. if (!ignoreParentClass) {
  47311. _super.prototype._updateCache.call(this);
  47312. }
  47313. var lockedTargetPosition = this._getLockedTargetPosition();
  47314. if (!lockedTargetPosition) {
  47315. this._cache.lockedTarget = null;
  47316. }
  47317. else {
  47318. if (!this._cache.lockedTarget) {
  47319. this._cache.lockedTarget = lockedTargetPosition.clone();
  47320. }
  47321. else {
  47322. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47323. }
  47324. }
  47325. this._cache.rotation.copyFrom(this.rotation);
  47326. if (this.rotationQuaternion)
  47327. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47328. };
  47329. // Synchronized
  47330. /** @hidden */
  47331. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47332. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47333. return false;
  47334. }
  47335. var lockedTargetPosition = this._getLockedTargetPosition();
  47336. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47337. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47338. };
  47339. // Methods
  47340. /** @hidden */
  47341. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47342. var engine = this.getEngine();
  47343. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47344. };
  47345. // Target
  47346. /** @hidden */
  47347. TargetCamera.prototype.setTarget = function (target) {
  47348. this.upVector.normalize();
  47349. if (this.position.z === target.z) {
  47350. this.position.z += BABYLON.Epsilon;
  47351. }
  47352. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47353. this._camMatrix.invert();
  47354. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47355. var vDir = target.subtract(this.position);
  47356. if (vDir.x >= 0.0) {
  47357. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47358. }
  47359. else {
  47360. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47361. }
  47362. this.rotation.z = 0;
  47363. if (isNaN(this.rotation.x)) {
  47364. this.rotation.x = 0;
  47365. }
  47366. if (isNaN(this.rotation.y)) {
  47367. this.rotation.y = 0;
  47368. }
  47369. if (isNaN(this.rotation.z)) {
  47370. this.rotation.z = 0;
  47371. }
  47372. if (this.rotationQuaternion) {
  47373. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47374. }
  47375. };
  47376. /**
  47377. * Return the current target position of the camera. This value is expressed in local space.
  47378. * @returns the target position
  47379. */
  47380. TargetCamera.prototype.getTarget = function () {
  47381. return this._currentTarget;
  47382. };
  47383. /** @hidden */
  47384. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47385. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47386. };
  47387. /** @hidden */
  47388. TargetCamera.prototype._updatePosition = function () {
  47389. if (this.parent) {
  47390. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47391. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47392. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47393. return;
  47394. }
  47395. this.position.addInPlace(this.cameraDirection);
  47396. };
  47397. /** @hidden */
  47398. TargetCamera.prototype._checkInputs = function () {
  47399. var needToMove = this._decideIfNeedsToMove();
  47400. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47401. // Move
  47402. if (needToMove) {
  47403. this._updatePosition();
  47404. }
  47405. // Rotate
  47406. if (needToRotate) {
  47407. this.rotation.x += this.cameraRotation.x;
  47408. this.rotation.y += this.cameraRotation.y;
  47409. //rotate, if quaternion is set and rotation was used
  47410. if (this.rotationQuaternion) {
  47411. var len = this.rotation.lengthSquared();
  47412. if (len) {
  47413. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47414. }
  47415. }
  47416. if (!this.noRotationConstraint) {
  47417. var limit = (Math.PI / 2) * 0.95;
  47418. if (this.rotation.x > limit)
  47419. this.rotation.x = limit;
  47420. if (this.rotation.x < -limit)
  47421. this.rotation.x = -limit;
  47422. }
  47423. }
  47424. // Inertia
  47425. if (needToMove) {
  47426. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47427. this.cameraDirection.x = 0;
  47428. }
  47429. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47430. this.cameraDirection.y = 0;
  47431. }
  47432. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47433. this.cameraDirection.z = 0;
  47434. }
  47435. this.cameraDirection.scaleInPlace(this.inertia);
  47436. }
  47437. if (needToRotate) {
  47438. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47439. this.cameraRotation.x = 0;
  47440. }
  47441. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47442. this.cameraRotation.y = 0;
  47443. }
  47444. this.cameraRotation.scaleInPlace(this.inertia);
  47445. }
  47446. _super.prototype._checkInputs.call(this);
  47447. };
  47448. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47449. if (this.rotationQuaternion) {
  47450. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47451. }
  47452. else {
  47453. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47454. }
  47455. };
  47456. /**
  47457. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  47458. * @returns the current camera
  47459. */
  47460. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47461. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47462. return this;
  47463. };
  47464. /** @hidden */
  47465. TargetCamera.prototype._getViewMatrix = function () {
  47466. if (this.lockedTarget) {
  47467. this.setTarget(this._getLockedTargetPosition());
  47468. }
  47469. // Compute
  47470. this._updateCameraRotationMatrix();
  47471. // Apply the changed rotation to the upVector.
  47472. if (this._cachedRotationZ != this.rotation.z) {
  47473. this._rotateUpVectorWithCameraRotationMatrix();
  47474. this._cachedRotationZ = this.rotation.z;
  47475. }
  47476. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47477. // Computing target and final matrix
  47478. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47479. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47480. return this._viewMatrix;
  47481. };
  47482. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47483. if (this.parent) {
  47484. var parentWorldMatrix = this.parent.getWorldMatrix();
  47485. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47486. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47487. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47488. this._markSyncedWithParent();
  47489. }
  47490. else {
  47491. this._globalPosition.copyFrom(position);
  47492. this._globalCurrentTarget.copyFrom(target);
  47493. this._globalCurrentUpVector.copyFrom(up);
  47494. }
  47495. if (this.getScene().useRightHandedSystem) {
  47496. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47497. }
  47498. else {
  47499. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47500. }
  47501. };
  47502. /**
  47503. * @hidden
  47504. */
  47505. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47506. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47507. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47508. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47509. if (!this.rotationQuaternion) {
  47510. this.rotationQuaternion = new BABYLON.Quaternion();
  47511. }
  47512. rigCamera._cameraRigParams = {};
  47513. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47514. }
  47515. return rigCamera;
  47516. }
  47517. return null;
  47518. };
  47519. /**
  47520. * @hidden
  47521. */
  47522. TargetCamera.prototype._updateRigCameras = function () {
  47523. var camLeft = this._rigCameras[0];
  47524. var camRight = this._rigCameras[1];
  47525. switch (this.cameraRigMode) {
  47526. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47530. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47531. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47532. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47533. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47534. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47535. camLeft.setTarget(this.getTarget());
  47536. camRight.setTarget(this.getTarget());
  47537. break;
  47538. case BABYLON.Camera.RIG_MODE_VR:
  47539. if (camLeft.rotationQuaternion) {
  47540. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47541. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47542. }
  47543. else {
  47544. camLeft.rotation.copyFrom(this.rotation);
  47545. camRight.rotation.copyFrom(this.rotation);
  47546. }
  47547. camLeft.position.copyFrom(this.position);
  47548. camRight.position.copyFrom(this.position);
  47549. break;
  47550. }
  47551. _super.prototype._updateRigCameras.call(this);
  47552. };
  47553. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47554. if (!this._rigCamTransformMatrix) {
  47555. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47556. }
  47557. var target = this.getTarget();
  47558. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47559. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47560. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47561. };
  47562. /**
  47563. * Gets the current object class name.
  47564. * @return the class name
  47565. */
  47566. TargetCamera.prototype.getClassName = function () {
  47567. return "TargetCamera";
  47568. };
  47569. __decorate([
  47570. BABYLON.serializeAsVector3()
  47571. ], TargetCamera.prototype, "rotation", void 0);
  47572. __decorate([
  47573. BABYLON.serialize()
  47574. ], TargetCamera.prototype, "speed", void 0);
  47575. __decorate([
  47576. BABYLON.serializeAsMeshReference("lockedTargetId")
  47577. ], TargetCamera.prototype, "lockedTarget", void 0);
  47578. return TargetCamera;
  47579. }(BABYLON.Camera));
  47580. BABYLON.TargetCamera = TargetCamera;
  47581. })(BABYLON || (BABYLON = {}));
  47582. //# sourceMappingURL=babylon.targetCamera.js.map
  47583. var BABYLON;
  47584. (function (BABYLON) {
  47585. /**
  47586. * Manage the mouse inputs to control the movement of a free camera.
  47587. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47588. */
  47589. var FreeCameraMouseInput = /** @class */ (function () {
  47590. /**
  47591. * Manage the mouse inputs to control the movement of a free camera.
  47592. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47593. * @param touchEnabled Defines if touch is enabled or not
  47594. */
  47595. function FreeCameraMouseInput(
  47596. /**
  47597. * Define if touch is enabled in the mouse input
  47598. */
  47599. touchEnabled) {
  47600. if (touchEnabled === void 0) { touchEnabled = true; }
  47601. this.touchEnabled = touchEnabled;
  47602. /**
  47603. * Defines the buttons associated with the input to handle camera move.
  47604. */
  47605. this.buttons = [0, 1, 2];
  47606. /**
  47607. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47608. */
  47609. this.angularSensibility = 2000.0;
  47610. this.previousPosition = null;
  47611. }
  47612. /**
  47613. * Attach the input controls to a specific dom element to get the input from.
  47614. * @param element Defines the element the controls should be listened from
  47615. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47616. */
  47617. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47618. var _this = this;
  47619. var engine = this.camera.getEngine();
  47620. if (!this._pointerInput) {
  47621. this._pointerInput = function (p, s) {
  47622. var evt = p.event;
  47623. if (engine.isInVRExclusivePointerMode) {
  47624. return;
  47625. }
  47626. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47627. return;
  47628. }
  47629. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47630. return;
  47631. }
  47632. var srcElement = (evt.srcElement || evt.target);
  47633. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47634. try {
  47635. srcElement.setPointerCapture(evt.pointerId);
  47636. }
  47637. catch (e) {
  47638. //Nothing to do with the error. Execution will continue.
  47639. }
  47640. _this.previousPosition = {
  47641. x: evt.clientX,
  47642. y: evt.clientY
  47643. };
  47644. if (!noPreventDefault) {
  47645. evt.preventDefault();
  47646. element.focus();
  47647. }
  47648. }
  47649. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47650. try {
  47651. srcElement.releasePointerCapture(evt.pointerId);
  47652. }
  47653. catch (e) {
  47654. //Nothing to do with the error.
  47655. }
  47656. _this.previousPosition = null;
  47657. if (!noPreventDefault) {
  47658. evt.preventDefault();
  47659. }
  47660. }
  47661. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47662. if (!_this.previousPosition || engine.isPointerLock) {
  47663. return;
  47664. }
  47665. var offsetX = evt.clientX - _this.previousPosition.x;
  47666. if (_this.camera.getScene().useRightHandedSystem)
  47667. offsetX *= -1;
  47668. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47669. offsetX *= -1;
  47670. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47671. var offsetY = evt.clientY - _this.previousPosition.y;
  47672. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47673. _this.previousPosition = {
  47674. x: evt.clientX,
  47675. y: evt.clientY
  47676. };
  47677. if (!noPreventDefault) {
  47678. evt.preventDefault();
  47679. }
  47680. }
  47681. };
  47682. }
  47683. this._onMouseMove = function (evt) {
  47684. if (!engine.isPointerLock) {
  47685. return;
  47686. }
  47687. if (engine.isInVRExclusivePointerMode) {
  47688. return;
  47689. }
  47690. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47691. if (_this.camera.getScene().useRightHandedSystem)
  47692. offsetX *= -1;
  47693. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47694. offsetX *= -1;
  47695. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47696. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47697. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47698. _this.previousPosition = null;
  47699. if (!noPreventDefault) {
  47700. evt.preventDefault();
  47701. }
  47702. };
  47703. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47704. element.addEventListener("mousemove", this._onMouseMove, false);
  47705. };
  47706. /**
  47707. * Detach the current controls from the specified dom element.
  47708. * @param element Defines the element to stop listening the inputs from
  47709. */
  47710. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47711. if (this._observer && element) {
  47712. this.camera.getScene().onPointerObservable.remove(this._observer);
  47713. if (this._onMouseMove) {
  47714. element.removeEventListener("mousemove", this._onMouseMove);
  47715. }
  47716. this._observer = null;
  47717. this._onMouseMove = null;
  47718. this.previousPosition = null;
  47719. }
  47720. };
  47721. /**
  47722. * Gets the class name of the current intput.
  47723. * @returns the class name
  47724. */
  47725. FreeCameraMouseInput.prototype.getClassName = function () {
  47726. return "FreeCameraMouseInput";
  47727. };
  47728. /**
  47729. * Get the friendly name associated with the input class.
  47730. * @returns the input friendly name
  47731. */
  47732. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47733. return "mouse";
  47734. };
  47735. __decorate([
  47736. BABYLON.serialize()
  47737. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47738. __decorate([
  47739. BABYLON.serialize()
  47740. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47741. return FreeCameraMouseInput;
  47742. }());
  47743. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47744. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47745. })(BABYLON || (BABYLON = {}));
  47746. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47747. var BABYLON;
  47748. (function (BABYLON) {
  47749. /**
  47750. * Manage the keyboard inputs to control the movement of a free camera.
  47751. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47752. */
  47753. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47754. function FreeCameraKeyboardMoveInput() {
  47755. /**
  47756. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47757. */
  47758. this.keysUp = [38];
  47759. /**
  47760. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47761. */
  47762. this.keysDown = [40];
  47763. /**
  47764. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47765. */
  47766. this.keysLeft = [37];
  47767. /**
  47768. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47769. */
  47770. this.keysRight = [39];
  47771. this._keys = new Array();
  47772. }
  47773. /**
  47774. * Attach the input controls to a specific dom element to get the input from.
  47775. * @param element Defines the element the controls should be listened from
  47776. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47777. */
  47778. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47779. var _this = this;
  47780. if (this._onCanvasBlurObserver) {
  47781. return;
  47782. }
  47783. this._scene = this.camera.getScene();
  47784. this._engine = this._scene.getEngine();
  47785. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47786. _this._keys = [];
  47787. });
  47788. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47789. var evt = info.event;
  47790. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47791. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47792. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47793. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47794. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47795. var index = _this._keys.indexOf(evt.keyCode);
  47796. if (index === -1) {
  47797. _this._keys.push(evt.keyCode);
  47798. }
  47799. if (!noPreventDefault) {
  47800. evt.preventDefault();
  47801. }
  47802. }
  47803. }
  47804. else {
  47805. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47806. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47807. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47808. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47809. var index = _this._keys.indexOf(evt.keyCode);
  47810. if (index >= 0) {
  47811. _this._keys.splice(index, 1);
  47812. }
  47813. if (!noPreventDefault) {
  47814. evt.preventDefault();
  47815. }
  47816. }
  47817. }
  47818. });
  47819. };
  47820. /**
  47821. * Detach the current controls from the specified dom element.
  47822. * @param element Defines the element to stop listening the inputs from
  47823. */
  47824. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47825. if (this._scene) {
  47826. if (this._onKeyboardObserver) {
  47827. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47828. }
  47829. if (this._onCanvasBlurObserver) {
  47830. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47831. }
  47832. this._onKeyboardObserver = null;
  47833. this._onCanvasBlurObserver = null;
  47834. }
  47835. this._keys = [];
  47836. };
  47837. /**
  47838. * Update the current camera state depending on the inputs that have been used this frame.
  47839. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47840. */
  47841. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47842. if (this._onKeyboardObserver) {
  47843. var camera = this.camera;
  47844. // Keyboard
  47845. for (var index = 0; index < this._keys.length; index++) {
  47846. var keyCode = this._keys[index];
  47847. var speed = camera._computeLocalCameraSpeed();
  47848. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47849. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47850. }
  47851. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47852. camera._localDirection.copyFromFloats(0, 0, speed);
  47853. }
  47854. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47855. camera._localDirection.copyFromFloats(speed, 0, 0);
  47856. }
  47857. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47858. camera._localDirection.copyFromFloats(0, 0, -speed);
  47859. }
  47860. if (camera.getScene().useRightHandedSystem) {
  47861. camera._localDirection.z *= -1;
  47862. }
  47863. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47864. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47865. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47866. }
  47867. }
  47868. };
  47869. /**
  47870. * Gets the class name of the current intput.
  47871. * @returns the class name
  47872. */
  47873. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47874. return "FreeCameraKeyboardMoveInput";
  47875. };
  47876. /** @hidden */
  47877. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47878. this._keys = [];
  47879. };
  47880. /**
  47881. * Get the friendly name associated with the input class.
  47882. * @returns the input friendly name
  47883. */
  47884. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47885. return "keyboard";
  47886. };
  47887. __decorate([
  47888. BABYLON.serialize()
  47889. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47890. __decorate([
  47891. BABYLON.serialize()
  47892. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47893. __decorate([
  47894. BABYLON.serialize()
  47895. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47896. __decorate([
  47897. BABYLON.serialize()
  47898. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47899. return FreeCameraKeyboardMoveInput;
  47900. }());
  47901. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47902. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47903. })(BABYLON || (BABYLON = {}));
  47904. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47905. var BABYLON;
  47906. (function (BABYLON) {
  47907. /**
  47908. * Default Inputs manager for the FreeCamera.
  47909. * It groups all the default supported inputs for ease of use.
  47910. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47911. */
  47912. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47913. __extends(FreeCameraInputsManager, _super);
  47914. /**
  47915. * Instantiates a new FreeCameraInputsManager.
  47916. * @param camera Defines the camera the inputs belong to
  47917. */
  47918. function FreeCameraInputsManager(camera) {
  47919. return _super.call(this, camera) || this;
  47920. }
  47921. /**
  47922. * Add keyboard input support to the input manager.
  47923. * @returns the current input manager
  47924. */
  47925. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47926. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47927. return this;
  47928. };
  47929. /**
  47930. * Add mouse input support to the input manager.
  47931. * @returns the current input manager
  47932. */
  47933. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47934. if (touchEnabled === void 0) { touchEnabled = true; }
  47935. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47936. return this;
  47937. };
  47938. /**
  47939. * Add orientation input support to the input manager.
  47940. * @returns the current input manager
  47941. */
  47942. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47943. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47944. return this;
  47945. };
  47946. /**
  47947. * Add touch input support to the input manager.
  47948. * @returns the current input manager
  47949. */
  47950. FreeCameraInputsManager.prototype.addTouch = function () {
  47951. this.add(new BABYLON.FreeCameraTouchInput());
  47952. return this;
  47953. };
  47954. /**
  47955. * Add virtual joystick input support to the input manager.
  47956. * @returns the current input manager
  47957. */
  47958. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47959. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47960. return this;
  47961. };
  47962. return FreeCameraInputsManager;
  47963. }(BABYLON.CameraInputsManager));
  47964. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47965. })(BABYLON || (BABYLON = {}));
  47966. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47967. var BABYLON;
  47968. (function (BABYLON) {
  47969. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47970. // Forcing to use the Universal camera
  47971. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47972. });
  47973. /**
  47974. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47975. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47976. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47977. */
  47978. var FreeCamera = /** @class */ (function (_super) {
  47979. __extends(FreeCamera, _super);
  47980. /**
  47981. * Instantiates a Free Camera.
  47982. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47983. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47984. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47985. * @param name Define the name of the camera in the scene
  47986. * @param position Define the start position of the camera in the scene
  47987. * @param scene Define the scene the camera belongs to
  47988. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47989. */
  47990. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47991. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47992. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47993. /**
  47994. * Define the collision ellipsoid of the camera.
  47995. * This is helpful to simulate a camera body like the player body around the camera
  47996. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47997. */
  47998. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47999. /**
  48000. * Define an offset for the position of the ellipsoid around the camera.
  48001. * This can be helpful to determine the center of the body near the gravity center of the body
  48002. * instead of its head.
  48003. */
  48004. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48005. /**
  48006. * Enable or disable collisions of the camera with the rest of the scene objects.
  48007. */
  48008. _this.checkCollisions = false;
  48009. /**
  48010. * Enable or disable gravity on the camera.
  48011. */
  48012. _this.applyGravity = false;
  48013. _this._needMoveForGravity = false;
  48014. _this._oldPosition = BABYLON.Vector3.Zero();
  48015. _this._diffPosition = BABYLON.Vector3.Zero();
  48016. _this._newPosition = BABYLON.Vector3.Zero();
  48017. // Collisions
  48018. _this._collisionMask = -1;
  48019. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48020. if (collidedMesh === void 0) { collidedMesh = null; }
  48021. //TODO move this to the collision coordinator!
  48022. if (_this.getScene().workerCollisions)
  48023. newPosition.multiplyInPlace(_this._collider._radius);
  48024. var updatePosition = function (newPos) {
  48025. _this._newPosition.copyFrom(newPos);
  48026. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48027. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48028. _this.position.addInPlace(_this._diffPosition);
  48029. if (_this.onCollide && collidedMesh) {
  48030. _this.onCollide(collidedMesh);
  48031. }
  48032. }
  48033. };
  48034. updatePosition(newPosition);
  48035. };
  48036. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48037. _this.inputs.addKeyboard().addMouse();
  48038. return _this;
  48039. }
  48040. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48041. /**
  48042. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48043. * Higher values reduce sensitivity.
  48044. */
  48045. get: function () {
  48046. var mouse = this.inputs.attached["mouse"];
  48047. if (mouse)
  48048. return mouse.angularSensibility;
  48049. return 0;
  48050. },
  48051. /**
  48052. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48053. * Higher values reduce sensitivity.
  48054. */
  48055. set: function (value) {
  48056. var mouse = this.inputs.attached["mouse"];
  48057. if (mouse)
  48058. mouse.angularSensibility = value;
  48059. },
  48060. enumerable: true,
  48061. configurable: true
  48062. });
  48063. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48064. /**
  48065. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48066. */
  48067. get: function () {
  48068. var keyboard = this.inputs.attached["keyboard"];
  48069. if (keyboard)
  48070. return keyboard.keysUp;
  48071. return [];
  48072. },
  48073. set: function (value) {
  48074. var keyboard = this.inputs.attached["keyboard"];
  48075. if (keyboard)
  48076. keyboard.keysUp = value;
  48077. },
  48078. enumerable: true,
  48079. configurable: true
  48080. });
  48081. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48082. /**
  48083. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48084. */
  48085. get: function () {
  48086. var keyboard = this.inputs.attached["keyboard"];
  48087. if (keyboard)
  48088. return keyboard.keysDown;
  48089. return [];
  48090. },
  48091. set: function (value) {
  48092. var keyboard = this.inputs.attached["keyboard"];
  48093. if (keyboard)
  48094. keyboard.keysDown = value;
  48095. },
  48096. enumerable: true,
  48097. configurable: true
  48098. });
  48099. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48100. /**
  48101. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48102. */
  48103. get: function () {
  48104. var keyboard = this.inputs.attached["keyboard"];
  48105. if (keyboard)
  48106. return keyboard.keysLeft;
  48107. return [];
  48108. },
  48109. set: function (value) {
  48110. var keyboard = this.inputs.attached["keyboard"];
  48111. if (keyboard)
  48112. keyboard.keysLeft = value;
  48113. },
  48114. enumerable: true,
  48115. configurable: true
  48116. });
  48117. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48118. /**
  48119. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48120. */
  48121. get: function () {
  48122. var keyboard = this.inputs.attached["keyboard"];
  48123. if (keyboard)
  48124. return keyboard.keysRight;
  48125. return [];
  48126. },
  48127. set: function (value) {
  48128. var keyboard = this.inputs.attached["keyboard"];
  48129. if (keyboard)
  48130. keyboard.keysRight = value;
  48131. },
  48132. enumerable: true,
  48133. configurable: true
  48134. });
  48135. /**
  48136. * Attached controls to the current camera.
  48137. * @param element Defines the element the controls should be listened from
  48138. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48139. */
  48140. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48141. this.inputs.attachElement(element, noPreventDefault);
  48142. };
  48143. /**
  48144. * Detach the current controls from the camera.
  48145. * The camera will stop reacting to inputs.
  48146. * @param element Defines the element to stop listening the inputs from
  48147. */
  48148. FreeCamera.prototype.detachControl = function (element) {
  48149. this.inputs.detachElement(element);
  48150. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48151. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48152. };
  48153. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48154. /**
  48155. * Define a collision mask to limit the list of object the camera can collide with
  48156. */
  48157. get: function () {
  48158. return this._collisionMask;
  48159. },
  48160. set: function (mask) {
  48161. this._collisionMask = !isNaN(mask) ? mask : -1;
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. /** @hidden */
  48167. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48168. var globalPosition;
  48169. if (this.parent) {
  48170. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48171. }
  48172. else {
  48173. globalPosition = this.position;
  48174. }
  48175. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48176. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48177. if (!this._collider) {
  48178. this._collider = new BABYLON.Collider();
  48179. }
  48180. this._collider._radius = this.ellipsoid;
  48181. this._collider.collisionMask = this._collisionMask;
  48182. //no need for clone, as long as gravity is not on.
  48183. var actualDisplacement = displacement;
  48184. //add gravity to the direction to prevent the dual-collision checking
  48185. if (this.applyGravity) {
  48186. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48187. actualDisplacement = displacement.add(this.getScene().gravity);
  48188. }
  48189. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48190. };
  48191. /** @hidden */
  48192. FreeCamera.prototype._checkInputs = function () {
  48193. if (!this._localDirection) {
  48194. this._localDirection = BABYLON.Vector3.Zero();
  48195. this._transformedDirection = BABYLON.Vector3.Zero();
  48196. }
  48197. this.inputs.checkInputs();
  48198. _super.prototype._checkInputs.call(this);
  48199. };
  48200. /** @hidden */
  48201. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48202. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48203. };
  48204. /** @hidden */
  48205. FreeCamera.prototype._updatePosition = function () {
  48206. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48207. this._collideWithWorld(this.cameraDirection);
  48208. }
  48209. else {
  48210. _super.prototype._updatePosition.call(this);
  48211. }
  48212. };
  48213. /**
  48214. * Destroy the camera and release the current resources hold by it.
  48215. */
  48216. FreeCamera.prototype.dispose = function () {
  48217. this.inputs.clear();
  48218. _super.prototype.dispose.call(this);
  48219. };
  48220. /**
  48221. * Gets the current object class name.
  48222. * @return the class name
  48223. */
  48224. FreeCamera.prototype.getClassName = function () {
  48225. return "FreeCamera";
  48226. };
  48227. __decorate([
  48228. BABYLON.serializeAsVector3()
  48229. ], FreeCamera.prototype, "ellipsoid", void 0);
  48230. __decorate([
  48231. BABYLON.serializeAsVector3()
  48232. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], FreeCamera.prototype, "checkCollisions", void 0);
  48236. __decorate([
  48237. BABYLON.serialize()
  48238. ], FreeCamera.prototype, "applyGravity", void 0);
  48239. return FreeCamera;
  48240. }(BABYLON.TargetCamera));
  48241. BABYLON.FreeCamera = FreeCamera;
  48242. })(BABYLON || (BABYLON = {}));
  48243. //# sourceMappingURL=babylon.freeCamera.js.map
  48244. var BABYLON;
  48245. (function (BABYLON) {
  48246. /**
  48247. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48248. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48249. */
  48250. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48251. function ArcRotateCameraKeyboardMoveInput() {
  48252. /**
  48253. * Defines the list of key codes associated with the up action (increase alpha)
  48254. */
  48255. this.keysUp = [38];
  48256. /**
  48257. * Defines the list of key codes associated with the down action (decrease alpha)
  48258. */
  48259. this.keysDown = [40];
  48260. /**
  48261. * Defines the list of key codes associated with the left action (increase beta)
  48262. */
  48263. this.keysLeft = [37];
  48264. /**
  48265. * Defines the list of key codes associated with the right action (decrease beta)
  48266. */
  48267. this.keysRight = [39];
  48268. /**
  48269. * Defines the list of key codes associated with the reset action.
  48270. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48271. */
  48272. this.keysReset = [220];
  48273. /**
  48274. * Defines the panning sensibility of the inputs.
  48275. * (How fast is the camera paning)
  48276. */
  48277. this.panningSensibility = 50.0;
  48278. /**
  48279. * Defines the zooming sensibility of the inputs.
  48280. * (How fast is the camera zooming)
  48281. */
  48282. this.zoomingSensibility = 25.0;
  48283. /**
  48284. * Defines wether maintaining the alt key down switch the movement mode from
  48285. * orientation to zoom.
  48286. */
  48287. this.useAltToZoom = true;
  48288. this._keys = new Array();
  48289. }
  48290. /**
  48291. * Attach the input controls to a specific dom element to get the input from.
  48292. * @param element Defines the element the controls should be listened from
  48293. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48294. */
  48295. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48296. var _this = this;
  48297. if (this._onCanvasBlurObserver) {
  48298. return;
  48299. }
  48300. this._scene = this.camera.getScene();
  48301. this._engine = this._scene.getEngine();
  48302. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48303. _this._keys = [];
  48304. });
  48305. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48306. var evt = info.event;
  48307. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48308. _this._ctrlPressed = evt.ctrlKey;
  48309. _this._altPressed = evt.altKey;
  48310. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48311. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48312. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48313. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48314. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48315. var index = _this._keys.indexOf(evt.keyCode);
  48316. if (index === -1) {
  48317. _this._keys.push(evt.keyCode);
  48318. }
  48319. if (evt.preventDefault) {
  48320. if (!noPreventDefault) {
  48321. evt.preventDefault();
  48322. }
  48323. }
  48324. }
  48325. }
  48326. else {
  48327. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48328. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48329. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48330. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48331. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48332. var index = _this._keys.indexOf(evt.keyCode);
  48333. if (index >= 0) {
  48334. _this._keys.splice(index, 1);
  48335. }
  48336. if (evt.preventDefault) {
  48337. if (!noPreventDefault) {
  48338. evt.preventDefault();
  48339. }
  48340. }
  48341. }
  48342. }
  48343. });
  48344. };
  48345. /**
  48346. * Detach the current controls from the specified dom element.
  48347. * @param element Defines the element to stop listening the inputs from
  48348. */
  48349. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48350. if (this._scene) {
  48351. if (this._onKeyboardObserver) {
  48352. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48353. }
  48354. if (this._onCanvasBlurObserver) {
  48355. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48356. }
  48357. this._onKeyboardObserver = null;
  48358. this._onCanvasBlurObserver = null;
  48359. }
  48360. this._keys = [];
  48361. };
  48362. /**
  48363. * Update the current camera state depending on the inputs that have been used this frame.
  48364. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48365. */
  48366. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48367. if (this._onKeyboardObserver) {
  48368. var camera = this.camera;
  48369. for (var index = 0; index < this._keys.length; index++) {
  48370. var keyCode = this._keys[index];
  48371. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48372. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48373. camera.inertialPanningX -= 1 / this.panningSensibility;
  48374. }
  48375. else {
  48376. camera.inertialAlphaOffset -= 0.01;
  48377. }
  48378. }
  48379. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48380. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48381. camera.inertialPanningY += 1 / this.panningSensibility;
  48382. }
  48383. else if (this._altPressed && this.useAltToZoom) {
  48384. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48385. }
  48386. else {
  48387. camera.inertialBetaOffset -= 0.01;
  48388. }
  48389. }
  48390. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48391. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48392. camera.inertialPanningX += 1 / this.panningSensibility;
  48393. }
  48394. else {
  48395. camera.inertialAlphaOffset += 0.01;
  48396. }
  48397. }
  48398. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48399. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48400. camera.inertialPanningY -= 1 / this.panningSensibility;
  48401. }
  48402. else if (this._altPressed && this.useAltToZoom) {
  48403. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48404. }
  48405. else {
  48406. camera.inertialBetaOffset += 0.01;
  48407. }
  48408. }
  48409. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48410. if (camera.useInputToRestoreState) {
  48411. camera.restoreState();
  48412. }
  48413. }
  48414. }
  48415. }
  48416. };
  48417. /**
  48418. * Gets the class name of the current intput.
  48419. * @returns the class name
  48420. */
  48421. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48422. return "ArcRotateCameraKeyboardMoveInput";
  48423. };
  48424. /**
  48425. * Get the friendly name associated with the input class.
  48426. * @returns the input friendly name
  48427. */
  48428. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48429. return "keyboard";
  48430. };
  48431. __decorate([
  48432. BABYLON.serialize()
  48433. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48434. __decorate([
  48435. BABYLON.serialize()
  48436. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48437. __decorate([
  48438. BABYLON.serialize()
  48439. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48440. __decorate([
  48441. BABYLON.serialize()
  48442. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48443. __decorate([
  48444. BABYLON.serialize()
  48445. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48446. __decorate([
  48447. BABYLON.serialize()
  48448. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48449. __decorate([
  48450. BABYLON.serialize()
  48451. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48452. __decorate([
  48453. BABYLON.serialize()
  48454. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48455. return ArcRotateCameraKeyboardMoveInput;
  48456. }());
  48457. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48458. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48459. })(BABYLON || (BABYLON = {}));
  48460. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48461. var BABYLON;
  48462. (function (BABYLON) {
  48463. /**
  48464. * Manage the mouse wheel inputs to control an arc rotate camera.
  48465. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48466. */
  48467. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48468. function ArcRotateCameraMouseWheelInput() {
  48469. /**
  48470. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48471. */
  48472. this.wheelPrecision = 3.0;
  48473. /**
  48474. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48475. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48476. */
  48477. this.wheelDeltaPercentage = 0;
  48478. }
  48479. /**
  48480. * Attach the input controls to a specific dom element to get the input from.
  48481. * @param element Defines the element the controls should be listened from
  48482. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48483. */
  48484. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48485. var _this = this;
  48486. this._wheel = function (p, s) {
  48487. //sanity check - this should be a PointerWheel event.
  48488. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48489. return;
  48490. var event = p.event;
  48491. var delta = 0;
  48492. if (event.wheelDelta) {
  48493. if (_this.wheelDeltaPercentage) {
  48494. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48495. if (event.wheelDelta > 0) {
  48496. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48497. }
  48498. else {
  48499. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48500. }
  48501. }
  48502. else {
  48503. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48504. }
  48505. }
  48506. else if (event.detail) {
  48507. delta = -event.detail / _this.wheelPrecision;
  48508. }
  48509. if (delta)
  48510. _this.camera.inertialRadiusOffset += delta;
  48511. if (event.preventDefault) {
  48512. if (!noPreventDefault) {
  48513. event.preventDefault();
  48514. }
  48515. }
  48516. };
  48517. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48518. };
  48519. /**
  48520. * Detach the current controls from the specified dom element.
  48521. * @param element Defines the element to stop listening the inputs from
  48522. */
  48523. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48524. if (this._observer && element) {
  48525. this.camera.getScene().onPointerObservable.remove(this._observer);
  48526. this._observer = null;
  48527. this._wheel = null;
  48528. }
  48529. };
  48530. /**
  48531. * Gets the class name of the current intput.
  48532. * @returns the class name
  48533. */
  48534. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48535. return "ArcRotateCameraMouseWheelInput";
  48536. };
  48537. /**
  48538. * Get the friendly name associated with the input class.
  48539. * @returns the input friendly name
  48540. */
  48541. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48542. return "mousewheel";
  48543. };
  48544. __decorate([
  48545. BABYLON.serialize()
  48546. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48547. __decorate([
  48548. BABYLON.serialize()
  48549. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48550. return ArcRotateCameraMouseWheelInput;
  48551. }());
  48552. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48553. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48554. })(BABYLON || (BABYLON = {}));
  48555. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48556. var BABYLON;
  48557. (function (BABYLON) {
  48558. /**
  48559. * Manage the pointers inputs to control an arc rotate camera.
  48560. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48561. */
  48562. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48563. function ArcRotateCameraPointersInput() {
  48564. /**
  48565. * Defines the buttons associated with the input to handle camera move.
  48566. */
  48567. this.buttons = [0, 1, 2];
  48568. /**
  48569. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48570. */
  48571. this.angularSensibilityX = 1000.0;
  48572. /**
  48573. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48574. */
  48575. this.angularSensibilityY = 1000.0;
  48576. /**
  48577. * Defines the pointer pinch precision or how fast is the camera zooming.
  48578. */
  48579. this.pinchPrecision = 12.0;
  48580. /**
  48581. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48582. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48583. */
  48584. this.pinchDeltaPercentage = 0;
  48585. /**
  48586. * Defines the pointer panning sensibility or how fast is the camera moving.
  48587. */
  48588. this.panningSensibility = 1000.0;
  48589. /**
  48590. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48591. */
  48592. this.multiTouchPanning = true;
  48593. /**
  48594. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48595. */
  48596. this.multiTouchPanAndZoom = true;
  48597. /**
  48598. * Revers pinch action direction.
  48599. */
  48600. this.pinchInwards = true;
  48601. this._isPanClick = false;
  48602. }
  48603. /**
  48604. * Attach the input controls to a specific dom element to get the input from.
  48605. * @param element Defines the element the controls should be listened from
  48606. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48607. */
  48608. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48609. var _this = this;
  48610. var engine = this.camera.getEngine();
  48611. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48612. var pointA = null;
  48613. var pointB = null;
  48614. var previousPinchSquaredDistance = 0;
  48615. var initialDistance = 0;
  48616. var twoFingerActivityCount = 0;
  48617. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48618. this._pointerInput = function (p, s) {
  48619. var evt = p.event;
  48620. var isTouch = p.event.pointerType === "touch";
  48621. if (engine.isInVRExclusivePointerMode) {
  48622. return;
  48623. }
  48624. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48625. return;
  48626. }
  48627. var srcElement = (evt.srcElement || evt.target);
  48628. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48629. try {
  48630. srcElement.setPointerCapture(evt.pointerId);
  48631. }
  48632. catch (e) {
  48633. //Nothing to do with the error. Execution will continue.
  48634. }
  48635. // Manage panning with pan button click
  48636. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48637. // manage pointers
  48638. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48639. if (pointA === null) {
  48640. pointA = cacheSoloPointer;
  48641. }
  48642. else if (pointB === null) {
  48643. pointB = cacheSoloPointer;
  48644. }
  48645. if (!noPreventDefault) {
  48646. evt.preventDefault();
  48647. element.focus();
  48648. }
  48649. }
  48650. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48651. if (_this.camera.useInputToRestoreState) {
  48652. _this.camera.restoreState();
  48653. }
  48654. }
  48655. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48656. try {
  48657. srcElement.releasePointerCapture(evt.pointerId);
  48658. }
  48659. catch (e) {
  48660. //Nothing to do with the error.
  48661. }
  48662. cacheSoloPointer = null;
  48663. previousPinchSquaredDistance = 0;
  48664. previousMultiTouchPanPosition.isPaning = false;
  48665. previousMultiTouchPanPosition.isPinching = false;
  48666. twoFingerActivityCount = 0;
  48667. initialDistance = 0;
  48668. if (!isTouch) {
  48669. pointB = null; // Mouse and pen are mono pointer
  48670. }
  48671. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48672. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48673. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48674. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48675. if (engine._badOS) {
  48676. pointA = pointB = null;
  48677. }
  48678. else {
  48679. //only remove the impacted pointer in case of multitouch allowing on most
  48680. //platforms switching from rotate to zoom and pan seamlessly.
  48681. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48682. pointA = pointB;
  48683. pointB = null;
  48684. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48685. }
  48686. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48687. pointB = null;
  48688. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48689. }
  48690. else {
  48691. pointA = pointB = null;
  48692. }
  48693. }
  48694. if (!noPreventDefault) {
  48695. evt.preventDefault();
  48696. }
  48697. }
  48698. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48699. if (!noPreventDefault) {
  48700. evt.preventDefault();
  48701. }
  48702. // One button down
  48703. if (pointA && pointB === null && cacheSoloPointer) {
  48704. if (_this.panningSensibility !== 0 &&
  48705. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48706. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48707. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48708. }
  48709. else {
  48710. var offsetX = evt.clientX - cacheSoloPointer.x;
  48711. var offsetY = evt.clientY - cacheSoloPointer.y;
  48712. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48713. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48714. }
  48715. cacheSoloPointer.x = evt.clientX;
  48716. cacheSoloPointer.y = evt.clientY;
  48717. }
  48718. // Two buttons down: pinch/pan
  48719. else if (pointA && pointB) {
  48720. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48721. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48722. ed.x = evt.clientX;
  48723. ed.y = evt.clientY;
  48724. var direction = _this.pinchInwards ? 1 : -1;
  48725. var distX = pointA.x - pointB.x;
  48726. var distY = pointA.y - pointB.y;
  48727. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48728. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48729. if (previousPinchSquaredDistance === 0) {
  48730. initialDistance = pinchDistance;
  48731. previousPinchSquaredDistance = pinchSquaredDistance;
  48732. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48733. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48734. return;
  48735. }
  48736. if (_this.multiTouchPanAndZoom) {
  48737. if (_this.pinchDeltaPercentage) {
  48738. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48739. }
  48740. else {
  48741. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48742. (_this.pinchPrecision *
  48743. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48744. direction);
  48745. }
  48746. if (_this.panningSensibility !== 0) {
  48747. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48748. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48749. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48750. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48751. previousMultiTouchPanPosition.x = pointersCenterX;
  48752. previousMultiTouchPanPosition.y = pointersCenterY;
  48753. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48754. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48755. }
  48756. }
  48757. else {
  48758. twoFingerActivityCount++;
  48759. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48760. if (_this.pinchDeltaPercentage) {
  48761. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48762. }
  48763. else {
  48764. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48765. (_this.pinchPrecision *
  48766. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48767. direction);
  48768. }
  48769. previousMultiTouchPanPosition.isPaning = false;
  48770. previousMultiTouchPanPosition.isPinching = true;
  48771. }
  48772. else {
  48773. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48774. if (!previousMultiTouchPanPosition.isPaning) {
  48775. previousMultiTouchPanPosition.isPaning = true;
  48776. previousMultiTouchPanPosition.isPinching = false;
  48777. previousMultiTouchPanPosition.x = ed.x;
  48778. previousMultiTouchPanPosition.y = ed.y;
  48779. return;
  48780. }
  48781. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48782. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48783. }
  48784. }
  48785. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48786. previousMultiTouchPanPosition.x = ed.x;
  48787. previousMultiTouchPanPosition.y = ed.y;
  48788. }
  48789. }
  48790. previousPinchSquaredDistance = pinchSquaredDistance;
  48791. }
  48792. }
  48793. };
  48794. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48795. this._onContextMenu = function (evt) {
  48796. evt.preventDefault();
  48797. };
  48798. if (!this.camera._useCtrlForPanning) {
  48799. element.addEventListener("contextmenu", this._onContextMenu, false);
  48800. }
  48801. this._onLostFocus = function () {
  48802. //this._keys = [];
  48803. pointA = pointB = null;
  48804. previousPinchSquaredDistance = 0;
  48805. previousMultiTouchPanPosition.isPaning = false;
  48806. previousMultiTouchPanPosition.isPinching = false;
  48807. twoFingerActivityCount = 0;
  48808. cacheSoloPointer = null;
  48809. initialDistance = 0;
  48810. };
  48811. this._onMouseMove = function (evt) {
  48812. if (!engine.isPointerLock) {
  48813. return;
  48814. }
  48815. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48816. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48817. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48818. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48819. if (!noPreventDefault) {
  48820. evt.preventDefault();
  48821. }
  48822. };
  48823. this._onGestureStart = function (e) {
  48824. if (window.MSGesture === undefined) {
  48825. return;
  48826. }
  48827. if (!_this._MSGestureHandler) {
  48828. _this._MSGestureHandler = new MSGesture();
  48829. _this._MSGestureHandler.target = element;
  48830. }
  48831. _this._MSGestureHandler.addPointer(e.pointerId);
  48832. };
  48833. this._onGesture = function (e) {
  48834. _this.camera.radius *= e.scale;
  48835. if (e.preventDefault) {
  48836. if (!noPreventDefault) {
  48837. e.stopPropagation();
  48838. e.preventDefault();
  48839. }
  48840. }
  48841. };
  48842. element.addEventListener("mousemove", this._onMouseMove, false);
  48843. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48844. element.addEventListener("MSGestureChange", this._onGesture, false);
  48845. BABYLON.Tools.RegisterTopRootEvents([
  48846. { name: "blur", handler: this._onLostFocus }
  48847. ]);
  48848. };
  48849. /**
  48850. * Detach the current controls from the specified dom element.
  48851. * @param element Defines the element to stop listening the inputs from
  48852. */
  48853. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48854. if (this._onLostFocus) {
  48855. BABYLON.Tools.UnregisterTopRootEvents([
  48856. { name: "blur", handler: this._onLostFocus }
  48857. ]);
  48858. }
  48859. if (element && this._observer) {
  48860. this.camera.getScene().onPointerObservable.remove(this._observer);
  48861. this._observer = null;
  48862. if (this._onContextMenu) {
  48863. element.removeEventListener("contextmenu", this._onContextMenu);
  48864. }
  48865. if (this._onMouseMove) {
  48866. element.removeEventListener("mousemove", this._onMouseMove);
  48867. }
  48868. if (this._onGestureStart) {
  48869. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48870. }
  48871. if (this._onGesture) {
  48872. element.removeEventListener("MSGestureChange", this._onGesture);
  48873. }
  48874. this._isPanClick = false;
  48875. this.pinchInwards = true;
  48876. this._onMouseMove = null;
  48877. this._onGestureStart = null;
  48878. this._onGesture = null;
  48879. this._MSGestureHandler = null;
  48880. this._onLostFocus = null;
  48881. this._onContextMenu = null;
  48882. }
  48883. };
  48884. /**
  48885. * Gets the class name of the current intput.
  48886. * @returns the class name
  48887. */
  48888. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48889. return "ArcRotateCameraPointersInput";
  48890. };
  48891. /**
  48892. * Get the friendly name associated with the input class.
  48893. * @returns the input friendly name
  48894. */
  48895. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48896. return "pointers";
  48897. };
  48898. __decorate([
  48899. BABYLON.serialize()
  48900. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48901. __decorate([
  48902. BABYLON.serialize()
  48903. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48904. __decorate([
  48905. BABYLON.serialize()
  48906. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48907. __decorate([
  48908. BABYLON.serialize()
  48909. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48910. __decorate([
  48911. BABYLON.serialize()
  48912. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48913. __decorate([
  48914. BABYLON.serialize()
  48915. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48916. __decorate([
  48917. BABYLON.serialize()
  48918. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48919. __decorate([
  48920. BABYLON.serialize()
  48921. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48922. return ArcRotateCameraPointersInput;
  48923. }());
  48924. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48925. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48926. })(BABYLON || (BABYLON = {}));
  48927. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48928. var BABYLON;
  48929. (function (BABYLON) {
  48930. /**
  48931. * Default Inputs manager for the ArcRotateCamera.
  48932. * It groups all the default supported inputs for ease of use.
  48933. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48934. */
  48935. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48936. __extends(ArcRotateCameraInputsManager, _super);
  48937. /**
  48938. * Instantiates a new ArcRotateCameraInputsManager.
  48939. * @param camera Defines the camera the inputs belong to
  48940. */
  48941. function ArcRotateCameraInputsManager(camera) {
  48942. return _super.call(this, camera) || this;
  48943. }
  48944. /**
  48945. * Add mouse wheel input support to the input manager.
  48946. * @returns the current input manager
  48947. */
  48948. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48949. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48950. return this;
  48951. };
  48952. /**
  48953. * Add pointers input support to the input manager.
  48954. * @returns the current input manager
  48955. */
  48956. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48957. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48958. return this;
  48959. };
  48960. /**
  48961. * Add keyboard input support to the input manager.
  48962. * @returns the current input manager
  48963. */
  48964. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48965. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48966. return this;
  48967. };
  48968. /**
  48969. * Add orientation input support to the input manager.
  48970. * @returns the current input manager
  48971. */
  48972. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48973. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48974. return this;
  48975. };
  48976. return ArcRotateCameraInputsManager;
  48977. }(BABYLON.CameraInputsManager));
  48978. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48979. })(BABYLON || (BABYLON = {}));
  48980. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48981. var BABYLON;
  48982. (function (BABYLON) {
  48983. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48984. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48985. });
  48986. /**
  48987. * This represents an orbital type of camera.
  48988. *
  48989. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48990. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48991. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48992. */
  48993. var ArcRotateCamera = /** @class */ (function (_super) {
  48994. __extends(ArcRotateCamera, _super);
  48995. /**
  48996. * Instantiates a new ArcRotateCamera in a given scene
  48997. * @param name Defines the name of the camera
  48998. * @param alpha Defines the camera rotation along the logitudinal axis
  48999. * @param beta Defines the camera rotation along the latitudinal axis
  49000. * @param radius Defines the camera distance from its target
  49001. * @param target Defines the camera target
  49002. * @param scene Defines the scene the camera belongs to
  49003. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49004. */
  49005. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49006. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49007. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49008. /**
  49009. * Current inertia value on the longitudinal axis.
  49010. * The bigger this number the longer it will take for the camera to stop.
  49011. */
  49012. _this.inertialAlphaOffset = 0;
  49013. /**
  49014. * Current inertia value on the latitudinal axis.
  49015. * The bigger this number the longer it will take for the camera to stop.
  49016. */
  49017. _this.inertialBetaOffset = 0;
  49018. /**
  49019. * Current inertia value on the radius axis.
  49020. * The bigger this number the longer it will take for the camera to stop.
  49021. */
  49022. _this.inertialRadiusOffset = 0;
  49023. /**
  49024. * Minimum allowed angle on the longitudinal axis.
  49025. * This can help limiting how the Camera is able to move in the scene.
  49026. */
  49027. _this.lowerAlphaLimit = null;
  49028. /**
  49029. * Maximum allowed angle on the longitudinal axis.
  49030. * This can help limiting how the Camera is able to move in the scene.
  49031. */
  49032. _this.upperAlphaLimit = null;
  49033. /**
  49034. * Minimum allowed angle on the latitudinal axis.
  49035. * This can help limiting how the Camera is able to move in the scene.
  49036. */
  49037. _this.lowerBetaLimit = 0.01;
  49038. /**
  49039. * Maximum allowed angle on the latitudinal axis.
  49040. * This can help limiting how the Camera is able to move in the scene.
  49041. */
  49042. _this.upperBetaLimit = Math.PI;
  49043. /**
  49044. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49045. * This can help limiting how the Camera is able to move in the scene.
  49046. */
  49047. _this.lowerRadiusLimit = null;
  49048. /**
  49049. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49050. * This can help limiting how the Camera is able to move in the scene.
  49051. */
  49052. _this.upperRadiusLimit = null;
  49053. /**
  49054. * Defines the current inertia value used during panning of the camera along the X axis.
  49055. */
  49056. _this.inertialPanningX = 0;
  49057. /**
  49058. * Defines the current inertia value used during panning of the camera along the Y axis.
  49059. */
  49060. _this.inertialPanningY = 0;
  49061. /**
  49062. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49063. * Basically if your fingers moves away from more than this distance you will be considered
  49064. * in pinch mode.
  49065. */
  49066. _this.pinchToPanMaxDistance = 20;
  49067. /**
  49068. * Defines the maximum distance the camera can pan.
  49069. * This could help keeping the cammera always in your scene.
  49070. */
  49071. _this.panningDistanceLimit = null;
  49072. /**
  49073. * Defines the target of the camera before paning.
  49074. */
  49075. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49076. /**
  49077. * Defines the value of the inertia used during panning.
  49078. * 0 would mean stop inertia and one would mean no decelleration at all.
  49079. */
  49080. _this.panningInertia = 0.9;
  49081. //-- end properties for backward compatibility for inputs
  49082. /**
  49083. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49084. */
  49085. _this.zoomOnFactor = 1;
  49086. /**
  49087. * Defines a screen offset for the camera position.
  49088. */
  49089. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49090. /**
  49091. * Allows the camera to be completely reversed.
  49092. * If false the camera can not arrive upside down.
  49093. */
  49094. _this.allowUpsideDown = true;
  49095. /**
  49096. * Define if double tap/click is used to restore the previously saved state of the camera.
  49097. */
  49098. _this.useInputToRestoreState = true;
  49099. /** @hidden */
  49100. _this._viewMatrix = new BABYLON.Matrix();
  49101. /**
  49102. * Defines the allowed panning axis.
  49103. */
  49104. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49105. /**
  49106. * Observable triggered when the mesh target has been changed on the camera.
  49107. */
  49108. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49109. /**
  49110. * Defines whether the camera should check collision with the objects oh the scene.
  49111. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49112. */
  49113. _this.checkCollisions = false;
  49114. /**
  49115. * Defines the collision radius of the camera.
  49116. * This simulates a sphere around the camera.
  49117. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49118. */
  49119. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49120. _this._previousPosition = BABYLON.Vector3.Zero();
  49121. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49122. _this._newPosition = BABYLON.Vector3.Zero();
  49123. _this._computationVector = BABYLON.Vector3.Zero();
  49124. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49125. if (collidedMesh === void 0) { collidedMesh = null; }
  49126. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49127. newPosition.multiplyInPlace(_this._collider._radius);
  49128. }
  49129. if (!collidedMesh) {
  49130. _this._previousPosition.copyFrom(_this.position);
  49131. }
  49132. else {
  49133. _this.setPosition(newPosition);
  49134. if (_this.onCollide) {
  49135. _this.onCollide(collidedMesh);
  49136. }
  49137. }
  49138. // Recompute because of constraints
  49139. var cosa = Math.cos(_this.alpha);
  49140. var sina = Math.sin(_this.alpha);
  49141. var cosb = Math.cos(_this.beta);
  49142. var sinb = Math.sin(_this.beta);
  49143. if (sinb === 0) {
  49144. sinb = 0.0001;
  49145. }
  49146. var target = _this._getTargetPosition();
  49147. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49148. target.addToRef(_this._computationVector, _this._newPosition);
  49149. _this.position.copyFrom(_this._newPosition);
  49150. var up = _this.upVector;
  49151. if (_this.allowUpsideDown && _this.beta < 0) {
  49152. up = up.clone();
  49153. up = up.negate();
  49154. }
  49155. _this._computeViewMatrix(_this.position, target, up);
  49156. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49157. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49158. _this._collisionTriggered = false;
  49159. };
  49160. _this._target = BABYLON.Vector3.Zero();
  49161. if (target) {
  49162. _this.setTarget(target);
  49163. }
  49164. _this.alpha = alpha;
  49165. _this.beta = beta;
  49166. _this.radius = radius;
  49167. _this.getViewMatrix();
  49168. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49169. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49170. return _this;
  49171. }
  49172. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49173. /**
  49174. * Defines the target point of the camera.
  49175. * The camera looks towards it form the radius distance.
  49176. */
  49177. get: function () {
  49178. return this._target;
  49179. },
  49180. set: function (value) {
  49181. this.setTarget(value);
  49182. },
  49183. enumerable: true,
  49184. configurable: true
  49185. });
  49186. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49187. //-- begin properties for backward compatibility for inputs
  49188. /**
  49189. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49190. */
  49191. get: function () {
  49192. var pointers = this.inputs.attached["pointers"];
  49193. if (pointers)
  49194. return pointers.angularSensibilityX;
  49195. return 0;
  49196. },
  49197. set: function (value) {
  49198. var pointers = this.inputs.attached["pointers"];
  49199. if (pointers) {
  49200. pointers.angularSensibilityX = value;
  49201. }
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49207. /**
  49208. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49209. */
  49210. get: function () {
  49211. var pointers = this.inputs.attached["pointers"];
  49212. if (pointers)
  49213. return pointers.angularSensibilityY;
  49214. return 0;
  49215. },
  49216. set: function (value) {
  49217. var pointers = this.inputs.attached["pointers"];
  49218. if (pointers) {
  49219. pointers.angularSensibilityY = value;
  49220. }
  49221. },
  49222. enumerable: true,
  49223. configurable: true
  49224. });
  49225. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49226. /**
  49227. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49228. */
  49229. get: function () {
  49230. var pointers = this.inputs.attached["pointers"];
  49231. if (pointers)
  49232. return pointers.pinchPrecision;
  49233. return 0;
  49234. },
  49235. set: function (value) {
  49236. var pointers = this.inputs.attached["pointers"];
  49237. if (pointers) {
  49238. pointers.pinchPrecision = value;
  49239. }
  49240. },
  49241. enumerable: true,
  49242. configurable: true
  49243. });
  49244. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49245. /**
  49246. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49247. * It will be used instead of pinchDeltaPrecision if different from 0.
  49248. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49249. */
  49250. get: function () {
  49251. var pointers = this.inputs.attached["pointers"];
  49252. if (pointers)
  49253. return pointers.pinchDeltaPercentage;
  49254. return 0;
  49255. },
  49256. set: function (value) {
  49257. var pointers = this.inputs.attached["pointers"];
  49258. if (pointers) {
  49259. pointers.pinchDeltaPercentage = value;
  49260. }
  49261. },
  49262. enumerable: true,
  49263. configurable: true
  49264. });
  49265. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49266. /**
  49267. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49268. */
  49269. get: function () {
  49270. var pointers = this.inputs.attached["pointers"];
  49271. if (pointers)
  49272. return pointers.panningSensibility;
  49273. return 0;
  49274. },
  49275. set: function (value) {
  49276. var pointers = this.inputs.attached["pointers"];
  49277. if (pointers) {
  49278. pointers.panningSensibility = value;
  49279. }
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49285. /**
  49286. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49287. */
  49288. get: function () {
  49289. var keyboard = this.inputs.attached["keyboard"];
  49290. if (keyboard)
  49291. return keyboard.keysUp;
  49292. return [];
  49293. },
  49294. set: function (value) {
  49295. var keyboard = this.inputs.attached["keyboard"];
  49296. if (keyboard)
  49297. keyboard.keysUp = value;
  49298. },
  49299. enumerable: true,
  49300. configurable: true
  49301. });
  49302. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49303. /**
  49304. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49305. */
  49306. get: function () {
  49307. var keyboard = this.inputs.attached["keyboard"];
  49308. if (keyboard)
  49309. return keyboard.keysDown;
  49310. return [];
  49311. },
  49312. set: function (value) {
  49313. var keyboard = this.inputs.attached["keyboard"];
  49314. if (keyboard)
  49315. keyboard.keysDown = value;
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49321. /**
  49322. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49323. */
  49324. get: function () {
  49325. var keyboard = this.inputs.attached["keyboard"];
  49326. if (keyboard)
  49327. return keyboard.keysLeft;
  49328. return [];
  49329. },
  49330. set: function (value) {
  49331. var keyboard = this.inputs.attached["keyboard"];
  49332. if (keyboard)
  49333. keyboard.keysLeft = value;
  49334. },
  49335. enumerable: true,
  49336. configurable: true
  49337. });
  49338. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49339. /**
  49340. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49341. */
  49342. get: function () {
  49343. var keyboard = this.inputs.attached["keyboard"];
  49344. if (keyboard)
  49345. return keyboard.keysRight;
  49346. return [];
  49347. },
  49348. set: function (value) {
  49349. var keyboard = this.inputs.attached["keyboard"];
  49350. if (keyboard)
  49351. keyboard.keysRight = value;
  49352. },
  49353. enumerable: true,
  49354. configurable: true
  49355. });
  49356. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49357. /**
  49358. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49359. */
  49360. get: function () {
  49361. var mousewheel = this.inputs.attached["mousewheel"];
  49362. if (mousewheel)
  49363. return mousewheel.wheelPrecision;
  49364. return 0;
  49365. },
  49366. set: function (value) {
  49367. var mousewheel = this.inputs.attached["mousewheel"];
  49368. if (mousewheel)
  49369. mousewheel.wheelPrecision = value;
  49370. },
  49371. enumerable: true,
  49372. configurable: true
  49373. });
  49374. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49375. /**
  49376. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49377. * It will be used instead of pinchDeltaPrecision if different from 0.
  49378. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49379. */
  49380. get: function () {
  49381. var mousewheel = this.inputs.attached["mousewheel"];
  49382. if (mousewheel)
  49383. return mousewheel.wheelDeltaPercentage;
  49384. return 0;
  49385. },
  49386. set: function (value) {
  49387. var mousewheel = this.inputs.attached["mousewheel"];
  49388. if (mousewheel)
  49389. mousewheel.wheelDeltaPercentage = value;
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49395. /**
  49396. * Gets the bouncing behavior of the camera if it has been enabled.
  49397. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49398. */
  49399. get: function () {
  49400. return this._bouncingBehavior;
  49401. },
  49402. enumerable: true,
  49403. configurable: true
  49404. });
  49405. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49406. /**
  49407. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49408. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49409. */
  49410. get: function () {
  49411. return this._bouncingBehavior != null;
  49412. },
  49413. set: function (value) {
  49414. if (value === this.useBouncingBehavior) {
  49415. return;
  49416. }
  49417. if (value) {
  49418. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49419. this.addBehavior(this._bouncingBehavior);
  49420. }
  49421. else if (this._bouncingBehavior) {
  49422. this.removeBehavior(this._bouncingBehavior);
  49423. this._bouncingBehavior = null;
  49424. }
  49425. },
  49426. enumerable: true,
  49427. configurable: true
  49428. });
  49429. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49430. /**
  49431. * Gets the framing behavior of the camera if it has been enabled.
  49432. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49433. */
  49434. get: function () {
  49435. return this._framingBehavior;
  49436. },
  49437. enumerable: true,
  49438. configurable: true
  49439. });
  49440. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49441. /**
  49442. * Defines if the framing behavior of the camera is enabled on the camera.
  49443. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49444. */
  49445. get: function () {
  49446. return this._framingBehavior != null;
  49447. },
  49448. set: function (value) {
  49449. if (value === this.useFramingBehavior) {
  49450. return;
  49451. }
  49452. if (value) {
  49453. this._framingBehavior = new BABYLON.FramingBehavior();
  49454. this.addBehavior(this._framingBehavior);
  49455. }
  49456. else if (this._framingBehavior) {
  49457. this.removeBehavior(this._framingBehavior);
  49458. this._framingBehavior = null;
  49459. }
  49460. },
  49461. enumerable: true,
  49462. configurable: true
  49463. });
  49464. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49465. /**
  49466. * Gets the auto rotation behavior of the camera if it has been enabled.
  49467. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49468. */
  49469. get: function () {
  49470. return this._autoRotationBehavior;
  49471. },
  49472. enumerable: true,
  49473. configurable: true
  49474. });
  49475. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49476. /**
  49477. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49478. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49479. */
  49480. get: function () {
  49481. return this._autoRotationBehavior != null;
  49482. },
  49483. set: function (value) {
  49484. if (value === this.useAutoRotationBehavior) {
  49485. return;
  49486. }
  49487. if (value) {
  49488. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49489. this.addBehavior(this._autoRotationBehavior);
  49490. }
  49491. else if (this._autoRotationBehavior) {
  49492. this.removeBehavior(this._autoRotationBehavior);
  49493. this._autoRotationBehavior = null;
  49494. }
  49495. },
  49496. enumerable: true,
  49497. configurable: true
  49498. });
  49499. // Cache
  49500. /** @hidden */
  49501. ArcRotateCamera.prototype._initCache = function () {
  49502. _super.prototype._initCache.call(this);
  49503. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49504. this._cache.alpha = undefined;
  49505. this._cache.beta = undefined;
  49506. this._cache.radius = undefined;
  49507. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49508. };
  49509. /** @hidden */
  49510. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49511. if (!ignoreParentClass) {
  49512. _super.prototype._updateCache.call(this);
  49513. }
  49514. this._cache._target.copyFrom(this._getTargetPosition());
  49515. this._cache.alpha = this.alpha;
  49516. this._cache.beta = this.beta;
  49517. this._cache.radius = this.radius;
  49518. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49519. };
  49520. ArcRotateCamera.prototype._getTargetPosition = function () {
  49521. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49522. var pos = this._targetHost.getAbsolutePosition();
  49523. if (this._targetBoundingCenter) {
  49524. pos.addToRef(this._targetBoundingCenter, this._target);
  49525. }
  49526. else {
  49527. this._target.copyFrom(pos);
  49528. }
  49529. }
  49530. var lockedTargetPosition = this._getLockedTargetPosition();
  49531. if (lockedTargetPosition) {
  49532. return lockedTargetPosition;
  49533. }
  49534. return this._target;
  49535. };
  49536. /**
  49537. * Stores the current state of the camera (alpha, beta, radius and target)
  49538. * @returns the camera itself
  49539. */
  49540. ArcRotateCamera.prototype.storeState = function () {
  49541. this._storedAlpha = this.alpha;
  49542. this._storedBeta = this.beta;
  49543. this._storedRadius = this.radius;
  49544. this._storedTarget = this._getTargetPosition().clone();
  49545. return _super.prototype.storeState.call(this);
  49546. };
  49547. /**
  49548. * @hidden
  49549. * Restored camera state. You must call storeState() first
  49550. */
  49551. ArcRotateCamera.prototype._restoreStateValues = function () {
  49552. if (!_super.prototype._restoreStateValues.call(this)) {
  49553. return false;
  49554. }
  49555. this.alpha = this._storedAlpha;
  49556. this.beta = this._storedBeta;
  49557. this.radius = this._storedRadius;
  49558. this.setTarget(this._storedTarget.clone());
  49559. this.inertialAlphaOffset = 0;
  49560. this.inertialBetaOffset = 0;
  49561. this.inertialRadiusOffset = 0;
  49562. this.inertialPanningX = 0;
  49563. this.inertialPanningY = 0;
  49564. return true;
  49565. };
  49566. // Synchronized
  49567. /** @hidden */
  49568. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49569. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49570. return false;
  49571. return this._cache._target.equals(this._getTargetPosition())
  49572. && this._cache.alpha === this.alpha
  49573. && this._cache.beta === this.beta
  49574. && this._cache.radius === this.radius
  49575. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49576. };
  49577. /**
  49578. * Attached controls to the current camera.
  49579. * @param element Defines the element the controls should be listened from
  49580. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49581. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49582. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49583. */
  49584. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49585. var _this = this;
  49586. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49587. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49588. this._useCtrlForPanning = useCtrlForPanning;
  49589. this._panningMouseButton = panningMouseButton;
  49590. this.inputs.attachElement(element, noPreventDefault);
  49591. this._reset = function () {
  49592. _this.inertialAlphaOffset = 0;
  49593. _this.inertialBetaOffset = 0;
  49594. _this.inertialRadiusOffset = 0;
  49595. _this.inertialPanningX = 0;
  49596. _this.inertialPanningY = 0;
  49597. };
  49598. };
  49599. /**
  49600. * Detach the current controls from the camera.
  49601. * The camera will stop reacting to inputs.
  49602. * @param element Defines the element to stop listening the inputs from
  49603. */
  49604. ArcRotateCamera.prototype.detachControl = function (element) {
  49605. this.inputs.detachElement(element);
  49606. if (this._reset) {
  49607. this._reset();
  49608. }
  49609. };
  49610. /** @hidden */
  49611. ArcRotateCamera.prototype._checkInputs = function () {
  49612. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49613. if (this._collisionTriggered) {
  49614. return;
  49615. }
  49616. this.inputs.checkInputs();
  49617. // Inertia
  49618. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49619. var inertialAlphaOffset = this.inertialAlphaOffset;
  49620. if (this.beta <= 0)
  49621. inertialAlphaOffset *= -1;
  49622. if (this.getScene().useRightHandedSystem)
  49623. inertialAlphaOffset *= -1;
  49624. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49625. inertialAlphaOffset *= -1;
  49626. this.alpha += inertialAlphaOffset;
  49627. this.beta += this.inertialBetaOffset;
  49628. this.radius -= this.inertialRadiusOffset;
  49629. this.inertialAlphaOffset *= this.inertia;
  49630. this.inertialBetaOffset *= this.inertia;
  49631. this.inertialRadiusOffset *= this.inertia;
  49632. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49633. this.inertialAlphaOffset = 0;
  49634. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49635. this.inertialBetaOffset = 0;
  49636. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49637. this.inertialRadiusOffset = 0;
  49638. }
  49639. // Panning inertia
  49640. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49641. if (!this._localDirection) {
  49642. this._localDirection = BABYLON.Vector3.Zero();
  49643. this._transformedDirection = BABYLON.Vector3.Zero();
  49644. }
  49645. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49646. this._localDirection.multiplyInPlace(this.panningAxis);
  49647. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49648. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49649. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49650. if (!this.panningAxis.y) {
  49651. this._transformedDirection.y = 0;
  49652. }
  49653. if (!this._targetHost) {
  49654. if (this.panningDistanceLimit) {
  49655. this._transformedDirection.addInPlace(this._target);
  49656. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49657. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49658. this._target.copyFrom(this._transformedDirection);
  49659. }
  49660. }
  49661. else {
  49662. this._target.addInPlace(this._transformedDirection);
  49663. }
  49664. }
  49665. this.inertialPanningX *= this.panningInertia;
  49666. this.inertialPanningY *= this.panningInertia;
  49667. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49668. this.inertialPanningX = 0;
  49669. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49670. this.inertialPanningY = 0;
  49671. }
  49672. // Limits
  49673. this._checkLimits();
  49674. _super.prototype._checkInputs.call(this);
  49675. };
  49676. ArcRotateCamera.prototype._checkLimits = function () {
  49677. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49678. if (this.allowUpsideDown && this.beta > Math.PI) {
  49679. this.beta = this.beta - (2 * Math.PI);
  49680. }
  49681. }
  49682. else {
  49683. if (this.beta < this.lowerBetaLimit) {
  49684. this.beta = this.lowerBetaLimit;
  49685. }
  49686. }
  49687. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49688. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49689. this.beta = this.beta + (2 * Math.PI);
  49690. }
  49691. }
  49692. else {
  49693. if (this.beta > this.upperBetaLimit) {
  49694. this.beta = this.upperBetaLimit;
  49695. }
  49696. }
  49697. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49698. this.alpha = this.lowerAlphaLimit;
  49699. }
  49700. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49701. this.alpha = this.upperAlphaLimit;
  49702. }
  49703. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49704. this.radius = this.lowerRadiusLimit;
  49705. }
  49706. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49707. this.radius = this.upperRadiusLimit;
  49708. }
  49709. };
  49710. /**
  49711. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49712. */
  49713. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49714. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49715. this.radius = this._computationVector.length();
  49716. if (this.radius === 0) {
  49717. this.radius = 0.0001; // Just to avoid division by zero
  49718. }
  49719. // Alpha
  49720. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49721. if (this._computationVector.z < 0) {
  49722. this.alpha = 2 * Math.PI - this.alpha;
  49723. }
  49724. // Beta
  49725. this.beta = Math.acos(this._computationVector.y / this.radius);
  49726. this._checkLimits();
  49727. };
  49728. /**
  49729. * Use a position to define the current camera related information like aplha, beta and radius
  49730. * @param position Defines the position to set the camera at
  49731. */
  49732. ArcRotateCamera.prototype.setPosition = function (position) {
  49733. if (this.position.equals(position)) {
  49734. return;
  49735. }
  49736. this.position.copyFrom(position);
  49737. this.rebuildAnglesAndRadius();
  49738. };
  49739. /**
  49740. * Defines the target the camera should look at.
  49741. * This will automatically adapt alpha beta and radius to fit within the new target.
  49742. * @param target Defines the new target as a Vector or a mesh
  49743. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49744. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49745. */
  49746. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49747. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49748. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49749. if (target.getBoundingInfo) {
  49750. if (toBoundingCenter) {
  49751. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49752. }
  49753. else {
  49754. this._targetBoundingCenter = null;
  49755. }
  49756. this._targetHost = target;
  49757. this._target = this._getTargetPosition();
  49758. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49759. }
  49760. else {
  49761. var newTarget = target;
  49762. var currentTarget = this._getTargetPosition();
  49763. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49764. return;
  49765. }
  49766. this._targetHost = null;
  49767. this._target = newTarget;
  49768. this._targetBoundingCenter = null;
  49769. this.onMeshTargetChangedObservable.notifyObservers(null);
  49770. }
  49771. this.rebuildAnglesAndRadius();
  49772. };
  49773. /** @hidden */
  49774. ArcRotateCamera.prototype._getViewMatrix = function () {
  49775. // Compute
  49776. var cosa = Math.cos(this.alpha);
  49777. var sina = Math.sin(this.alpha);
  49778. var cosb = Math.cos(this.beta);
  49779. var sinb = Math.sin(this.beta);
  49780. if (sinb === 0) {
  49781. sinb = 0.0001;
  49782. }
  49783. var target = this._getTargetPosition();
  49784. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49785. target.addToRef(this._computationVector, this._newPosition);
  49786. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49787. if (!this._collider) {
  49788. this._collider = new BABYLON.Collider();
  49789. }
  49790. this._collider._radius = this.collisionRadius;
  49791. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49792. this._collisionTriggered = true;
  49793. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49794. }
  49795. else {
  49796. this.position.copyFrom(this._newPosition);
  49797. var up = this.upVector;
  49798. if (this.allowUpsideDown && sinb < 0) {
  49799. up = up.clone();
  49800. up = up.negate();
  49801. }
  49802. this._computeViewMatrix(this.position, target, up);
  49803. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49804. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49805. }
  49806. this._currentTarget = target;
  49807. return this._viewMatrix;
  49808. };
  49809. /**
  49810. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49811. * @param meshes Defines the mesh to zoom on
  49812. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49813. */
  49814. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49815. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49816. meshes = meshes || this.getScene().meshes;
  49817. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49818. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49819. this.radius = distance * this.zoomOnFactor;
  49820. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49821. };
  49822. /**
  49823. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49824. * The target will be changed but the radius
  49825. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49826. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49827. */
  49828. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49829. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49830. var meshesOrMinMaxVector;
  49831. var distance;
  49832. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49833. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49834. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49835. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49836. }
  49837. else { //minMaxVector and distance
  49838. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49839. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49840. distance = minMaxVectorAndDistance.distance;
  49841. }
  49842. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49843. if (!doNotUpdateMaxZ) {
  49844. this.maxZ = distance * 2;
  49845. }
  49846. };
  49847. /**
  49848. * @override
  49849. * Override Camera.createRigCamera
  49850. */
  49851. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49852. var alphaShift = 0;
  49853. switch (this.cameraRigMode) {
  49854. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49855. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49856. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49857. case BABYLON.Camera.RIG_MODE_VR:
  49858. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49859. break;
  49860. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49861. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49862. break;
  49863. }
  49864. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49865. rigCam._cameraRigParams = {};
  49866. return rigCam;
  49867. };
  49868. /**
  49869. * @hidden
  49870. * @override
  49871. * Override Camera._updateRigCameras
  49872. */
  49873. ArcRotateCamera.prototype._updateRigCameras = function () {
  49874. var camLeft = this._rigCameras[0];
  49875. var camRight = this._rigCameras[1];
  49876. camLeft.beta = camRight.beta = this.beta;
  49877. camLeft.radius = camRight.radius = this.radius;
  49878. switch (this.cameraRigMode) {
  49879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49880. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49881. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49882. case BABYLON.Camera.RIG_MODE_VR:
  49883. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49884. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49885. break;
  49886. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49887. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49888. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49889. break;
  49890. }
  49891. _super.prototype._updateRigCameras.call(this);
  49892. };
  49893. /**
  49894. * Destroy the camera and release the current resources hold by it.
  49895. */
  49896. ArcRotateCamera.prototype.dispose = function () {
  49897. this.inputs.clear();
  49898. _super.prototype.dispose.call(this);
  49899. };
  49900. /**
  49901. * Gets the current object class name.
  49902. * @return the class name
  49903. */
  49904. ArcRotateCamera.prototype.getClassName = function () {
  49905. return "ArcRotateCamera";
  49906. };
  49907. __decorate([
  49908. BABYLON.serialize()
  49909. ], ArcRotateCamera.prototype, "alpha", void 0);
  49910. __decorate([
  49911. BABYLON.serialize()
  49912. ], ArcRotateCamera.prototype, "beta", void 0);
  49913. __decorate([
  49914. BABYLON.serialize()
  49915. ], ArcRotateCamera.prototype, "radius", void 0);
  49916. __decorate([
  49917. BABYLON.serializeAsVector3("target")
  49918. ], ArcRotateCamera.prototype, "_target", void 0);
  49919. __decorate([
  49920. BABYLON.serialize()
  49921. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49922. __decorate([
  49923. BABYLON.serialize()
  49924. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49925. __decorate([
  49926. BABYLON.serialize()
  49927. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49928. __decorate([
  49929. BABYLON.serialize()
  49930. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49931. __decorate([
  49932. BABYLON.serialize()
  49933. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49934. __decorate([
  49935. BABYLON.serialize()
  49936. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49937. __decorate([
  49938. BABYLON.serialize()
  49939. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49940. __decorate([
  49941. BABYLON.serialize()
  49942. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49943. __decorate([
  49944. BABYLON.serialize()
  49945. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49946. __decorate([
  49947. BABYLON.serialize()
  49948. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49949. __decorate([
  49950. BABYLON.serialize()
  49951. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49952. __decorate([
  49953. BABYLON.serialize()
  49954. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49955. __decorate([
  49956. BABYLON.serialize()
  49957. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49958. __decorate([
  49959. BABYLON.serializeAsVector3()
  49960. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49961. __decorate([
  49962. BABYLON.serialize()
  49963. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49964. __decorate([
  49965. BABYLON.serialize()
  49966. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49967. __decorate([
  49968. BABYLON.serialize()
  49969. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49970. __decorate([
  49971. BABYLON.serialize()
  49972. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49973. __decorate([
  49974. BABYLON.serialize()
  49975. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49976. return ArcRotateCamera;
  49977. }(BABYLON.TargetCamera));
  49978. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49979. })(BABYLON || (BABYLON = {}));
  49980. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49981. var BABYLON;
  49982. (function (BABYLON) {
  49983. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49984. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49985. });
  49986. /**
  49987. * The HemisphericLight simulates the ambient environment light,
  49988. * so the passed direction is the light reflection direction, not the incoming direction.
  49989. */
  49990. var HemisphericLight = /** @class */ (function (_super) {
  49991. __extends(HemisphericLight, _super);
  49992. /**
  49993. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49994. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49995. * The HemisphericLight can't cast shadows.
  49996. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49997. * @param name The friendly name of the light
  49998. * @param direction The direction of the light reflection
  49999. * @param scene The scene the light belongs to
  50000. */
  50001. function HemisphericLight(name, direction, scene) {
  50002. var _this = _super.call(this, name, scene) || this;
  50003. /**
  50004. * The groundColor is the light in the opposite direction to the one specified during creation.
  50005. * 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.
  50006. */
  50007. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50008. _this.direction = direction || BABYLON.Vector3.Up();
  50009. return _this;
  50010. }
  50011. HemisphericLight.prototype._buildUniformLayout = function () {
  50012. this._uniformBuffer.addUniform("vLightData", 4);
  50013. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50014. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50015. this._uniformBuffer.addUniform("vLightGround", 3);
  50016. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50017. this._uniformBuffer.addUniform("depthValues", 2);
  50018. this._uniformBuffer.create();
  50019. };
  50020. /**
  50021. * Returns the string "HemisphericLight".
  50022. * @return The class name
  50023. */
  50024. HemisphericLight.prototype.getClassName = function () {
  50025. return "HemisphericLight";
  50026. };
  50027. /**
  50028. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50029. * Returns the updated direction.
  50030. * @param target The target the direction should point to
  50031. * @return The computed direction
  50032. */
  50033. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50034. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50035. return this.direction;
  50036. };
  50037. /**
  50038. * Returns the shadow generator associated to the light.
  50039. * @returns Always null for hemispheric lights because it does not support shadows.
  50040. */
  50041. HemisphericLight.prototype.getShadowGenerator = function () {
  50042. return null;
  50043. };
  50044. /**
  50045. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50046. * @param effect The effect to update
  50047. * @param lightIndex The index of the light in the effect to update
  50048. * @returns The hemispheric light
  50049. */
  50050. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50051. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50052. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50053. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50054. return this;
  50055. };
  50056. /**
  50057. * Computes the world matrix of the node
  50058. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50059. * @param useWasUpdatedFlag defines a reserved property
  50060. * @returns the world matrix
  50061. */
  50062. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50063. if (!this._worldMatrix) {
  50064. this._worldMatrix = BABYLON.Matrix.Identity();
  50065. }
  50066. return this._worldMatrix;
  50067. };
  50068. /**
  50069. * Returns the integer 3.
  50070. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50071. */
  50072. HemisphericLight.prototype.getTypeID = function () {
  50073. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50074. };
  50075. /**
  50076. * Prepares the list of defines specific to the light type.
  50077. * @param defines the list of defines
  50078. * @param lightIndex defines the index of the light for the effect
  50079. */
  50080. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50081. defines["HEMILIGHT" + lightIndex] = true;
  50082. };
  50083. __decorate([
  50084. BABYLON.serializeAsColor3()
  50085. ], HemisphericLight.prototype, "groundColor", void 0);
  50086. __decorate([
  50087. BABYLON.serializeAsVector3()
  50088. ], HemisphericLight.prototype, "direction", void 0);
  50089. return HemisphericLight;
  50090. }(BABYLON.Light));
  50091. BABYLON.HemisphericLight = HemisphericLight;
  50092. })(BABYLON || (BABYLON = {}));
  50093. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50094. var BABYLON;
  50095. (function (BABYLON) {
  50096. /**
  50097. * Base implementation IShadowLight
  50098. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50099. */
  50100. var ShadowLight = /** @class */ (function (_super) {
  50101. __extends(ShadowLight, _super);
  50102. function ShadowLight() {
  50103. var _this = _super !== null && _super.apply(this, arguments) || this;
  50104. _this._needProjectionMatrixCompute = true;
  50105. return _this;
  50106. }
  50107. ShadowLight.prototype._setPosition = function (value) {
  50108. this._position = value;
  50109. };
  50110. Object.defineProperty(ShadowLight.prototype, "position", {
  50111. /**
  50112. * Sets the position the shadow will be casted from. Also use as the light position for both
  50113. * point and spot lights.
  50114. */
  50115. get: function () {
  50116. return this._position;
  50117. },
  50118. /**
  50119. * Sets the position the shadow will be casted from. Also use as the light position for both
  50120. * point and spot lights.
  50121. */
  50122. set: function (value) {
  50123. this._setPosition(value);
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. ShadowLight.prototype._setDirection = function (value) {
  50129. this._direction = value;
  50130. };
  50131. Object.defineProperty(ShadowLight.prototype, "direction", {
  50132. /**
  50133. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50134. * Also use as the light direction on spot and directional lights.
  50135. */
  50136. get: function () {
  50137. return this._direction;
  50138. },
  50139. /**
  50140. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50141. * Also use as the light direction on spot and directional lights.
  50142. */
  50143. set: function (value) {
  50144. this._setDirection(value);
  50145. },
  50146. enumerable: true,
  50147. configurable: true
  50148. });
  50149. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50150. /**
  50151. * Gets the shadow projection clipping minimum z value.
  50152. */
  50153. get: function () {
  50154. return this._shadowMinZ;
  50155. },
  50156. /**
  50157. * Sets the shadow projection clipping minimum z value.
  50158. */
  50159. set: function (value) {
  50160. this._shadowMinZ = value;
  50161. this.forceProjectionMatrixCompute();
  50162. },
  50163. enumerable: true,
  50164. configurable: true
  50165. });
  50166. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50167. /**
  50168. * Sets the shadow projection clipping maximum z value.
  50169. */
  50170. get: function () {
  50171. return this._shadowMaxZ;
  50172. },
  50173. /**
  50174. * Gets the shadow projection clipping maximum z value.
  50175. */
  50176. set: function (value) {
  50177. this._shadowMaxZ = value;
  50178. this.forceProjectionMatrixCompute();
  50179. },
  50180. enumerable: true,
  50181. configurable: true
  50182. });
  50183. /**
  50184. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50185. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50186. */
  50187. ShadowLight.prototype.computeTransformedInformation = function () {
  50188. if (this.parent && this.parent.getWorldMatrix) {
  50189. if (!this.transformedPosition) {
  50190. this.transformedPosition = BABYLON.Vector3.Zero();
  50191. }
  50192. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50193. // In case the direction is present.
  50194. if (this.direction) {
  50195. if (!this.transformedDirection) {
  50196. this.transformedDirection = BABYLON.Vector3.Zero();
  50197. }
  50198. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50199. }
  50200. return true;
  50201. }
  50202. return false;
  50203. };
  50204. /**
  50205. * Return the depth scale used for the shadow map.
  50206. * @returns the depth scale.
  50207. */
  50208. ShadowLight.prototype.getDepthScale = function () {
  50209. return 50.0;
  50210. };
  50211. /**
  50212. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50213. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50214. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50215. */
  50216. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50217. return this.transformedDirection ? this.transformedDirection : this.direction;
  50218. };
  50219. /**
  50220. * Returns the ShadowLight absolute position in the World.
  50221. * @returns the position vector in world space
  50222. */
  50223. ShadowLight.prototype.getAbsolutePosition = function () {
  50224. return this.transformedPosition ? this.transformedPosition : this.position;
  50225. };
  50226. /**
  50227. * Sets the ShadowLight direction toward the passed target.
  50228. * @param target The point tot target in local space
  50229. * @returns the updated ShadowLight direction
  50230. */
  50231. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50232. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50233. return this.direction;
  50234. };
  50235. /**
  50236. * Returns the light rotation in euler definition.
  50237. * @returns the x y z rotation in local space.
  50238. */
  50239. ShadowLight.prototype.getRotation = function () {
  50240. this.direction.normalize();
  50241. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50242. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50243. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50244. };
  50245. /**
  50246. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50247. * @returns true if a cube texture needs to be use
  50248. */
  50249. ShadowLight.prototype.needCube = function () {
  50250. return false;
  50251. };
  50252. /**
  50253. * Detects if the projection matrix requires to be recomputed this frame.
  50254. * @returns true if it requires to be recomputed otherwise, false.
  50255. */
  50256. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50257. return this._needProjectionMatrixCompute;
  50258. };
  50259. /**
  50260. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50261. */
  50262. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50263. this._needProjectionMatrixCompute = true;
  50264. };
  50265. /** @hidden */
  50266. ShadowLight.prototype._initCache = function () {
  50267. _super.prototype._initCache.call(this);
  50268. this._cache.position = BABYLON.Vector3.Zero();
  50269. };
  50270. /** @hidden */
  50271. ShadowLight.prototype._isSynchronized = function () {
  50272. if (!this._cache.position.equals(this.position))
  50273. return false;
  50274. return true;
  50275. };
  50276. /**
  50277. * Computes the world matrix of the node
  50278. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50279. * @returns the world matrix
  50280. */
  50281. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50282. if (!force && this.isSynchronized()) {
  50283. this._currentRenderId = this.getScene().getRenderId();
  50284. return this._worldMatrix;
  50285. }
  50286. this._updateCache();
  50287. this._cache.position.copyFrom(this.position);
  50288. if (!this._worldMatrix) {
  50289. this._worldMatrix = BABYLON.Matrix.Identity();
  50290. }
  50291. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50292. if (this.parent && this.parent.getWorldMatrix) {
  50293. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50294. this._markSyncedWithParent();
  50295. }
  50296. // Cache the determinant
  50297. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50298. return this._worldMatrix;
  50299. };
  50300. /**
  50301. * Gets the minZ used for shadow according to both the scene and the light.
  50302. * @param activeCamera The camera we are returning the min for
  50303. * @returns the depth min z
  50304. */
  50305. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50306. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50307. };
  50308. /**
  50309. * Gets the maxZ used for shadow according to both the scene and the light.
  50310. * @param activeCamera The camera we are returning the max for
  50311. * @returns the depth max z
  50312. */
  50313. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50314. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50315. };
  50316. /**
  50317. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50318. * @param matrix The materix to updated with the projection information
  50319. * @param viewMatrix The transform matrix of the light
  50320. * @param renderList The list of mesh to render in the map
  50321. * @returns The current light
  50322. */
  50323. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50324. if (this.customProjectionMatrixBuilder) {
  50325. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50326. }
  50327. else {
  50328. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50329. }
  50330. return this;
  50331. };
  50332. __decorate([
  50333. BABYLON.serializeAsVector3()
  50334. ], ShadowLight.prototype, "position", null);
  50335. __decorate([
  50336. BABYLON.serializeAsVector3()
  50337. ], ShadowLight.prototype, "direction", null);
  50338. __decorate([
  50339. BABYLON.serialize()
  50340. ], ShadowLight.prototype, "shadowMinZ", null);
  50341. __decorate([
  50342. BABYLON.serialize()
  50343. ], ShadowLight.prototype, "shadowMaxZ", null);
  50344. return ShadowLight;
  50345. }(BABYLON.Light));
  50346. BABYLON.ShadowLight = ShadowLight;
  50347. })(BABYLON || (BABYLON = {}));
  50348. //# sourceMappingURL=babylon.shadowLight.js.map
  50349. var BABYLON;
  50350. (function (BABYLON) {
  50351. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50352. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50353. });
  50354. /**
  50355. * A point light is a light defined by an unique point in world space.
  50356. * The light is emitted in every direction from this point.
  50357. * A good example of a point light is a standard light bulb.
  50358. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50359. */
  50360. var PointLight = /** @class */ (function (_super) {
  50361. __extends(PointLight, _super);
  50362. /**
  50363. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50364. * A PointLight emits the light in every direction.
  50365. * It can cast shadows.
  50366. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50367. * ```javascript
  50368. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50369. * ```
  50370. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50371. * @param name The light friendly name
  50372. * @param position The position of the point light in the scene
  50373. * @param scene The scene the lights belongs to
  50374. */
  50375. function PointLight(name, position, scene) {
  50376. var _this = _super.call(this, name, scene) || this;
  50377. _this._shadowAngle = Math.PI / 2;
  50378. _this.position = position;
  50379. return _this;
  50380. }
  50381. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50382. /**
  50383. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50384. * This specifies what angle the shadow will use to be created.
  50385. *
  50386. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50387. */
  50388. get: function () {
  50389. return this._shadowAngle;
  50390. },
  50391. /**
  50392. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50393. * This specifies what angle the shadow will use to be created.
  50394. *
  50395. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50396. */
  50397. set: function (value) {
  50398. this._shadowAngle = value;
  50399. this.forceProjectionMatrixCompute();
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(PointLight.prototype, "direction", {
  50405. /**
  50406. * Gets the direction if it has been set.
  50407. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50408. */
  50409. get: function () {
  50410. return this._direction;
  50411. },
  50412. /**
  50413. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50414. */
  50415. set: function (value) {
  50416. var previousNeedCube = this.needCube();
  50417. this._direction = value;
  50418. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50419. this._shadowGenerator.recreateShadowMap();
  50420. }
  50421. },
  50422. enumerable: true,
  50423. configurable: true
  50424. });
  50425. /**
  50426. * Returns the string "PointLight"
  50427. * @returns the class name
  50428. */
  50429. PointLight.prototype.getClassName = function () {
  50430. return "PointLight";
  50431. };
  50432. /**
  50433. * Returns the integer 0.
  50434. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50435. */
  50436. PointLight.prototype.getTypeID = function () {
  50437. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50438. };
  50439. /**
  50440. * Specifies wether or not the shadowmap should be a cube texture.
  50441. * @returns true if the shadowmap needs to be a cube texture.
  50442. */
  50443. PointLight.prototype.needCube = function () {
  50444. return !this.direction;
  50445. };
  50446. /**
  50447. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50448. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50449. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50450. */
  50451. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50452. if (this.direction) {
  50453. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50454. }
  50455. else {
  50456. switch (faceIndex) {
  50457. case 0:
  50458. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50459. case 1:
  50460. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50461. case 2:
  50462. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50463. case 3:
  50464. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50465. case 4:
  50466. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50467. case 5:
  50468. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50469. }
  50470. }
  50471. return BABYLON.Vector3.Zero();
  50472. };
  50473. /**
  50474. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50475. * - fov = PI / 2
  50476. * - aspect ratio : 1.0
  50477. * - z-near and far equal to the active camera minZ and maxZ.
  50478. * Returns the PointLight.
  50479. */
  50480. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50481. var activeCamera = this.getScene().activeCamera;
  50482. if (!activeCamera) {
  50483. return;
  50484. }
  50485. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50486. };
  50487. PointLight.prototype._buildUniformLayout = function () {
  50488. this._uniformBuffer.addUniform("vLightData", 4);
  50489. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50490. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50491. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50492. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50493. this._uniformBuffer.addUniform("depthValues", 2);
  50494. this._uniformBuffer.create();
  50495. };
  50496. /**
  50497. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50498. * @param effect The effect to update
  50499. * @param lightIndex The index of the light in the effect to update
  50500. * @returns The point light
  50501. */
  50502. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50503. if (this.computeTransformedInformation()) {
  50504. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50505. }
  50506. else {
  50507. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50508. }
  50509. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50510. return this;
  50511. };
  50512. /**
  50513. * Prepares the list of defines specific to the light type.
  50514. * @param defines the list of defines
  50515. * @param lightIndex defines the index of the light for the effect
  50516. */
  50517. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50518. defines["POINTLIGHT" + lightIndex] = true;
  50519. };
  50520. __decorate([
  50521. BABYLON.serialize()
  50522. ], PointLight.prototype, "shadowAngle", null);
  50523. return PointLight;
  50524. }(BABYLON.ShadowLight));
  50525. BABYLON.PointLight = PointLight;
  50526. })(BABYLON || (BABYLON = {}));
  50527. //# sourceMappingURL=babylon.pointLight.js.map
  50528. var BABYLON;
  50529. (function (BABYLON) {
  50530. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50531. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50532. });
  50533. /**
  50534. * A directional light is defined by a direction (what a surprise!).
  50535. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50536. * 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.
  50537. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50538. */
  50539. var DirectionalLight = /** @class */ (function (_super) {
  50540. __extends(DirectionalLight, _super);
  50541. /**
  50542. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50543. * The directional light is emitted from everywhere in the given direction.
  50544. * It can cast shadows.
  50545. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50546. * @param name The friendly name of the light
  50547. * @param direction The direction of the light
  50548. * @param scene The scene the light belongs to
  50549. */
  50550. function DirectionalLight(name, direction, scene) {
  50551. var _this = _super.call(this, name, scene) || this;
  50552. _this._shadowFrustumSize = 0;
  50553. _this._shadowOrthoScale = 0.1;
  50554. /**
  50555. * Automatically compute the projection matrix to best fit (including all the casters)
  50556. * on each frame.
  50557. */
  50558. _this.autoUpdateExtends = true;
  50559. // Cache
  50560. _this._orthoLeft = Number.MAX_VALUE;
  50561. _this._orthoRight = Number.MIN_VALUE;
  50562. _this._orthoTop = Number.MIN_VALUE;
  50563. _this._orthoBottom = Number.MAX_VALUE;
  50564. _this.position = direction.scale(-1.0);
  50565. _this.direction = direction;
  50566. return _this;
  50567. }
  50568. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50569. /**
  50570. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50571. */
  50572. get: function () {
  50573. return this._shadowFrustumSize;
  50574. },
  50575. /**
  50576. * Specifies a fix frustum size for the shadow generation.
  50577. */
  50578. set: function (value) {
  50579. this._shadowFrustumSize = value;
  50580. this.forceProjectionMatrixCompute();
  50581. },
  50582. enumerable: true,
  50583. configurable: true
  50584. });
  50585. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50586. /**
  50587. * Gets the shadow projection scale against the optimal computed one.
  50588. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50589. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50590. */
  50591. get: function () {
  50592. return this._shadowOrthoScale;
  50593. },
  50594. /**
  50595. * Sets the shadow projection scale against the optimal computed one.
  50596. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50597. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50598. */
  50599. set: function (value) {
  50600. this._shadowOrthoScale = value;
  50601. this.forceProjectionMatrixCompute();
  50602. },
  50603. enumerable: true,
  50604. configurable: true
  50605. });
  50606. /**
  50607. * Returns the string "DirectionalLight".
  50608. * @return The class name
  50609. */
  50610. DirectionalLight.prototype.getClassName = function () {
  50611. return "DirectionalLight";
  50612. };
  50613. /**
  50614. * Returns the integer 1.
  50615. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50616. */
  50617. DirectionalLight.prototype.getTypeID = function () {
  50618. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50619. };
  50620. /**
  50621. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50622. * Returns the DirectionalLight Shadow projection matrix.
  50623. */
  50624. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50625. if (this.shadowFrustumSize > 0) {
  50626. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50627. }
  50628. else {
  50629. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50630. }
  50631. };
  50632. /**
  50633. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50634. * Returns the DirectionalLight Shadow projection matrix.
  50635. */
  50636. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50637. var activeCamera = this.getScene().activeCamera;
  50638. if (!activeCamera) {
  50639. return;
  50640. }
  50641. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50642. };
  50643. /**
  50644. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50645. * Returns the DirectionalLight Shadow projection matrix.
  50646. */
  50647. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50648. var activeCamera = this.getScene().activeCamera;
  50649. if (!activeCamera) {
  50650. return;
  50651. }
  50652. // Check extends
  50653. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50654. var tempVector3 = BABYLON.Vector3.Zero();
  50655. this._orthoLeft = Number.MAX_VALUE;
  50656. this._orthoRight = Number.MIN_VALUE;
  50657. this._orthoTop = Number.MIN_VALUE;
  50658. this._orthoBottom = Number.MAX_VALUE;
  50659. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50660. var mesh = renderList[meshIndex];
  50661. if (!mesh) {
  50662. continue;
  50663. }
  50664. var boundingInfo = mesh.getBoundingInfo();
  50665. var boundingBox = boundingInfo.boundingBox;
  50666. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50667. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50668. if (tempVector3.x < this._orthoLeft)
  50669. this._orthoLeft = tempVector3.x;
  50670. if (tempVector3.y < this._orthoBottom)
  50671. this._orthoBottom = tempVector3.y;
  50672. if (tempVector3.x > this._orthoRight)
  50673. this._orthoRight = tempVector3.x;
  50674. if (tempVector3.y > this._orthoTop)
  50675. this._orthoTop = tempVector3.y;
  50676. }
  50677. }
  50678. }
  50679. var xOffset = this._orthoRight - this._orthoLeft;
  50680. var yOffset = this._orthoTop - this._orthoBottom;
  50681. 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);
  50682. };
  50683. DirectionalLight.prototype._buildUniformLayout = function () {
  50684. this._uniformBuffer.addUniform("vLightData", 4);
  50685. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50686. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50687. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50688. this._uniformBuffer.addUniform("depthValues", 2);
  50689. this._uniformBuffer.create();
  50690. };
  50691. /**
  50692. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50693. * @param effect The effect to update
  50694. * @param lightIndex The index of the light in the effect to update
  50695. * @returns The directional light
  50696. */
  50697. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50698. if (this.computeTransformedInformation()) {
  50699. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50700. return this;
  50701. }
  50702. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50703. return this;
  50704. };
  50705. /**
  50706. * Gets the minZ used for shadow according to both the scene and the light.
  50707. *
  50708. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50709. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50710. * @param activeCamera The camera we are returning the min for
  50711. * @returns the depth min z
  50712. */
  50713. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50714. return 1;
  50715. };
  50716. /**
  50717. * Gets the maxZ used for shadow according to both the scene and the light.
  50718. *
  50719. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50720. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50721. * @param activeCamera The camera we are returning the max for
  50722. * @returns the depth max z
  50723. */
  50724. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50725. return 1;
  50726. };
  50727. /**
  50728. * Prepares the list of defines specific to the light type.
  50729. * @param defines the list of defines
  50730. * @param lightIndex defines the index of the light for the effect
  50731. */
  50732. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50733. defines["DIRLIGHT" + lightIndex] = true;
  50734. };
  50735. __decorate([
  50736. BABYLON.serialize()
  50737. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50738. __decorate([
  50739. BABYLON.serialize()
  50740. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50741. __decorate([
  50742. BABYLON.serialize()
  50743. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50744. return DirectionalLight;
  50745. }(BABYLON.ShadowLight));
  50746. BABYLON.DirectionalLight = DirectionalLight;
  50747. })(BABYLON || (BABYLON = {}));
  50748. //# sourceMappingURL=babylon.directionalLight.js.map
  50749. var BABYLON;
  50750. (function (BABYLON) {
  50751. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50752. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50753. });
  50754. /**
  50755. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50756. * These values define a cone of light starting from the position, emitting toward the direction.
  50757. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50758. * and the exponent defines the speed of the decay of the light with distance (reach).
  50759. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50760. */
  50761. var SpotLight = /** @class */ (function (_super) {
  50762. __extends(SpotLight, _super);
  50763. /**
  50764. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50765. * It can cast shadows.
  50766. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50767. * @param name The light friendly name
  50768. * @param position The position of the spot light in the scene
  50769. * @param direction The direction of the light in the scene
  50770. * @param angle The cone angle of the light in Radians
  50771. * @param exponent The light decay speed with the distance from the emission spot
  50772. * @param scene The scene the lights belongs to
  50773. */
  50774. function SpotLight(name, position, direction, angle, exponent, scene) {
  50775. var _this = _super.call(this, name, scene) || this;
  50776. _this._innerAngle = 0;
  50777. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50778. _this._projectionTextureLightNear = 1e-6;
  50779. _this._projectionTextureLightFar = 1000.0;
  50780. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50781. _this._projectionTextureViewLightDirty = true;
  50782. _this._projectionTextureProjectionLightDirty = true;
  50783. _this._projectionTextureDirty = true;
  50784. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50785. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50786. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50787. _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);
  50788. _this.position = position;
  50789. _this.direction = direction;
  50790. _this.angle = angle;
  50791. _this.exponent = exponent;
  50792. return _this;
  50793. }
  50794. Object.defineProperty(SpotLight.prototype, "angle", {
  50795. /**
  50796. * Gets the cone angle of the spot light in Radians.
  50797. */
  50798. get: function () {
  50799. return this._angle;
  50800. },
  50801. /**
  50802. * Sets the cone angle of the spot light in Radians.
  50803. */
  50804. set: function (value) {
  50805. this._angle = value;
  50806. this._cosHalfAngle = Math.cos(value * 0.5);
  50807. this._projectionTextureProjectionLightDirty = true;
  50808. this.forceProjectionMatrixCompute();
  50809. this._computeAngleValues();
  50810. },
  50811. enumerable: true,
  50812. configurable: true
  50813. });
  50814. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50815. /**
  50816. * Only used in gltf falloff mode, this defines the angle where
  50817. * the directional falloff will start before cutting at angle which could be seen
  50818. * as outer angle.
  50819. */
  50820. get: function () {
  50821. return this._innerAngle;
  50822. },
  50823. /**
  50824. * Only used in gltf falloff mode, this defines the angle where
  50825. * the directional falloff will start before cutting at angle which could be seen
  50826. * as outer angle.
  50827. */
  50828. set: function (value) {
  50829. this._innerAngle = value;
  50830. this._computeAngleValues();
  50831. },
  50832. enumerable: true,
  50833. configurable: true
  50834. });
  50835. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50836. /**
  50837. * Allows scaling the angle of the light for shadow generation only.
  50838. */
  50839. get: function () {
  50840. return this._shadowAngleScale;
  50841. },
  50842. /**
  50843. * Allows scaling the angle of the light for shadow generation only.
  50844. */
  50845. set: function (value) {
  50846. this._shadowAngleScale = value;
  50847. this.forceProjectionMatrixCompute();
  50848. },
  50849. enumerable: true,
  50850. configurable: true
  50851. });
  50852. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50853. /**
  50854. * Allows reading the projecton texture
  50855. */
  50856. get: function () {
  50857. return this._projectionTextureMatrix;
  50858. },
  50859. enumerable: true,
  50860. configurable: true
  50861. });
  50862. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50863. /**
  50864. * Gets the near clip of the Spotlight for texture projection.
  50865. */
  50866. get: function () {
  50867. return this._projectionTextureLightNear;
  50868. },
  50869. /**
  50870. * Sets the near clip of the Spotlight for texture projection.
  50871. */
  50872. set: function (value) {
  50873. this._projectionTextureLightNear = value;
  50874. this._projectionTextureProjectionLightDirty = true;
  50875. },
  50876. enumerable: true,
  50877. configurable: true
  50878. });
  50879. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50880. /**
  50881. * Gets the far clip of the Spotlight for texture projection.
  50882. */
  50883. get: function () {
  50884. return this._projectionTextureLightFar;
  50885. },
  50886. /**
  50887. * Sets the far clip of the Spotlight for texture projection.
  50888. */
  50889. set: function (value) {
  50890. this._projectionTextureLightFar = value;
  50891. this._projectionTextureProjectionLightDirty = true;
  50892. },
  50893. enumerable: true,
  50894. configurable: true
  50895. });
  50896. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50897. /**
  50898. * Gets the Up vector of the Spotlight for texture projection.
  50899. */
  50900. get: function () {
  50901. return this._projectionTextureUpDirection;
  50902. },
  50903. /**
  50904. * Sets the Up vector of the Spotlight for texture projection.
  50905. */
  50906. set: function (value) {
  50907. this._projectionTextureUpDirection = value;
  50908. this._projectionTextureProjectionLightDirty = true;
  50909. },
  50910. enumerable: true,
  50911. configurable: true
  50912. });
  50913. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50914. /**
  50915. * Gets the projection texture of the light.
  50916. */
  50917. get: function () {
  50918. return this._projectionTexture;
  50919. },
  50920. /**
  50921. * Sets the projection texture of the light.
  50922. */
  50923. set: function (value) {
  50924. this._projectionTexture = value;
  50925. this._projectionTextureDirty = true;
  50926. },
  50927. enumerable: true,
  50928. configurable: true
  50929. });
  50930. /**
  50931. * Returns the string "SpotLight".
  50932. * @returns the class name
  50933. */
  50934. SpotLight.prototype.getClassName = function () {
  50935. return "SpotLight";
  50936. };
  50937. /**
  50938. * Returns the integer 2.
  50939. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50940. */
  50941. SpotLight.prototype.getTypeID = function () {
  50942. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50943. };
  50944. /**
  50945. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50946. */
  50947. SpotLight.prototype._setDirection = function (value) {
  50948. _super.prototype._setDirection.call(this, value);
  50949. this._projectionTextureViewLightDirty = true;
  50950. };
  50951. /**
  50952. * Overrides the position setter to recompute the projection texture view light Matrix.
  50953. */
  50954. SpotLight.prototype._setPosition = function (value) {
  50955. _super.prototype._setPosition.call(this, value);
  50956. this._projectionTextureViewLightDirty = true;
  50957. };
  50958. /**
  50959. * 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.
  50960. * Returns the SpotLight.
  50961. */
  50962. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50963. var activeCamera = this.getScene().activeCamera;
  50964. if (!activeCamera) {
  50965. return;
  50966. }
  50967. this._shadowAngleScale = this._shadowAngleScale || 1;
  50968. var angle = this._shadowAngleScale * this._angle;
  50969. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50970. };
  50971. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50972. this._projectionTextureViewLightDirty = false;
  50973. this._projectionTextureDirty = true;
  50974. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50975. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50976. };
  50977. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50978. this._projectionTextureProjectionLightDirty = false;
  50979. this._projectionTextureDirty = true;
  50980. var light_far = this.projectionTextureLightFar;
  50981. var light_near = this.projectionTextureLightNear;
  50982. var P = light_far / (light_far - light_near);
  50983. var Q = -P * light_near;
  50984. var S = 1.0 / Math.tan(this._angle / 2.0);
  50985. var A = 1.0;
  50986. 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);
  50987. };
  50988. /**
  50989. * Main function for light texture projection matrix computing.
  50990. */
  50991. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50992. this._projectionTextureDirty = false;
  50993. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50994. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50995. };
  50996. SpotLight.prototype._buildUniformLayout = function () {
  50997. this._uniformBuffer.addUniform("vLightData", 4);
  50998. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50999. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51000. this._uniformBuffer.addUniform("vLightDirection", 3);
  51001. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51002. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51003. this._uniformBuffer.addUniform("depthValues", 2);
  51004. this._uniformBuffer.create();
  51005. };
  51006. SpotLight.prototype._computeAngleValues = function () {
  51007. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51008. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51009. };
  51010. /**
  51011. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51012. * @param effect The effect to update
  51013. * @param lightIndex The index of the light in the effect to update
  51014. * @returns The spot light
  51015. */
  51016. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51017. var normalizeDirection;
  51018. if (this.computeTransformedInformation()) {
  51019. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51020. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51021. }
  51022. else {
  51023. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51024. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51025. }
  51026. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51027. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51028. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51029. if (this._projectionTextureViewLightDirty) {
  51030. this._computeProjectionTextureViewLightMatrix();
  51031. }
  51032. if (this._projectionTextureProjectionLightDirty) {
  51033. this._computeProjectionTextureProjectionLightMatrix();
  51034. }
  51035. if (this._projectionTextureDirty) {
  51036. this._computeProjectionTextureMatrix();
  51037. }
  51038. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51039. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51040. }
  51041. return this;
  51042. };
  51043. /**
  51044. * Disposes the light and the associated resources.
  51045. */
  51046. SpotLight.prototype.dispose = function () {
  51047. _super.prototype.dispose.call(this);
  51048. if (this._projectionTexture) {
  51049. this._projectionTexture.dispose();
  51050. }
  51051. };
  51052. /**
  51053. * Prepares the list of defines specific to the light type.
  51054. * @param defines the list of defines
  51055. * @param lightIndex defines the index of the light for the effect
  51056. */
  51057. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51058. defines["SPOTLIGHT" + lightIndex] = true;
  51059. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51060. };
  51061. __decorate([
  51062. BABYLON.serialize()
  51063. ], SpotLight.prototype, "angle", null);
  51064. __decorate([
  51065. BABYLON.serialize()
  51066. ], SpotLight.prototype, "innerAngle", null);
  51067. __decorate([
  51068. BABYLON.serialize()
  51069. ], SpotLight.prototype, "shadowAngleScale", null);
  51070. __decorate([
  51071. BABYLON.serialize()
  51072. ], SpotLight.prototype, "exponent", void 0);
  51073. __decorate([
  51074. BABYLON.serialize()
  51075. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51076. __decorate([
  51077. BABYLON.serialize()
  51078. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51079. __decorate([
  51080. BABYLON.serialize()
  51081. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51082. __decorate([
  51083. BABYLON.serializeAsTexture("projectedLightTexture")
  51084. ], SpotLight.prototype, "_projectionTexture", void 0);
  51085. return SpotLight;
  51086. }(BABYLON.ShadowLight));
  51087. BABYLON.SpotLight = SpotLight;
  51088. })(BABYLON || (BABYLON = {}));
  51089. //# sourceMappingURL=babylon.spotLight.js.map
  51090. var BABYLON;
  51091. (function (BABYLON) {
  51092. /**
  51093. * Class used to override all child animations of a given target
  51094. */
  51095. var AnimationPropertiesOverride = /** @class */ (function () {
  51096. function AnimationPropertiesOverride() {
  51097. /**
  51098. * Gets or sets a value indicating if animation blending must be used
  51099. */
  51100. this.enableBlending = false;
  51101. /**
  51102. * Gets or sets the blending speed to use when enableBlending is true
  51103. */
  51104. this.blendingSpeed = 0.01;
  51105. /**
  51106. * Gets or sets the default loop mode to use
  51107. */
  51108. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51109. }
  51110. return AnimationPropertiesOverride;
  51111. }());
  51112. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51113. })(BABYLON || (BABYLON = {}));
  51114. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51115. var BABYLON;
  51116. (function (BABYLON) {
  51117. /**
  51118. * Represents the range of an animation
  51119. */
  51120. var AnimationRange = /** @class */ (function () {
  51121. /**
  51122. * Initializes the range of an animation
  51123. * @param name The name of the animation range
  51124. * @param from The starting frame of the animation
  51125. * @param to The ending frame of the animation
  51126. */
  51127. function AnimationRange(
  51128. /**The name of the animation range**/
  51129. name,
  51130. /**The starting frame of the animation */
  51131. from,
  51132. /**The ending frame of the animation*/
  51133. to) {
  51134. this.name = name;
  51135. this.from = from;
  51136. this.to = to;
  51137. }
  51138. /**
  51139. * Makes a copy of the animation range
  51140. * @returns A copy of the animation range
  51141. */
  51142. AnimationRange.prototype.clone = function () {
  51143. return new AnimationRange(this.name, this.from, this.to);
  51144. };
  51145. return AnimationRange;
  51146. }());
  51147. BABYLON.AnimationRange = AnimationRange;
  51148. /**
  51149. * Composed of a frame, and an action function
  51150. */
  51151. var AnimationEvent = /** @class */ (function () {
  51152. /**
  51153. * Initializes the animation event
  51154. * @param frame The frame for which the event is triggered
  51155. * @param action The event to perform when triggered
  51156. * @param onlyOnce Specifies if the event should be triggered only once
  51157. */
  51158. function AnimationEvent(
  51159. /** The frame for which the event is triggered **/
  51160. frame,
  51161. /** The event to perform when triggered **/
  51162. action,
  51163. /** Specifies if the event should be triggered only once**/
  51164. onlyOnce) {
  51165. this.frame = frame;
  51166. this.action = action;
  51167. this.onlyOnce = onlyOnce;
  51168. /**
  51169. * Specifies if the animation event is done
  51170. */
  51171. this.isDone = false;
  51172. }
  51173. /** @hidden */
  51174. AnimationEvent.prototype._clone = function () {
  51175. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51176. };
  51177. return AnimationEvent;
  51178. }());
  51179. BABYLON.AnimationEvent = AnimationEvent;
  51180. /**
  51181. * A cursor which tracks a point on a path
  51182. */
  51183. var PathCursor = /** @class */ (function () {
  51184. /**
  51185. * Initializes the path cursor
  51186. * @param path The path to track
  51187. */
  51188. function PathCursor(path) {
  51189. this.path = path;
  51190. /**
  51191. * Stores path cursor callbacks for when an onchange event is triggered
  51192. */
  51193. this._onchange = new Array();
  51194. /**
  51195. * The value of the path cursor
  51196. */
  51197. this.value = 0;
  51198. /**
  51199. * The animation array of the path cursor
  51200. */
  51201. this.animations = new Array();
  51202. }
  51203. /**
  51204. * Gets the cursor point on the path
  51205. * @returns A point on the path cursor at the cursor location
  51206. */
  51207. PathCursor.prototype.getPoint = function () {
  51208. var point = this.path.getPointAtLengthPosition(this.value);
  51209. return new BABYLON.Vector3(point.x, 0, point.y);
  51210. };
  51211. /**
  51212. * Moves the cursor ahead by the step amount
  51213. * @param step The amount to move the cursor forward
  51214. * @returns This path cursor
  51215. */
  51216. PathCursor.prototype.moveAhead = function (step) {
  51217. if (step === void 0) { step = 0.002; }
  51218. this.move(step);
  51219. return this;
  51220. };
  51221. /**
  51222. * Moves the cursor behind by the step amount
  51223. * @param step The amount to move the cursor back
  51224. * @returns This path cursor
  51225. */
  51226. PathCursor.prototype.moveBack = function (step) {
  51227. if (step === void 0) { step = 0.002; }
  51228. this.move(-step);
  51229. return this;
  51230. };
  51231. /**
  51232. * Moves the cursor by the step amount
  51233. * If the step amount is greater than one, an exception is thrown
  51234. * @param step The amount to move the cursor
  51235. * @returns This path cursor
  51236. */
  51237. PathCursor.prototype.move = function (step) {
  51238. if (Math.abs(step) > 1) {
  51239. throw "step size should be less than 1.";
  51240. }
  51241. this.value += step;
  51242. this.ensureLimits();
  51243. this.raiseOnChange();
  51244. return this;
  51245. };
  51246. /**
  51247. * Ensures that the value is limited between zero and one
  51248. * @returns This path cursor
  51249. */
  51250. PathCursor.prototype.ensureLimits = function () {
  51251. while (this.value > 1) {
  51252. this.value -= 1;
  51253. }
  51254. while (this.value < 0) {
  51255. this.value += 1;
  51256. }
  51257. return this;
  51258. };
  51259. /**
  51260. * Runs onchange callbacks on change (used by the animation engine)
  51261. * @returns This path cursor
  51262. */
  51263. PathCursor.prototype.raiseOnChange = function () {
  51264. var _this = this;
  51265. this._onchange.forEach(function (f) { return f(_this); });
  51266. return this;
  51267. };
  51268. /**
  51269. * Executes a function on change
  51270. * @param f A path cursor onchange callback
  51271. * @returns This path cursor
  51272. */
  51273. PathCursor.prototype.onchange = function (f) {
  51274. this._onchange.push(f);
  51275. return this;
  51276. };
  51277. return PathCursor;
  51278. }());
  51279. BABYLON.PathCursor = PathCursor;
  51280. /**
  51281. * Enum for the animation key frame interpolation type
  51282. */
  51283. var AnimationKeyInterpolation;
  51284. (function (AnimationKeyInterpolation) {
  51285. /**
  51286. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51287. */
  51288. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51289. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51290. /**
  51291. * Class used to store any kind of animation
  51292. */
  51293. var Animation = /** @class */ (function () {
  51294. /**
  51295. * Initializes the animation
  51296. * @param name Name of the animation
  51297. * @param targetProperty Property to animate
  51298. * @param framePerSecond The frames per second of the animation
  51299. * @param dataType The data type of the animation
  51300. * @param loopMode The loop mode of the animation
  51301. * @param enableBlendings Specifies if blending should be enabled
  51302. */
  51303. function Animation(
  51304. /**Name of the animation */
  51305. name,
  51306. /**Property to animate */
  51307. targetProperty,
  51308. /**The frames per second of the animation */
  51309. framePerSecond,
  51310. /**The data type of the animation */
  51311. dataType,
  51312. /**The loop mode of the animation */
  51313. loopMode,
  51314. /**Specifies if blending should be enabled */
  51315. enableBlending) {
  51316. this.name = name;
  51317. this.targetProperty = targetProperty;
  51318. this.framePerSecond = framePerSecond;
  51319. this.dataType = dataType;
  51320. this.loopMode = loopMode;
  51321. this.enableBlending = enableBlending;
  51322. /**
  51323. * @hidden Internal use only
  51324. */
  51325. this._runtimeAnimations = new Array();
  51326. /**
  51327. * The set of event that will be linked to this animation
  51328. */
  51329. this._events = new Array();
  51330. /**
  51331. * Stores the blending speed of the animation
  51332. */
  51333. this.blendingSpeed = 0.01;
  51334. /**
  51335. * Stores the animation ranges for the animation
  51336. */
  51337. this._ranges = {};
  51338. this.targetPropertyPath = targetProperty.split(".");
  51339. this.dataType = dataType;
  51340. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51341. }
  51342. /**
  51343. * @hidden Internal use
  51344. */
  51345. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51346. var dataType = undefined;
  51347. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51348. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51349. }
  51350. else if (from instanceof BABYLON.Quaternion) {
  51351. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51352. }
  51353. else if (from instanceof BABYLON.Vector3) {
  51354. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51355. }
  51356. else if (from instanceof BABYLON.Vector2) {
  51357. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51358. }
  51359. else if (from instanceof BABYLON.Color3) {
  51360. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51361. }
  51362. else if (from instanceof BABYLON.Size) {
  51363. dataType = Animation.ANIMATIONTYPE_SIZE;
  51364. }
  51365. if (dataType == undefined) {
  51366. return null;
  51367. }
  51368. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51369. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51370. animation.setKeys(keys);
  51371. if (easingFunction !== undefined) {
  51372. animation.setEasingFunction(easingFunction);
  51373. }
  51374. return animation;
  51375. };
  51376. /**
  51377. * Sets up an animation
  51378. * @param property The property to animate
  51379. * @param animationType The animation type to apply
  51380. * @param framePerSecond The frames per second of the animation
  51381. * @param easingFunction The easing function used in the animation
  51382. * @returns The created animation
  51383. */
  51384. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51385. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51386. animation.setEasingFunction(easingFunction);
  51387. return animation;
  51388. };
  51389. /**
  51390. * Create and start an animation on a node
  51391. * @param name defines the name of the global animation that will be run on all nodes
  51392. * @param node defines the root node where the animation will take place
  51393. * @param targetProperty defines property to animate
  51394. * @param framePerSecond defines the number of frame per second yo use
  51395. * @param totalFrame defines the number of frames in total
  51396. * @param from defines the initial value
  51397. * @param to defines the final value
  51398. * @param loopMode defines which loop mode you want to use (off by default)
  51399. * @param easingFunction defines the easing function to use (linear by default)
  51400. * @param onAnimationEnd defines the callback to call when animation end
  51401. * @returns the animatable created for this animation
  51402. */
  51403. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51404. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51405. if (!animation) {
  51406. return null;
  51407. }
  51408. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51409. };
  51410. /**
  51411. * Create and start an animation on a node and its descendants
  51412. * @param name defines the name of the global animation that will be run on all nodes
  51413. * @param node defines the root node where the animation will take place
  51414. * @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
  51415. * @param targetProperty defines property to animate
  51416. * @param framePerSecond defines the number of frame per second to use
  51417. * @param totalFrame defines the number of frames in total
  51418. * @param from defines the initial value
  51419. * @param to defines the final value
  51420. * @param loopMode defines which loop mode you want to use (off by default)
  51421. * @param easingFunction defines the easing function to use (linear by default)
  51422. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51423. * @returns the list of animatables created for all nodes
  51424. * @example https://www.babylonjs-playground.com/#MH0VLI
  51425. */
  51426. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51427. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51428. if (!animation) {
  51429. return null;
  51430. }
  51431. var scene = node.getScene();
  51432. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51433. };
  51434. /**
  51435. * Creates a new animation, merges it with the existing animations and starts it
  51436. * @param name Name of the animation
  51437. * @param node Node which contains the scene that begins the animations
  51438. * @param targetProperty Specifies which property to animate
  51439. * @param framePerSecond The frames per second of the animation
  51440. * @param totalFrame The total number of frames
  51441. * @param from The frame at the beginning of the animation
  51442. * @param to The frame at the end of the animation
  51443. * @param loopMode Specifies the loop mode of the animation
  51444. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51445. * @param onAnimationEnd Callback to run once the animation is complete
  51446. * @returns Nullable animation
  51447. */
  51448. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51449. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51450. if (!animation) {
  51451. return null;
  51452. }
  51453. node.animations.push(animation);
  51454. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51455. };
  51456. /**
  51457. * Transition property of an host to the target Value
  51458. * @param property The property to transition
  51459. * @param targetValue The target Value of the property
  51460. * @param host The object where the property to animate belongs
  51461. * @param scene Scene used to run the animation
  51462. * @param frameRate Framerate (in frame/s) to use
  51463. * @param transition The transition type we want to use
  51464. * @param duration The duration of the animation, in milliseconds
  51465. * @param onAnimationEnd Callback trigger at the end of the animation
  51466. * @returns Nullable animation
  51467. */
  51468. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51469. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51470. if (duration <= 0) {
  51471. host[property] = targetValue;
  51472. if (onAnimationEnd) {
  51473. onAnimationEnd();
  51474. }
  51475. return null;
  51476. }
  51477. var endFrame = frameRate * (duration / 1000);
  51478. transition.setKeys([{
  51479. frame: 0,
  51480. value: host[property].clone ? host[property].clone() : host[property]
  51481. },
  51482. {
  51483. frame: endFrame,
  51484. value: targetValue
  51485. }]);
  51486. if (!host.animations) {
  51487. host.animations = [];
  51488. }
  51489. host.animations.push(transition);
  51490. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51491. animation.onAnimationEnd = onAnimationEnd;
  51492. return animation;
  51493. };
  51494. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51495. /**
  51496. * Return the array of runtime animations currently using this animation
  51497. */
  51498. get: function () {
  51499. return this._runtimeAnimations;
  51500. },
  51501. enumerable: true,
  51502. configurable: true
  51503. });
  51504. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51505. /**
  51506. * Specifies if any of the runtime animations are currently running
  51507. */
  51508. get: function () {
  51509. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51510. var runtimeAnimation = _a[_i];
  51511. if (!runtimeAnimation.isStopped) {
  51512. return true;
  51513. }
  51514. }
  51515. return false;
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. // Methods
  51521. /**
  51522. * Converts the animation to a string
  51523. * @param fullDetails support for multiple levels of logging within scene loading
  51524. * @returns String form of the animation
  51525. */
  51526. Animation.prototype.toString = function (fullDetails) {
  51527. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51528. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51529. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51530. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51531. if (fullDetails) {
  51532. ret += ", Ranges: {";
  51533. var first = true;
  51534. for (var name in this._ranges) {
  51535. if (first) {
  51536. ret += ", ";
  51537. first = false;
  51538. }
  51539. ret += name;
  51540. }
  51541. ret += "}";
  51542. }
  51543. return ret;
  51544. };
  51545. /**
  51546. * Add an event to this animation
  51547. * @param event Event to add
  51548. */
  51549. Animation.prototype.addEvent = function (event) {
  51550. this._events.push(event);
  51551. };
  51552. /**
  51553. * Remove all events found at the given frame
  51554. * @param frame The frame to remove events from
  51555. */
  51556. Animation.prototype.removeEvents = function (frame) {
  51557. for (var index = 0; index < this._events.length; index++) {
  51558. if (this._events[index].frame === frame) {
  51559. this._events.splice(index, 1);
  51560. index--;
  51561. }
  51562. }
  51563. };
  51564. /**
  51565. * Retrieves all the events from the animation
  51566. * @returns Events from the animation
  51567. */
  51568. Animation.prototype.getEvents = function () {
  51569. return this._events;
  51570. };
  51571. /**
  51572. * Creates an animation range
  51573. * @param name Name of the animation range
  51574. * @param from Starting frame of the animation range
  51575. * @param to Ending frame of the animation
  51576. */
  51577. Animation.prototype.createRange = function (name, from, to) {
  51578. // check name not already in use; could happen for bones after serialized
  51579. if (!this._ranges[name]) {
  51580. this._ranges[name] = new AnimationRange(name, from, to);
  51581. }
  51582. };
  51583. /**
  51584. * Deletes an animation range by name
  51585. * @param name Name of the animation range to delete
  51586. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51587. */
  51588. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51589. if (deleteFrames === void 0) { deleteFrames = true; }
  51590. var range = this._ranges[name];
  51591. if (!range) {
  51592. return;
  51593. }
  51594. if (deleteFrames) {
  51595. var from = range.from;
  51596. var to = range.to;
  51597. // this loop MUST go high to low for multiple splices to work
  51598. for (var key = this._keys.length - 1; key >= 0; key--) {
  51599. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51600. this._keys.splice(key, 1);
  51601. }
  51602. }
  51603. }
  51604. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51605. };
  51606. /**
  51607. * Gets the animation range by name, or null if not defined
  51608. * @param name Name of the animation range
  51609. * @returns Nullable animation range
  51610. */
  51611. Animation.prototype.getRange = function (name) {
  51612. return this._ranges[name];
  51613. };
  51614. /**
  51615. * Gets the key frames from the animation
  51616. * @returns The key frames of the animation
  51617. */
  51618. Animation.prototype.getKeys = function () {
  51619. return this._keys;
  51620. };
  51621. /**
  51622. * Gets the highest frame rate of the animation
  51623. * @returns Highest frame rate of the animation
  51624. */
  51625. Animation.prototype.getHighestFrame = function () {
  51626. var ret = 0;
  51627. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51628. if (ret < this._keys[key].frame) {
  51629. ret = this._keys[key].frame;
  51630. }
  51631. }
  51632. return ret;
  51633. };
  51634. /**
  51635. * Gets the easing function of the animation
  51636. * @returns Easing function of the animation
  51637. */
  51638. Animation.prototype.getEasingFunction = function () {
  51639. return this._easingFunction;
  51640. };
  51641. /**
  51642. * Sets the easing function of the animation
  51643. * @param easingFunction A custom mathematical formula for animation
  51644. */
  51645. Animation.prototype.setEasingFunction = function (easingFunction) {
  51646. this._easingFunction = easingFunction;
  51647. };
  51648. /**
  51649. * Interpolates a scalar linearly
  51650. * @param startValue Start value of the animation curve
  51651. * @param endValue End value of the animation curve
  51652. * @param gradient Scalar amount to interpolate
  51653. * @returns Interpolated scalar value
  51654. */
  51655. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51656. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51657. };
  51658. /**
  51659. * Interpolates a scalar cubically
  51660. * @param startValue Start value of the animation curve
  51661. * @param outTangent End tangent of the animation
  51662. * @param endValue End value of the animation curve
  51663. * @param inTangent Start tangent of the animation curve
  51664. * @param gradient Scalar amount to interpolate
  51665. * @returns Interpolated scalar value
  51666. */
  51667. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51668. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51669. };
  51670. /**
  51671. * Interpolates a quaternion using a spherical linear interpolation
  51672. * @param startValue Start value of the animation curve
  51673. * @param endValue End value of the animation curve
  51674. * @param gradient Scalar amount to interpolate
  51675. * @returns Interpolated quaternion value
  51676. */
  51677. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51678. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51679. };
  51680. /**
  51681. * Interpolates a quaternion cubically
  51682. * @param startValue Start value of the animation curve
  51683. * @param outTangent End tangent of the animation curve
  51684. * @param endValue End value of the animation curve
  51685. * @param inTangent Start tangent of the animation curve
  51686. * @param gradient Scalar amount to interpolate
  51687. * @returns Interpolated quaternion value
  51688. */
  51689. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51690. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51691. };
  51692. /**
  51693. * Interpolates a Vector3 linearl
  51694. * @param startValue Start value of the animation curve
  51695. * @param endValue End value of the animation curve
  51696. * @param gradient Scalar amount to interpolate
  51697. * @returns Interpolated scalar value
  51698. */
  51699. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51700. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51701. };
  51702. /**
  51703. * Interpolates a Vector3 cubically
  51704. * @param startValue Start value of the animation curve
  51705. * @param outTangent End tangent of the animation
  51706. * @param endValue End value of the animation curve
  51707. * @param inTangent Start tangent of the animation curve
  51708. * @param gradient Scalar amount to interpolate
  51709. * @returns InterpolatedVector3 value
  51710. */
  51711. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51712. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51713. };
  51714. /**
  51715. * Interpolates a Vector2 linearly
  51716. * @param startValue Start value of the animation curve
  51717. * @param endValue End value of the animation curve
  51718. * @param gradient Scalar amount to interpolate
  51719. * @returns Interpolated Vector2 value
  51720. */
  51721. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51722. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51723. };
  51724. /**
  51725. * Interpolates a Vector2 cubically
  51726. * @param startValue Start value of the animation curve
  51727. * @param outTangent End tangent of the animation
  51728. * @param endValue End value of the animation curve
  51729. * @param inTangent Start tangent of the animation curve
  51730. * @param gradient Scalar amount to interpolate
  51731. * @returns Interpolated Vector2 value
  51732. */
  51733. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51734. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51735. };
  51736. /**
  51737. * Interpolates a size linearly
  51738. * @param startValue Start value of the animation curve
  51739. * @param endValue End value of the animation curve
  51740. * @param gradient Scalar amount to interpolate
  51741. * @returns Interpolated Size value
  51742. */
  51743. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51744. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51745. };
  51746. /**
  51747. * Interpolates a Color3 linearly
  51748. * @param startValue Start value of the animation curve
  51749. * @param endValue End value of the animation curve
  51750. * @param gradient Scalar amount to interpolate
  51751. * @returns Interpolated Color3 value
  51752. */
  51753. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51754. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51755. };
  51756. /**
  51757. * @hidden Internal use only
  51758. */
  51759. Animation.prototype._getKeyValue = function (value) {
  51760. if (typeof value === "function") {
  51761. return value();
  51762. }
  51763. return value;
  51764. };
  51765. /**
  51766. * @hidden Internal use only
  51767. */
  51768. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51769. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51770. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51771. }
  51772. var keys = this.getKeys();
  51773. // Try to get a hash to find the right key
  51774. 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));
  51775. if (keys[startKeyIndex].frame >= currentFrame) {
  51776. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51777. startKeyIndex--;
  51778. }
  51779. }
  51780. for (var key = startKeyIndex; key < keys.length; key++) {
  51781. var endKey = keys[key + 1];
  51782. if (endKey.frame >= currentFrame) {
  51783. var startKey = keys[key];
  51784. var startValue = this._getKeyValue(startKey.value);
  51785. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51786. return startValue;
  51787. }
  51788. var endValue = this._getKeyValue(endKey.value);
  51789. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51790. var frameDelta = endKey.frame - startKey.frame;
  51791. // gradient : percent of currentFrame between the frame inf and the frame sup
  51792. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51793. // check for easingFunction and correction of gradient
  51794. var easingFunction = this.getEasingFunction();
  51795. if (easingFunction != null) {
  51796. gradient = easingFunction.ease(gradient);
  51797. }
  51798. switch (this.dataType) {
  51799. // Float
  51800. case Animation.ANIMATIONTYPE_FLOAT:
  51801. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51802. switch (loopMode) {
  51803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51805. return floatValue;
  51806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51807. return offsetValue * repeatCount + floatValue;
  51808. }
  51809. break;
  51810. // Quaternion
  51811. case Animation.ANIMATIONTYPE_QUATERNION:
  51812. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51813. switch (loopMode) {
  51814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51816. return quatValue;
  51817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51818. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51819. }
  51820. return quatValue;
  51821. // Vector3
  51822. case Animation.ANIMATIONTYPE_VECTOR3:
  51823. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51824. switch (loopMode) {
  51825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51827. return vec3Value;
  51828. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51829. return vec3Value.add(offsetValue.scale(repeatCount));
  51830. }
  51831. // Vector2
  51832. case Animation.ANIMATIONTYPE_VECTOR2:
  51833. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51834. switch (loopMode) {
  51835. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51836. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51837. return vec2Value;
  51838. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51839. return vec2Value.add(offsetValue.scale(repeatCount));
  51840. }
  51841. // Size
  51842. case Animation.ANIMATIONTYPE_SIZE:
  51843. switch (loopMode) {
  51844. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51845. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51846. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51847. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51848. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51849. }
  51850. // Color3
  51851. case Animation.ANIMATIONTYPE_COLOR3:
  51852. switch (loopMode) {
  51853. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51854. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51855. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51857. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51858. }
  51859. // Matrix
  51860. case Animation.ANIMATIONTYPE_MATRIX:
  51861. switch (loopMode) {
  51862. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51863. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51864. if (Animation.AllowMatricesInterpolation) {
  51865. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51866. }
  51867. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51868. return startValue;
  51869. }
  51870. default:
  51871. break;
  51872. }
  51873. break;
  51874. }
  51875. }
  51876. return this._getKeyValue(keys[keys.length - 1].value);
  51877. };
  51878. /**
  51879. * Defines the function to use to interpolate matrices
  51880. * @param startValue defines the start matrix
  51881. * @param endValue defines the end matrix
  51882. * @param gradient defines the gradient between both matrices
  51883. * @param result defines an optional target matrix where to store the interpolation
  51884. * @returns the interpolated matrix
  51885. */
  51886. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51887. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51888. if (result) {
  51889. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51890. return result;
  51891. }
  51892. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51893. }
  51894. if (result) {
  51895. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51896. return result;
  51897. }
  51898. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51899. };
  51900. /**
  51901. * Makes a copy of the animation
  51902. * @returns Cloned animation
  51903. */
  51904. Animation.prototype.clone = function () {
  51905. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51906. clone.enableBlending = this.enableBlending;
  51907. clone.blendingSpeed = this.blendingSpeed;
  51908. if (this._keys) {
  51909. clone.setKeys(this._keys);
  51910. }
  51911. if (this._ranges) {
  51912. clone._ranges = {};
  51913. for (var name in this._ranges) {
  51914. var range = this._ranges[name];
  51915. if (!range) {
  51916. continue;
  51917. }
  51918. clone._ranges[name] = range.clone();
  51919. }
  51920. }
  51921. return clone;
  51922. };
  51923. /**
  51924. * Sets the key frames of the animation
  51925. * @param values The animation key frames to set
  51926. */
  51927. Animation.prototype.setKeys = function (values) {
  51928. this._keys = values.slice(0);
  51929. };
  51930. /**
  51931. * Serializes the animation to an object
  51932. * @returns Serialized object
  51933. */
  51934. Animation.prototype.serialize = function () {
  51935. var serializationObject = {};
  51936. serializationObject.name = this.name;
  51937. serializationObject.property = this.targetProperty;
  51938. serializationObject.framePerSecond = this.framePerSecond;
  51939. serializationObject.dataType = this.dataType;
  51940. serializationObject.loopBehavior = this.loopMode;
  51941. serializationObject.enableBlending = this.enableBlending;
  51942. serializationObject.blendingSpeed = this.blendingSpeed;
  51943. var dataType = this.dataType;
  51944. serializationObject.keys = [];
  51945. var keys = this.getKeys();
  51946. for (var index = 0; index < keys.length; index++) {
  51947. var animationKey = keys[index];
  51948. var key = {};
  51949. key.frame = animationKey.frame;
  51950. switch (dataType) {
  51951. case Animation.ANIMATIONTYPE_FLOAT:
  51952. key.values = [animationKey.value];
  51953. break;
  51954. case Animation.ANIMATIONTYPE_QUATERNION:
  51955. case Animation.ANIMATIONTYPE_MATRIX:
  51956. case Animation.ANIMATIONTYPE_VECTOR3:
  51957. case Animation.ANIMATIONTYPE_COLOR3:
  51958. key.values = animationKey.value.asArray();
  51959. break;
  51960. }
  51961. serializationObject.keys.push(key);
  51962. }
  51963. serializationObject.ranges = [];
  51964. for (var name in this._ranges) {
  51965. var source = this._ranges[name];
  51966. if (!source) {
  51967. continue;
  51968. }
  51969. var range = {};
  51970. range.name = name;
  51971. range.from = source.from;
  51972. range.to = source.to;
  51973. serializationObject.ranges.push(range);
  51974. }
  51975. return serializationObject;
  51976. };
  51977. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51978. /**
  51979. * Get the float animation type
  51980. */
  51981. get: function () {
  51982. return Animation._ANIMATIONTYPE_FLOAT;
  51983. },
  51984. enumerable: true,
  51985. configurable: true
  51986. });
  51987. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51988. /**
  51989. * Get the Vector3 animation type
  51990. */
  51991. get: function () {
  51992. return Animation._ANIMATIONTYPE_VECTOR3;
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51998. /**
  51999. * Get the Vector2 animation type
  52000. */
  52001. get: function () {
  52002. return Animation._ANIMATIONTYPE_VECTOR2;
  52003. },
  52004. enumerable: true,
  52005. configurable: true
  52006. });
  52007. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52008. /**
  52009. * Get the Size animation type
  52010. */
  52011. get: function () {
  52012. return Animation._ANIMATIONTYPE_SIZE;
  52013. },
  52014. enumerable: true,
  52015. configurable: true
  52016. });
  52017. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52018. /**
  52019. * Get the Quaternion animation type
  52020. */
  52021. get: function () {
  52022. return Animation._ANIMATIONTYPE_QUATERNION;
  52023. },
  52024. enumerable: true,
  52025. configurable: true
  52026. });
  52027. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52028. /**
  52029. * Get the Matrix animation type
  52030. */
  52031. get: function () {
  52032. return Animation._ANIMATIONTYPE_MATRIX;
  52033. },
  52034. enumerable: true,
  52035. configurable: true
  52036. });
  52037. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52038. /**
  52039. * Get the Color3 animation type
  52040. */
  52041. get: function () {
  52042. return Animation._ANIMATIONTYPE_COLOR3;
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52048. /**
  52049. * Get the Relative Loop Mode
  52050. */
  52051. get: function () {
  52052. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52058. /**
  52059. * Get the Cycle Loop Mode
  52060. */
  52061. get: function () {
  52062. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52068. /**
  52069. * Get the Constant Loop Mode
  52070. */
  52071. get: function () {
  52072. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52073. },
  52074. enumerable: true,
  52075. configurable: true
  52076. });
  52077. /** @hidden */
  52078. Animation._UniversalLerp = function (left, right, amount) {
  52079. var constructor = left.constructor;
  52080. if (constructor.Lerp) { // Lerp supported
  52081. return constructor.Lerp(left, right, amount);
  52082. }
  52083. else if (constructor.Slerp) { // Slerp supported
  52084. return constructor.Slerp(left, right, amount);
  52085. }
  52086. else if (left.toFixed) { // Number
  52087. return left * (1.0 - amount) + amount * right;
  52088. }
  52089. else { // Blending not supported
  52090. return right;
  52091. }
  52092. };
  52093. /**
  52094. * Parses an animation object and creates an animation
  52095. * @param parsedAnimation Parsed animation object
  52096. * @returns Animation object
  52097. */
  52098. Animation.Parse = function (parsedAnimation) {
  52099. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52100. var dataType = parsedAnimation.dataType;
  52101. var keys = [];
  52102. var data;
  52103. var index;
  52104. if (parsedAnimation.enableBlending) {
  52105. animation.enableBlending = parsedAnimation.enableBlending;
  52106. }
  52107. if (parsedAnimation.blendingSpeed) {
  52108. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52109. }
  52110. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52111. var key = parsedAnimation.keys[index];
  52112. var inTangent;
  52113. var outTangent;
  52114. switch (dataType) {
  52115. case Animation.ANIMATIONTYPE_FLOAT:
  52116. data = key.values[0];
  52117. if (key.values.length >= 1) {
  52118. inTangent = key.values[1];
  52119. }
  52120. if (key.values.length >= 2) {
  52121. outTangent = key.values[2];
  52122. }
  52123. break;
  52124. case Animation.ANIMATIONTYPE_QUATERNION:
  52125. data = BABYLON.Quaternion.FromArray(key.values);
  52126. if (key.values.length >= 8) {
  52127. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52128. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52129. inTangent = _inTangent;
  52130. }
  52131. }
  52132. if (key.values.length >= 12) {
  52133. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52134. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52135. outTangent = _outTangent;
  52136. }
  52137. }
  52138. break;
  52139. case Animation.ANIMATIONTYPE_MATRIX:
  52140. data = BABYLON.Matrix.FromArray(key.values);
  52141. break;
  52142. case Animation.ANIMATIONTYPE_COLOR3:
  52143. data = BABYLON.Color3.FromArray(key.values);
  52144. break;
  52145. case Animation.ANIMATIONTYPE_VECTOR3:
  52146. default:
  52147. data = BABYLON.Vector3.FromArray(key.values);
  52148. break;
  52149. }
  52150. var keyData = {};
  52151. keyData.frame = key.frame;
  52152. keyData.value = data;
  52153. if (inTangent != undefined) {
  52154. keyData.inTangent = inTangent;
  52155. }
  52156. if (outTangent != undefined) {
  52157. keyData.outTangent = outTangent;
  52158. }
  52159. keys.push(keyData);
  52160. }
  52161. animation.setKeys(keys);
  52162. if (parsedAnimation.ranges) {
  52163. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52164. data = parsedAnimation.ranges[index];
  52165. animation.createRange(data.name, data.from, data.to);
  52166. }
  52167. }
  52168. return animation;
  52169. };
  52170. /**
  52171. * Appends the serialized animations from the source animations
  52172. * @param source Source containing the animations
  52173. * @param destination Target to store the animations
  52174. */
  52175. Animation.AppendSerializedAnimations = function (source, destination) {
  52176. if (source.animations) {
  52177. destination.animations = [];
  52178. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52179. var animation = source.animations[animationIndex];
  52180. destination.animations.push(animation.serialize());
  52181. }
  52182. }
  52183. };
  52184. /**
  52185. * Use matrix interpolation instead of using direct key value when animating matrices
  52186. */
  52187. Animation.AllowMatricesInterpolation = false;
  52188. /**
  52189. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52190. */
  52191. Animation.AllowMatrixDecomposeForInterpolation = true;
  52192. // Statics
  52193. /**
  52194. * Float animation type
  52195. */
  52196. Animation._ANIMATIONTYPE_FLOAT = 0;
  52197. /**
  52198. * Vector3 animation type
  52199. */
  52200. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52201. /**
  52202. * Quaternion animation type
  52203. */
  52204. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52205. /**
  52206. * Matrix animation type
  52207. */
  52208. Animation._ANIMATIONTYPE_MATRIX = 3;
  52209. /**
  52210. * Color3 animation type
  52211. */
  52212. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52213. /**
  52214. * Vector2 animation type
  52215. */
  52216. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52217. /**
  52218. * Size animation type
  52219. */
  52220. Animation._ANIMATIONTYPE_SIZE = 6;
  52221. /**
  52222. * Relative Loop Mode
  52223. */
  52224. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52225. /**
  52226. * Cycle Loop Mode
  52227. */
  52228. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52229. /**
  52230. * Constant Loop Mode
  52231. */
  52232. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52233. return Animation;
  52234. }());
  52235. BABYLON.Animation = Animation;
  52236. })(BABYLON || (BABYLON = {}));
  52237. //# sourceMappingURL=babylon.animation.js.map
  52238. var BABYLON;
  52239. (function (BABYLON) {
  52240. /**
  52241. * This class defines the direct association between an animation and a target
  52242. */
  52243. var TargetedAnimation = /** @class */ (function () {
  52244. function TargetedAnimation() {
  52245. }
  52246. return TargetedAnimation;
  52247. }());
  52248. BABYLON.TargetedAnimation = TargetedAnimation;
  52249. /**
  52250. * Use this class to create coordinated animations on multiple targets
  52251. */
  52252. var AnimationGroup = /** @class */ (function () {
  52253. /**
  52254. * Instantiates a new Animation Group.
  52255. * This helps managing several animations at once.
  52256. * @see http://doc.babylonjs.com/how_to/group
  52257. * @param name Defines the name of the group
  52258. * @param scene Defines the scene the group belongs to
  52259. */
  52260. function AnimationGroup(
  52261. /** The name of the animation group */
  52262. name, scene) {
  52263. if (scene === void 0) { scene = null; }
  52264. this.name = name;
  52265. this._targetedAnimations = new Array();
  52266. this._animatables = new Array();
  52267. this._from = Number.MAX_VALUE;
  52268. this._to = -Number.MAX_VALUE;
  52269. this._speedRatio = 1;
  52270. /**
  52271. * This observable will notify when one animation have ended.
  52272. */
  52273. this.onAnimationEndObservable = new BABYLON.Observable();
  52274. /**
  52275. * This observable will notify when all animations have ended.
  52276. */
  52277. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52278. /**
  52279. * This observable will notify when all animations have paused.
  52280. */
  52281. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52282. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52283. this._scene.animationGroups.push(this);
  52284. }
  52285. Object.defineProperty(AnimationGroup.prototype, "from", {
  52286. /**
  52287. * Gets the first frame
  52288. */
  52289. get: function () {
  52290. return this._from;
  52291. },
  52292. enumerable: true,
  52293. configurable: true
  52294. });
  52295. Object.defineProperty(AnimationGroup.prototype, "to", {
  52296. /**
  52297. * Gets the last frame
  52298. */
  52299. get: function () {
  52300. return this._to;
  52301. },
  52302. enumerable: true,
  52303. configurable: true
  52304. });
  52305. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52306. /**
  52307. * Define if the animations are started
  52308. */
  52309. get: function () {
  52310. return this._isStarted;
  52311. },
  52312. enumerable: true,
  52313. configurable: true
  52314. });
  52315. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52316. /**
  52317. * Gets or sets the speed ratio to use for all animations
  52318. */
  52319. get: function () {
  52320. return this._speedRatio;
  52321. },
  52322. /**
  52323. * Gets or sets the speed ratio to use for all animations
  52324. */
  52325. set: function (value) {
  52326. if (this._speedRatio === value) {
  52327. return;
  52328. }
  52329. this._speedRatio = value;
  52330. for (var index = 0; index < this._animatables.length; index++) {
  52331. var animatable = this._animatables[index];
  52332. animatable.speedRatio = this._speedRatio;
  52333. }
  52334. },
  52335. enumerable: true,
  52336. configurable: true
  52337. });
  52338. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52339. /**
  52340. * Gets the targeted animations for this animation group
  52341. */
  52342. get: function () {
  52343. return this._targetedAnimations;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52349. /**
  52350. * returning the list of animatables controlled by this animation group.
  52351. */
  52352. get: function () {
  52353. return this._animatables;
  52354. },
  52355. enumerable: true,
  52356. configurable: true
  52357. });
  52358. /**
  52359. * Add an animation (with its target) in the group
  52360. * @param animation defines the animation we want to add
  52361. * @param target defines the target of the animation
  52362. * @returns the {BABYLON.TargetedAnimation} object
  52363. */
  52364. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52365. var targetedAnimation = {
  52366. animation: animation,
  52367. target: target
  52368. };
  52369. var keys = animation.getKeys();
  52370. if (this._from > keys[0].frame) {
  52371. this._from = keys[0].frame;
  52372. }
  52373. if (this._to < keys[keys.length - 1].frame) {
  52374. this._to = keys[keys.length - 1].frame;
  52375. }
  52376. this._targetedAnimations.push(targetedAnimation);
  52377. return targetedAnimation;
  52378. };
  52379. /**
  52380. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52381. * It can add constant keys at begin or end
  52382. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52383. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52384. * @returns the animation group
  52385. */
  52386. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52387. if (beginFrame === void 0) { beginFrame = null; }
  52388. if (endFrame === void 0) { endFrame = null; }
  52389. if (beginFrame == null)
  52390. beginFrame = this._from;
  52391. if (endFrame == null)
  52392. endFrame = this._to;
  52393. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52394. var targetedAnimation = this._targetedAnimations[index];
  52395. var keys = targetedAnimation.animation.getKeys();
  52396. var startKey = keys[0];
  52397. var endKey = keys[keys.length - 1];
  52398. if (startKey.frame > beginFrame) {
  52399. var newKey = {
  52400. frame: beginFrame,
  52401. value: startKey.value,
  52402. inTangent: startKey.inTangent,
  52403. outTangent: startKey.outTangent,
  52404. interpolation: startKey.interpolation
  52405. };
  52406. keys.splice(0, 0, newKey);
  52407. }
  52408. if (endKey.frame < endFrame) {
  52409. var newKey = {
  52410. frame: endFrame,
  52411. value: endKey.value,
  52412. inTangent: endKey.outTangent,
  52413. outTangent: endKey.outTangent,
  52414. interpolation: endKey.interpolation
  52415. };
  52416. keys.push(newKey);
  52417. }
  52418. }
  52419. this._from = beginFrame;
  52420. this._to = endFrame;
  52421. return this;
  52422. };
  52423. /**
  52424. * Start all animations on given targets
  52425. * @param loop defines if animations must loop
  52426. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52427. * @param from defines the from key (optional)
  52428. * @param to defines the to key (optional)
  52429. * @returns the current animation group
  52430. */
  52431. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52432. var _this = this;
  52433. if (loop === void 0) { loop = false; }
  52434. if (speedRatio === void 0) { speedRatio = 1; }
  52435. if (this._isStarted || this._targetedAnimations.length === 0) {
  52436. return this;
  52437. }
  52438. var _loop_1 = function (targetedAnimation) {
  52439. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52440. animatable.onAnimationEnd = function () {
  52441. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52442. _this._checkAnimationGroupEnded(animatable);
  52443. };
  52444. this_1._animatables.push(animatable);
  52445. };
  52446. var this_1 = this;
  52447. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52448. var targetedAnimation = _a[_i];
  52449. _loop_1(targetedAnimation);
  52450. }
  52451. this._speedRatio = speedRatio;
  52452. this._isStarted = true;
  52453. return this;
  52454. };
  52455. /**
  52456. * Pause all animations
  52457. * @returns the animation group
  52458. */
  52459. AnimationGroup.prototype.pause = function () {
  52460. if (!this._isStarted) {
  52461. return this;
  52462. }
  52463. for (var index = 0; index < this._animatables.length; index++) {
  52464. var animatable = this._animatables[index];
  52465. animatable.pause();
  52466. }
  52467. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52468. return this;
  52469. };
  52470. /**
  52471. * Play all animations to initial state
  52472. * This function will start() the animations if they were not started or will restart() them if they were paused
  52473. * @param loop defines if animations must loop
  52474. * @returns the animation group
  52475. */
  52476. AnimationGroup.prototype.play = function (loop) {
  52477. // only if all animatables are ready and exist
  52478. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52479. if (loop !== undefined) {
  52480. for (var index = 0; index < this._animatables.length; index++) {
  52481. var animatable = this._animatables[index];
  52482. animatable.loopAnimation = loop;
  52483. }
  52484. }
  52485. this.restart();
  52486. }
  52487. else {
  52488. this.stop();
  52489. this.start(loop, this._speedRatio);
  52490. }
  52491. return this;
  52492. };
  52493. /**
  52494. * Reset all animations to initial state
  52495. * @returns the animation group
  52496. */
  52497. AnimationGroup.prototype.reset = function () {
  52498. if (!this._isStarted) {
  52499. return this;
  52500. }
  52501. for (var index = 0; index < this._animatables.length; index++) {
  52502. var animatable = this._animatables[index];
  52503. animatable.reset();
  52504. }
  52505. return this;
  52506. };
  52507. /**
  52508. * Restart animations from key 0
  52509. * @returns the animation group
  52510. */
  52511. AnimationGroup.prototype.restart = function () {
  52512. if (!this._isStarted) {
  52513. return this;
  52514. }
  52515. for (var index = 0; index < this._animatables.length; index++) {
  52516. var animatable = this._animatables[index];
  52517. animatable.restart();
  52518. }
  52519. return this;
  52520. };
  52521. /**
  52522. * Stop all animations
  52523. * @returns the animation group
  52524. */
  52525. AnimationGroup.prototype.stop = function () {
  52526. if (!this._isStarted) {
  52527. return this;
  52528. }
  52529. var list = this._animatables.slice();
  52530. for (var index = 0; index < list.length; index++) {
  52531. list[index].stop();
  52532. }
  52533. this._isStarted = false;
  52534. return this;
  52535. };
  52536. /**
  52537. * Set animation weight for all animatables
  52538. * @param weight defines the weight to use
  52539. * @return the animationGroup
  52540. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52541. */
  52542. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52543. for (var index = 0; index < this._animatables.length; index++) {
  52544. var animatable = this._animatables[index];
  52545. animatable.weight = weight;
  52546. }
  52547. return this;
  52548. };
  52549. /**
  52550. * Synchronize and normalize all animatables with a source animatable
  52551. * @param root defines the root animatable to synchronize with
  52552. * @return the animationGroup
  52553. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52554. */
  52555. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52556. for (var index = 0; index < this._animatables.length; index++) {
  52557. var animatable = this._animatables[index];
  52558. animatable.syncWith(root);
  52559. }
  52560. return this;
  52561. };
  52562. /**
  52563. * Goes to a specific frame in this animation group
  52564. * @param frame the frame number to go to
  52565. * @return the animationGroup
  52566. */
  52567. AnimationGroup.prototype.goToFrame = function (frame) {
  52568. if (!this._isStarted) {
  52569. return this;
  52570. }
  52571. for (var index = 0; index < this._animatables.length; index++) {
  52572. var animatable = this._animatables[index];
  52573. animatable.goToFrame(frame);
  52574. }
  52575. return this;
  52576. };
  52577. /**
  52578. * Dispose all associated resources
  52579. */
  52580. AnimationGroup.prototype.dispose = function () {
  52581. this._targetedAnimations = [];
  52582. this._animatables = [];
  52583. var index = this._scene.animationGroups.indexOf(this);
  52584. if (index > -1) {
  52585. this._scene.animationGroups.splice(index, 1);
  52586. }
  52587. };
  52588. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52589. // animatable should be taken out of the array
  52590. var idx = this._animatables.indexOf(animatable);
  52591. if (idx > -1) {
  52592. this._animatables.splice(idx, 1);
  52593. }
  52594. // all animatables were removed? animation group ended!
  52595. if (this._animatables.length === 0) {
  52596. this._isStarted = false;
  52597. this.onAnimationGroupEndObservable.notifyObservers(this);
  52598. }
  52599. };
  52600. // Statics
  52601. /**
  52602. * Returns a new AnimationGroup object parsed from the source provided.
  52603. * @param parsedAnimationGroup defines the source
  52604. * @param scene defines the scene that will receive the animationGroup
  52605. * @returns a new AnimationGroup
  52606. */
  52607. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52608. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52609. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52610. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52611. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52612. var id = targetedAnimation.targetId;
  52613. var targetNode = scene.getNodeByID(id);
  52614. if (targetNode != null)
  52615. animationGroup.addTargetedAnimation(animation, targetNode);
  52616. }
  52617. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52618. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52619. return animationGroup;
  52620. };
  52621. /**
  52622. * Returns the string "AnimationGroup"
  52623. * @returns "AnimationGroup"
  52624. */
  52625. AnimationGroup.prototype.getClassName = function () {
  52626. return "AnimationGroup";
  52627. };
  52628. /**
  52629. * Creates a detailled string about the object
  52630. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52631. * @returns a string representing the object
  52632. */
  52633. AnimationGroup.prototype.toString = function (fullDetails) {
  52634. var ret = "Name: " + this.name;
  52635. ret += ", type: " + this.getClassName();
  52636. if (fullDetails) {
  52637. ret += ", from: " + this._from;
  52638. ret += ", to: " + this._to;
  52639. ret += ", isStarted: " + this._isStarted;
  52640. ret += ", speedRatio: " + this._speedRatio;
  52641. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52642. ret += ", animatables length: " + this._animatables;
  52643. }
  52644. return ret;
  52645. };
  52646. return AnimationGroup;
  52647. }());
  52648. BABYLON.AnimationGroup = AnimationGroup;
  52649. })(BABYLON || (BABYLON = {}));
  52650. //# sourceMappingURL=babylon.animationGroup.js.map
  52651. var BABYLON;
  52652. (function (BABYLON) {
  52653. // Static values to help the garbage collector
  52654. // Quaternion
  52655. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52656. // Vector3
  52657. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52658. // Vector2
  52659. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52660. // Size
  52661. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52662. // Color3
  52663. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52664. /**
  52665. * Defines a runtime animation
  52666. */
  52667. var RuntimeAnimation = /** @class */ (function () {
  52668. /**
  52669. * Create a new RuntimeAnimation object
  52670. * @param target defines the target of the animation
  52671. * @param animation defines the source animation object
  52672. * @param scene defines the hosting scene
  52673. * @param host defines the initiating Animatable
  52674. */
  52675. function RuntimeAnimation(target, animation, scene, host) {
  52676. var _this = this;
  52677. this._events = new Array();
  52678. /**
  52679. * The current frame of the runtime animation
  52680. */
  52681. this._currentFrame = 0;
  52682. /**
  52683. * The original value of the runtime animation
  52684. */
  52685. this._originalValue = new Array();
  52686. /**
  52687. * The offsets cache of the runtime animation
  52688. */
  52689. this._offsetsCache = {};
  52690. /**
  52691. * The high limits cache of the runtime animation
  52692. */
  52693. this._highLimitsCache = {};
  52694. /**
  52695. * Specifies if the runtime animation has been stopped
  52696. */
  52697. this._stopped = false;
  52698. /**
  52699. * The blending factor of the runtime animation
  52700. */
  52701. this._blendingFactor = 0;
  52702. /**
  52703. * The target path of the runtime animation
  52704. */
  52705. this._targetPath = "";
  52706. /**
  52707. * The weight of the runtime animation
  52708. */
  52709. this._weight = 1.0;
  52710. /**
  52711. * The ratio offset of the runtime animation
  52712. */
  52713. this._ratioOffset = 0;
  52714. /**
  52715. * The previous delay of the runtime animation
  52716. */
  52717. this._previousDelay = 0;
  52718. /**
  52719. * The previous ratio of the runtime animation
  52720. */
  52721. this._previousRatio = 0;
  52722. this._animation = animation;
  52723. this._target = target;
  52724. this._scene = scene;
  52725. this._host = host;
  52726. animation._runtimeAnimations.push(this);
  52727. // Cloning events locally
  52728. var events = animation.getEvents();
  52729. if (events && events.length > 0) {
  52730. events.forEach(function (e) {
  52731. _this._events.push(e._clone());
  52732. });
  52733. }
  52734. }
  52735. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52736. /**
  52737. * Gets the current frame of the runtime animation
  52738. */
  52739. get: function () {
  52740. return this._currentFrame;
  52741. },
  52742. enumerable: true,
  52743. configurable: true
  52744. });
  52745. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52746. /**
  52747. * Gets the weight of the runtime animation
  52748. */
  52749. get: function () {
  52750. return this._weight;
  52751. },
  52752. enumerable: true,
  52753. configurable: true
  52754. });
  52755. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52756. /**
  52757. * Gets the current value of the runtime animation
  52758. */
  52759. get: function () {
  52760. return this._currentValue;
  52761. },
  52762. enumerable: true,
  52763. configurable: true
  52764. });
  52765. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52766. /**
  52767. * Gets the target path of the runtime animation
  52768. */
  52769. get: function () {
  52770. return this._targetPath;
  52771. },
  52772. enumerable: true,
  52773. configurable: true
  52774. });
  52775. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52776. /**
  52777. * Gets the actual target of the runtime animation
  52778. */
  52779. get: function () {
  52780. return this._activeTarget;
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52786. /**
  52787. * Gets the animation from the runtime animation
  52788. */
  52789. get: function () {
  52790. return this._animation;
  52791. },
  52792. enumerable: true,
  52793. configurable: true
  52794. });
  52795. /**
  52796. * Resets the runtime animation to the beginning
  52797. * @param restoreOriginal defines whether to restore the target property to the original value
  52798. */
  52799. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52800. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52801. if (restoreOriginal) {
  52802. if (this._target instanceof Array) {
  52803. var index = 0;
  52804. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52805. var target = _a[_i];
  52806. if (this._originalValue[index] !== undefined) {
  52807. this._setValue(target, this._originalValue[index], -1);
  52808. }
  52809. index++;
  52810. }
  52811. }
  52812. else {
  52813. if (this._originalValue[0] !== undefined) {
  52814. this._setValue(this._target, this._originalValue[0], -1);
  52815. }
  52816. }
  52817. }
  52818. this._offsetsCache = {};
  52819. this._highLimitsCache = {};
  52820. this._currentFrame = 0;
  52821. this._blendingFactor = 0;
  52822. this._originalValue = new Array();
  52823. // Events
  52824. for (var index = 0; index < this._events.length; index++) {
  52825. this._events[index].isDone = false;
  52826. }
  52827. };
  52828. /**
  52829. * Specifies if the runtime animation is stopped
  52830. * @returns Boolean specifying if the runtime animation is stopped
  52831. */
  52832. RuntimeAnimation.prototype.isStopped = function () {
  52833. return this._stopped;
  52834. };
  52835. /**
  52836. * Disposes of the runtime animation
  52837. */
  52838. RuntimeAnimation.prototype.dispose = function () {
  52839. var index = this._animation.runtimeAnimations.indexOf(this);
  52840. if (index > -1) {
  52841. this._animation.runtimeAnimations.splice(index, 1);
  52842. }
  52843. };
  52844. /**
  52845. * Interpolates the animation from the current frame
  52846. * @param currentFrame The frame to interpolate the animation to
  52847. * @param repeatCount The number of times that the animation should loop
  52848. * @param loopMode The type of looping mode to use
  52849. * @param offsetValue Animation offset value
  52850. * @param highLimitValue The high limit value
  52851. * @returns The interpolated value
  52852. */
  52853. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52854. this._currentFrame = currentFrame;
  52855. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52856. this._workValue = BABYLON.Matrix.Zero();
  52857. }
  52858. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52859. };
  52860. /**
  52861. * Apply the interpolated value to the target
  52862. * @param currentValue defines the value computed by the animation
  52863. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52864. */
  52865. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52866. if (weight === void 0) { weight = 1.0; }
  52867. if (this._target instanceof Array) {
  52868. var index = 0;
  52869. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52870. var target = _a[_i];
  52871. this._setValue(target, currentValue, weight, index);
  52872. index++;
  52873. }
  52874. }
  52875. else {
  52876. this._setValue(this._target, currentValue, weight);
  52877. }
  52878. };
  52879. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52880. if (targetIndex === void 0) { targetIndex = 0; }
  52881. // Set value
  52882. var path;
  52883. var destination;
  52884. var targetPropertyPath = this._animation.targetPropertyPath;
  52885. if (targetPropertyPath.length > 1) {
  52886. var property = target[targetPropertyPath[0]];
  52887. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52888. property = property[targetPropertyPath[index]];
  52889. }
  52890. path = targetPropertyPath[targetPropertyPath.length - 1];
  52891. destination = property;
  52892. }
  52893. else {
  52894. path = targetPropertyPath[0];
  52895. destination = target;
  52896. }
  52897. this._targetPath = path;
  52898. this._activeTarget = destination;
  52899. this._weight = weight;
  52900. if (this._originalValue[targetIndex] === undefined) {
  52901. var originalValue = void 0;
  52902. if (destination.getRestPose && path === "_matrix") { // For bones
  52903. originalValue = destination.getRestPose();
  52904. }
  52905. else {
  52906. originalValue = destination[path];
  52907. }
  52908. if (originalValue && originalValue.clone) {
  52909. this._originalValue[targetIndex] = originalValue.clone();
  52910. }
  52911. else {
  52912. this._originalValue[targetIndex] = originalValue;
  52913. }
  52914. }
  52915. // Blending
  52916. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52917. if (enableBlending && this._blendingFactor <= 1.0) {
  52918. if (!this._originalBlendValue) {
  52919. var originalValue = destination[path];
  52920. if (originalValue.clone) {
  52921. this._originalBlendValue = originalValue.clone();
  52922. }
  52923. else {
  52924. this._originalBlendValue = originalValue;
  52925. }
  52926. }
  52927. if (this._originalBlendValue.m) { // Matrix
  52928. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52929. if (this._currentValue) {
  52930. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52931. }
  52932. else {
  52933. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52934. }
  52935. }
  52936. else {
  52937. if (this._currentValue) {
  52938. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52939. }
  52940. else {
  52941. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52942. }
  52943. }
  52944. }
  52945. else {
  52946. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52947. }
  52948. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52949. this._blendingFactor += blendingSpeed;
  52950. }
  52951. else {
  52952. this._currentValue = currentValue;
  52953. }
  52954. if (weight !== -1.0) {
  52955. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52956. }
  52957. else {
  52958. destination[path] = this._currentValue;
  52959. }
  52960. if (target.markAsDirty) {
  52961. target.markAsDirty(this._animation.targetProperty);
  52962. }
  52963. };
  52964. /**
  52965. * Gets the loop pmode of the runtime animation
  52966. * @returns Loop Mode
  52967. */
  52968. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52969. if (this._target && this._target.animationPropertiesOverride) {
  52970. return this._target.animationPropertiesOverride.loopMode;
  52971. }
  52972. return this._animation.loopMode;
  52973. };
  52974. /**
  52975. * Move the current animation to a given frame
  52976. * @param frame defines the frame to move to
  52977. */
  52978. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52979. var keys = this._animation.getKeys();
  52980. if (frame < keys[0].frame) {
  52981. frame = keys[0].frame;
  52982. }
  52983. else if (frame > keys[keys.length - 1].frame) {
  52984. frame = keys[keys.length - 1].frame;
  52985. }
  52986. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52987. this.setValue(currentValue, -1);
  52988. };
  52989. /**
  52990. * @hidden Internal use only
  52991. */
  52992. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52993. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52994. this._ratioOffset = this._previousRatio - newRatio;
  52995. };
  52996. /**
  52997. * Execute the current animation
  52998. * @param delay defines the delay to add to the current frame
  52999. * @param from defines the lower bound of the animation range
  53000. * @param to defines the upper bound of the animation range
  53001. * @param loop defines if the current animation must loop
  53002. * @param speedRatio defines the current speed ratio
  53003. * @param weight defines the weight of the animation (default is -1 so no weight)
  53004. * @returns a boolean indicating if the animation is running
  53005. */
  53006. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53007. if (weight === void 0) { weight = -1.0; }
  53008. var targetPropertyPath = this._animation.targetPropertyPath;
  53009. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53010. this._stopped = true;
  53011. return false;
  53012. }
  53013. var returnValue = true;
  53014. var keys = this._animation.getKeys();
  53015. // Adding a start key at frame 0 if missing
  53016. if (keys[0].frame !== 0) {
  53017. var newKey = { frame: 0, value: keys[0].value };
  53018. keys.splice(0, 0, newKey);
  53019. }
  53020. // Adding a duplicate key when there is only one key at frame zero
  53021. else if (keys.length === 1) {
  53022. var newKey = { frame: 0.001, value: keys[0].value };
  53023. keys.push(newKey);
  53024. }
  53025. // Check limits
  53026. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53027. from = keys[0].frame;
  53028. }
  53029. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53030. to = keys[keys.length - 1].frame;
  53031. }
  53032. //to and from cannot be the same key
  53033. if (from === to) {
  53034. if (from > keys[0].frame) {
  53035. from--;
  53036. }
  53037. else if (to < keys[keys.length - 1].frame) {
  53038. to++;
  53039. }
  53040. }
  53041. // Compute ratio
  53042. var range = to - from;
  53043. var offsetValue;
  53044. // ratio represents the frame delta between from and to
  53045. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53046. var highLimitValue = 0;
  53047. this._previousDelay = delay;
  53048. this._previousRatio = ratio;
  53049. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53050. returnValue = false;
  53051. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53052. }
  53053. else {
  53054. // Get max value if required
  53055. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53056. var keyOffset = to.toString() + from.toString();
  53057. if (!this._offsetsCache[keyOffset]) {
  53058. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53059. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53060. switch (this._animation.dataType) {
  53061. // Float
  53062. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53063. this._offsetsCache[keyOffset] = toValue - fromValue;
  53064. break;
  53065. // Quaternion
  53066. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53067. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53068. break;
  53069. // Vector3
  53070. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53071. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53072. // Vector2
  53073. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53074. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53075. // Size
  53076. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53077. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53078. // Color3
  53079. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53080. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53081. default:
  53082. break;
  53083. }
  53084. this._highLimitsCache[keyOffset] = toValue;
  53085. }
  53086. highLimitValue = this._highLimitsCache[keyOffset];
  53087. offsetValue = this._offsetsCache[keyOffset];
  53088. }
  53089. }
  53090. if (offsetValue === undefined) {
  53091. switch (this._animation.dataType) {
  53092. // Float
  53093. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53094. offsetValue = 0;
  53095. break;
  53096. // Quaternion
  53097. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53098. offsetValue = _staticOffsetValueQuaternion;
  53099. break;
  53100. // Vector3
  53101. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53102. offsetValue = _staticOffsetValueVector3;
  53103. break;
  53104. // Vector2
  53105. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53106. offsetValue = _staticOffsetValueVector2;
  53107. break;
  53108. // Size
  53109. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53110. offsetValue = _staticOffsetValueSize;
  53111. break;
  53112. // Color3
  53113. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53114. offsetValue = _staticOffsetValueColor3;
  53115. }
  53116. }
  53117. // Compute value
  53118. var repeatCount = (ratio / range) >> 0;
  53119. var currentFrame = returnValue ? from + ratio % range : to;
  53120. // Need to normalize?
  53121. if (this._host && this._host.syncRoot) {
  53122. var syncRoot = this._host.syncRoot;
  53123. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53124. currentFrame = from + (to - from) * hostNormalizedFrame;
  53125. }
  53126. // Reset events if looping
  53127. var events = this._events;
  53128. if (range > 0 && this.currentFrame > currentFrame ||
  53129. range < 0 && this.currentFrame < currentFrame) {
  53130. // Need to reset animation events
  53131. for (var index = 0; index < events.length; index++) {
  53132. if (!events[index].onlyOnce) {
  53133. // reset event, the animation is looping
  53134. events[index].isDone = false;
  53135. }
  53136. }
  53137. }
  53138. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53139. // Set value
  53140. this.setValue(currentValue, weight);
  53141. // Check events
  53142. for (var index = 0; index < events.length; index++) {
  53143. // Make sure current frame has passed event frame and that event frame is within the current range
  53144. // Also, handle both forward and reverse animations
  53145. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53146. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53147. var event = events[index];
  53148. if (!event.isDone) {
  53149. // If event should be done only once, remove it.
  53150. if (event.onlyOnce) {
  53151. events.splice(index, 1);
  53152. index--;
  53153. }
  53154. event.isDone = true;
  53155. event.action(currentFrame);
  53156. } // Don't do anything if the event has already be done.
  53157. }
  53158. }
  53159. if (!returnValue) {
  53160. this._stopped = true;
  53161. }
  53162. return returnValue;
  53163. };
  53164. return RuntimeAnimation;
  53165. }());
  53166. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53167. })(BABYLON || (BABYLON = {}));
  53168. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53169. var BABYLON;
  53170. (function (BABYLON) {
  53171. /**
  53172. * Class used to store an actual running animation
  53173. */
  53174. var Animatable = /** @class */ (function () {
  53175. /**
  53176. * Creates a new Animatable
  53177. * @param scene defines the hosting scene
  53178. * @param target defines the target object
  53179. * @param fromFrame defines the starting frame number (default is 0)
  53180. * @param toFrame defines the ending frame number (default is 100)
  53181. * @param loopAnimation defines if the animation must loop (default is false)
  53182. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53183. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53184. * @param animations defines a group of animation to add to the new Animatable
  53185. */
  53186. function Animatable(scene,
  53187. /** defines the target object */
  53188. target,
  53189. /** defines the starting frame number (default is 0) */
  53190. fromFrame,
  53191. /** defines the ending frame number (default is 100) */
  53192. toFrame,
  53193. /** defines if the animation must loop (default is false) */
  53194. loopAnimation, speedRatio,
  53195. /** defines a callback to call when animation ends if it is not looping */
  53196. onAnimationEnd, animations) {
  53197. if (fromFrame === void 0) { fromFrame = 0; }
  53198. if (toFrame === void 0) { toFrame = 100; }
  53199. if (loopAnimation === void 0) { loopAnimation = false; }
  53200. if (speedRatio === void 0) { speedRatio = 1.0; }
  53201. this.target = target;
  53202. this.fromFrame = fromFrame;
  53203. this.toFrame = toFrame;
  53204. this.loopAnimation = loopAnimation;
  53205. this.onAnimationEnd = onAnimationEnd;
  53206. this._localDelayOffset = null;
  53207. this._pausedDelay = null;
  53208. this._runtimeAnimations = new Array();
  53209. this._paused = false;
  53210. this._speedRatio = 1;
  53211. this._weight = -1.0;
  53212. /**
  53213. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53214. * This will only apply for non looping animation (default is true)
  53215. */
  53216. this.disposeOnEnd = true;
  53217. /**
  53218. * Gets a boolean indicating if the animation has started
  53219. */
  53220. this.animationStarted = false;
  53221. /**
  53222. * Observer raised when the animation ends
  53223. */
  53224. this.onAnimationEndObservable = new BABYLON.Observable();
  53225. this._scene = scene;
  53226. if (animations) {
  53227. this.appendAnimations(target, animations);
  53228. }
  53229. this._speedRatio = speedRatio;
  53230. scene._activeAnimatables.push(this);
  53231. }
  53232. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53233. /**
  53234. * Gets the root Animatable used to synchronize and normalize animations
  53235. */
  53236. get: function () {
  53237. return this._syncRoot;
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53243. /**
  53244. * Gets the current frame of the first RuntimeAnimation
  53245. * Used to synchronize Animatables
  53246. */
  53247. get: function () {
  53248. if (this._runtimeAnimations.length === 0) {
  53249. return 0;
  53250. }
  53251. return this._runtimeAnimations[0].currentFrame;
  53252. },
  53253. enumerable: true,
  53254. configurable: true
  53255. });
  53256. Object.defineProperty(Animatable.prototype, "weight", {
  53257. /**
  53258. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53259. */
  53260. get: function () {
  53261. return this._weight;
  53262. },
  53263. set: function (value) {
  53264. if (value === -1) { // -1 is ok and means no weight
  53265. this._weight = -1;
  53266. return;
  53267. }
  53268. // Else weight must be in [0, 1] range
  53269. this._weight = Math.min(Math.max(value, 0), 1.0);
  53270. },
  53271. enumerable: true,
  53272. configurable: true
  53273. });
  53274. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53275. /**
  53276. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53277. */
  53278. get: function () {
  53279. return this._speedRatio;
  53280. },
  53281. set: function (value) {
  53282. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53283. var animation = this._runtimeAnimations[index];
  53284. animation._prepareForSpeedRatioChange(value);
  53285. }
  53286. this._speedRatio = value;
  53287. },
  53288. enumerable: true,
  53289. configurable: true
  53290. });
  53291. // Methods
  53292. /**
  53293. * Synchronize and normalize current Animatable with a source Animatable
  53294. * This is useful when using animation weights and when animations are not of the same length
  53295. * @param root defines the root Animatable to synchronize with
  53296. * @returns the current Animatable
  53297. */
  53298. Animatable.prototype.syncWith = function (root) {
  53299. this._syncRoot = root;
  53300. if (root) {
  53301. // Make sure this animatable will animate after the root
  53302. var index = this._scene._activeAnimatables.indexOf(this);
  53303. if (index > -1) {
  53304. this._scene._activeAnimatables.splice(index, 1);
  53305. this._scene._activeAnimatables.push(this);
  53306. }
  53307. }
  53308. return this;
  53309. };
  53310. /**
  53311. * Gets the list of runtime animations
  53312. * @returns an array of RuntimeAnimation
  53313. */
  53314. Animatable.prototype.getAnimations = function () {
  53315. return this._runtimeAnimations;
  53316. };
  53317. /**
  53318. * Adds more animations to the current animatable
  53319. * @param target defines the target of the animations
  53320. * @param animations defines the new animations to add
  53321. */
  53322. Animatable.prototype.appendAnimations = function (target, animations) {
  53323. for (var index = 0; index < animations.length; index++) {
  53324. var animation = animations[index];
  53325. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53326. }
  53327. };
  53328. /**
  53329. * Gets the source animation for a specific property
  53330. * @param property defines the propertyu to look for
  53331. * @returns null or the source animation for the given property
  53332. */
  53333. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53334. var runtimeAnimations = this._runtimeAnimations;
  53335. for (var index = 0; index < runtimeAnimations.length; index++) {
  53336. if (runtimeAnimations[index].animation.targetProperty === property) {
  53337. return runtimeAnimations[index].animation;
  53338. }
  53339. }
  53340. return null;
  53341. };
  53342. /**
  53343. * Gets the runtime animation for a specific property
  53344. * @param property defines the propertyu to look for
  53345. * @returns null or the runtime animation for the given property
  53346. */
  53347. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53348. var runtimeAnimations = this._runtimeAnimations;
  53349. for (var index = 0; index < runtimeAnimations.length; index++) {
  53350. if (runtimeAnimations[index].animation.targetProperty === property) {
  53351. return runtimeAnimations[index];
  53352. }
  53353. }
  53354. return null;
  53355. };
  53356. /**
  53357. * Resets the animatable to its original state
  53358. */
  53359. Animatable.prototype.reset = function () {
  53360. var runtimeAnimations = this._runtimeAnimations;
  53361. for (var index = 0; index < runtimeAnimations.length; index++) {
  53362. runtimeAnimations[index].reset(true);
  53363. }
  53364. this._localDelayOffset = null;
  53365. this._pausedDelay = null;
  53366. };
  53367. /**
  53368. * Allows the animatable to blend with current running animations
  53369. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53370. * @param blendingSpeed defines the blending speed to use
  53371. */
  53372. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53373. var runtimeAnimations = this._runtimeAnimations;
  53374. for (var index = 0; index < runtimeAnimations.length; index++) {
  53375. runtimeAnimations[index].animation.enableBlending = true;
  53376. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53377. }
  53378. };
  53379. /**
  53380. * Disable animation blending
  53381. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53382. */
  53383. Animatable.prototype.disableBlending = function () {
  53384. var runtimeAnimations = this._runtimeAnimations;
  53385. for (var index = 0; index < runtimeAnimations.length; index++) {
  53386. runtimeAnimations[index].animation.enableBlending = false;
  53387. }
  53388. };
  53389. /**
  53390. * Jump directly to a given frame
  53391. * @param frame defines the frame to jump to
  53392. */
  53393. Animatable.prototype.goToFrame = function (frame) {
  53394. var runtimeAnimations = this._runtimeAnimations;
  53395. if (runtimeAnimations[0]) {
  53396. var fps = runtimeAnimations[0].animation.framePerSecond;
  53397. var currentFrame = runtimeAnimations[0].currentFrame;
  53398. var adjustTime = frame - currentFrame;
  53399. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53400. if (this._localDelayOffset === null) {
  53401. this._localDelayOffset = 0;
  53402. }
  53403. this._localDelayOffset -= delay;
  53404. }
  53405. for (var index = 0; index < runtimeAnimations.length; index++) {
  53406. runtimeAnimations[index].goToFrame(frame);
  53407. }
  53408. };
  53409. /**
  53410. * Pause the animation
  53411. */
  53412. Animatable.prototype.pause = function () {
  53413. if (this._paused) {
  53414. return;
  53415. }
  53416. this._paused = true;
  53417. };
  53418. /**
  53419. * Restart the animation
  53420. */
  53421. Animatable.prototype.restart = function () {
  53422. this._paused = false;
  53423. };
  53424. Animatable.prototype._raiseOnAnimationEnd = function () {
  53425. if (this.onAnimationEnd) {
  53426. this.onAnimationEnd();
  53427. }
  53428. this.onAnimationEndObservable.notifyObservers(this);
  53429. };
  53430. /**
  53431. * Stop and delete the current animation
  53432. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53433. * @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)
  53434. */
  53435. Animatable.prototype.stop = function (animationName, targetMask) {
  53436. if (animationName || targetMask) {
  53437. var idx = this._scene._activeAnimatables.indexOf(this);
  53438. if (idx > -1) {
  53439. var runtimeAnimations = this._runtimeAnimations;
  53440. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53441. var runtimeAnimation = runtimeAnimations[index];
  53442. if (animationName && runtimeAnimation.animation.name != animationName) {
  53443. continue;
  53444. }
  53445. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53446. continue;
  53447. }
  53448. runtimeAnimation.dispose();
  53449. runtimeAnimations.splice(index, 1);
  53450. }
  53451. if (runtimeAnimations.length == 0) {
  53452. this._scene._activeAnimatables.splice(idx, 1);
  53453. this._raiseOnAnimationEnd();
  53454. }
  53455. }
  53456. }
  53457. else {
  53458. var index = this._scene._activeAnimatables.indexOf(this);
  53459. if (index > -1) {
  53460. this._scene._activeAnimatables.splice(index, 1);
  53461. var runtimeAnimations = this._runtimeAnimations;
  53462. for (var index = 0; index < runtimeAnimations.length; index++) {
  53463. runtimeAnimations[index].dispose();
  53464. }
  53465. this._raiseOnAnimationEnd();
  53466. }
  53467. }
  53468. };
  53469. /**
  53470. * Wait asynchronously for the animation to end
  53471. * @returns a promise which will be fullfilled when the animation ends
  53472. */
  53473. Animatable.prototype.waitAsync = function () {
  53474. var _this = this;
  53475. return new Promise(function (resolve, reject) {
  53476. _this.onAnimationEndObservable.add(function () {
  53477. resolve(_this);
  53478. }, undefined, undefined, _this, true);
  53479. });
  53480. };
  53481. /** @hidden */
  53482. Animatable.prototype._animate = function (delay) {
  53483. if (this._paused) {
  53484. this.animationStarted = false;
  53485. if (this._pausedDelay === null) {
  53486. this._pausedDelay = delay;
  53487. }
  53488. return true;
  53489. }
  53490. if (this._localDelayOffset === null) {
  53491. this._localDelayOffset = delay;
  53492. this._pausedDelay = null;
  53493. }
  53494. else if (this._pausedDelay !== null) {
  53495. this._localDelayOffset += delay - this._pausedDelay;
  53496. this._pausedDelay = null;
  53497. }
  53498. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53499. return true;
  53500. }
  53501. // Animating
  53502. var running = false;
  53503. var runtimeAnimations = this._runtimeAnimations;
  53504. var index;
  53505. for (index = 0; index < runtimeAnimations.length; index++) {
  53506. var animation = runtimeAnimations[index];
  53507. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53508. running = running || isRunning;
  53509. }
  53510. this.animationStarted = running;
  53511. if (!running) {
  53512. if (this.disposeOnEnd) {
  53513. // Remove from active animatables
  53514. index = this._scene._activeAnimatables.indexOf(this);
  53515. this._scene._activeAnimatables.splice(index, 1);
  53516. // Dispose all runtime animations
  53517. for (index = 0; index < runtimeAnimations.length; index++) {
  53518. runtimeAnimations[index].dispose();
  53519. }
  53520. }
  53521. this._raiseOnAnimationEnd();
  53522. if (this.disposeOnEnd) {
  53523. this.onAnimationEnd = null;
  53524. this.onAnimationEndObservable.clear();
  53525. }
  53526. }
  53527. return running;
  53528. };
  53529. return Animatable;
  53530. }());
  53531. BABYLON.Animatable = Animatable;
  53532. })(BABYLON || (BABYLON = {}));
  53533. //# sourceMappingURL=babylon.animatable.js.map
  53534. var BABYLON;
  53535. (function (BABYLON) {
  53536. /**
  53537. * Base class used for every default easing function.
  53538. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53539. */
  53540. var EasingFunction = /** @class */ (function () {
  53541. function EasingFunction() {
  53542. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53543. }
  53544. /**
  53545. * Sets the easing mode of the current function.
  53546. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53547. */
  53548. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53549. var n = Math.min(Math.max(easingMode, 0), 2);
  53550. this._easingMode = n;
  53551. };
  53552. /**
  53553. * Gets the current easing mode.
  53554. * @returns the easing mode
  53555. */
  53556. EasingFunction.prototype.getEasingMode = function () {
  53557. return this._easingMode;
  53558. };
  53559. /**
  53560. * @hidden
  53561. */
  53562. EasingFunction.prototype.easeInCore = function (gradient) {
  53563. throw new Error('You must implement this method');
  53564. };
  53565. /**
  53566. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53567. * of the easing function.
  53568. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53569. * @returns the corresponding value on the curve defined by the easing function
  53570. */
  53571. EasingFunction.prototype.ease = function (gradient) {
  53572. switch (this._easingMode) {
  53573. case EasingFunction.EASINGMODE_EASEIN:
  53574. return this.easeInCore(gradient);
  53575. case EasingFunction.EASINGMODE_EASEOUT:
  53576. return (1 - this.easeInCore(1 - gradient));
  53577. }
  53578. if (gradient >= 0.5) {
  53579. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53580. }
  53581. return (this.easeInCore(gradient * 2) * 0.5);
  53582. };
  53583. /**
  53584. * Interpolation follows the mathematical formula associated with the easing function.
  53585. */
  53586. EasingFunction.EASINGMODE_EASEIN = 0;
  53587. /**
  53588. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53589. */
  53590. EasingFunction.EASINGMODE_EASEOUT = 1;
  53591. /**
  53592. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53593. */
  53594. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53595. return EasingFunction;
  53596. }());
  53597. BABYLON.EasingFunction = EasingFunction;
  53598. /**
  53599. * Easing function with a circle shape (see link below).
  53600. * @see https://easings.net/#easeInCirc
  53601. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53602. */
  53603. var CircleEase = /** @class */ (function (_super) {
  53604. __extends(CircleEase, _super);
  53605. function CircleEase() {
  53606. return _super !== null && _super.apply(this, arguments) || this;
  53607. }
  53608. /** @hidden */
  53609. CircleEase.prototype.easeInCore = function (gradient) {
  53610. gradient = Math.max(0, Math.min(1, gradient));
  53611. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53612. };
  53613. return CircleEase;
  53614. }(EasingFunction));
  53615. BABYLON.CircleEase = CircleEase;
  53616. /**
  53617. * Easing function with a ease back shape (see link below).
  53618. * @see https://easings.net/#easeInBack
  53619. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53620. */
  53621. var BackEase = /** @class */ (function (_super) {
  53622. __extends(BackEase, _super);
  53623. /**
  53624. * Instantiates a back ease easing
  53625. * @see https://easings.net/#easeInBack
  53626. * @param amplitude Defines the amplitude of the function
  53627. */
  53628. function BackEase(
  53629. /** Defines the amplitude of the function */
  53630. amplitude) {
  53631. if (amplitude === void 0) { amplitude = 1; }
  53632. var _this = _super.call(this) || this;
  53633. _this.amplitude = amplitude;
  53634. return _this;
  53635. }
  53636. /** @hidden */
  53637. BackEase.prototype.easeInCore = function (gradient) {
  53638. var num = Math.max(0, this.amplitude);
  53639. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53640. };
  53641. return BackEase;
  53642. }(EasingFunction));
  53643. BABYLON.BackEase = BackEase;
  53644. /**
  53645. * Easing function with a bouncing shape (see link below).
  53646. * @see https://easings.net/#easeInBounce
  53647. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53648. */
  53649. var BounceEase = /** @class */ (function (_super) {
  53650. __extends(BounceEase, _super);
  53651. /**
  53652. * Instantiates a bounce easing
  53653. * @see https://easings.net/#easeInBounce
  53654. * @param bounces Defines the number of bounces
  53655. * @param bounciness Defines the amplitude of the bounce
  53656. */
  53657. function BounceEase(
  53658. /** Defines the number of bounces */
  53659. bounces,
  53660. /** Defines the amplitude of the bounce */
  53661. bounciness) {
  53662. if (bounces === void 0) { bounces = 3; }
  53663. if (bounciness === void 0) { bounciness = 2; }
  53664. var _this = _super.call(this) || this;
  53665. _this.bounces = bounces;
  53666. _this.bounciness = bounciness;
  53667. return _this;
  53668. }
  53669. /** @hidden */
  53670. BounceEase.prototype.easeInCore = function (gradient) {
  53671. var y = Math.max(0.0, this.bounces);
  53672. var bounciness = this.bounciness;
  53673. if (bounciness <= 1.0) {
  53674. bounciness = 1.001;
  53675. }
  53676. var num9 = Math.pow(bounciness, y);
  53677. var num5 = 1.0 - bounciness;
  53678. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53679. var num15 = gradient * num4;
  53680. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53681. var num3 = Math.floor(num65);
  53682. var num13 = num3 + 1.0;
  53683. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53684. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53685. var num7 = (num8 + num12) * 0.5;
  53686. var num6 = gradient - num7;
  53687. var num2 = num7 - num8;
  53688. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53689. };
  53690. return BounceEase;
  53691. }(EasingFunction));
  53692. BABYLON.BounceEase = BounceEase;
  53693. /**
  53694. * Easing function with a power of 3 shape (see link below).
  53695. * @see https://easings.net/#easeInCubic
  53696. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53697. */
  53698. var CubicEase = /** @class */ (function (_super) {
  53699. __extends(CubicEase, _super);
  53700. function CubicEase() {
  53701. return _super !== null && _super.apply(this, arguments) || this;
  53702. }
  53703. /** @hidden */
  53704. CubicEase.prototype.easeInCore = function (gradient) {
  53705. return (gradient * gradient * gradient);
  53706. };
  53707. return CubicEase;
  53708. }(EasingFunction));
  53709. BABYLON.CubicEase = CubicEase;
  53710. /**
  53711. * Easing function with an elastic shape (see link below).
  53712. * @see https://easings.net/#easeInElastic
  53713. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53714. */
  53715. var ElasticEase = /** @class */ (function (_super) {
  53716. __extends(ElasticEase, _super);
  53717. /**
  53718. * Instantiates an elastic easing function
  53719. * @see https://easings.net/#easeInElastic
  53720. * @param oscillations Defines the number of oscillations
  53721. * @param springiness Defines the amplitude of the oscillations
  53722. */
  53723. function ElasticEase(
  53724. /** Defines the number of oscillations*/
  53725. oscillations,
  53726. /** Defines the amplitude of the oscillations*/
  53727. springiness) {
  53728. if (oscillations === void 0) { oscillations = 3; }
  53729. if (springiness === void 0) { springiness = 3; }
  53730. var _this = _super.call(this) || this;
  53731. _this.oscillations = oscillations;
  53732. _this.springiness = springiness;
  53733. return _this;
  53734. }
  53735. /** @hidden */
  53736. ElasticEase.prototype.easeInCore = function (gradient) {
  53737. var num2;
  53738. var num3 = Math.max(0.0, this.oscillations);
  53739. var num = Math.max(0.0, this.springiness);
  53740. if (num == 0) {
  53741. num2 = gradient;
  53742. }
  53743. else {
  53744. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53745. }
  53746. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53747. };
  53748. return ElasticEase;
  53749. }(EasingFunction));
  53750. BABYLON.ElasticEase = ElasticEase;
  53751. /**
  53752. * Easing function with an exponential shape (see link below).
  53753. * @see https://easings.net/#easeInExpo
  53754. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53755. */
  53756. var ExponentialEase = /** @class */ (function (_super) {
  53757. __extends(ExponentialEase, _super);
  53758. /**
  53759. * Instantiates an exponential easing function
  53760. * @see https://easings.net/#easeInExpo
  53761. * @param exponent Defines the exponent of the function
  53762. */
  53763. function ExponentialEase(
  53764. /** Defines the exponent of the function */
  53765. exponent) {
  53766. if (exponent === void 0) { exponent = 2; }
  53767. var _this = _super.call(this) || this;
  53768. _this.exponent = exponent;
  53769. return _this;
  53770. }
  53771. /** @hidden */
  53772. ExponentialEase.prototype.easeInCore = function (gradient) {
  53773. if (this.exponent <= 0) {
  53774. return gradient;
  53775. }
  53776. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53777. };
  53778. return ExponentialEase;
  53779. }(EasingFunction));
  53780. BABYLON.ExponentialEase = ExponentialEase;
  53781. /**
  53782. * Easing function with a power shape (see link below).
  53783. * @see https://easings.net/#easeInQuad
  53784. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53785. */
  53786. var PowerEase = /** @class */ (function (_super) {
  53787. __extends(PowerEase, _super);
  53788. /**
  53789. * Instantiates an power base easing function
  53790. * @see https://easings.net/#easeInQuad
  53791. * @param power Defines the power of the function
  53792. */
  53793. function PowerEase(
  53794. /** Defines the power of the function */
  53795. power) {
  53796. if (power === void 0) { power = 2; }
  53797. var _this = _super.call(this) || this;
  53798. _this.power = power;
  53799. return _this;
  53800. }
  53801. /** @hidden */
  53802. PowerEase.prototype.easeInCore = function (gradient) {
  53803. var y = Math.max(0.0, this.power);
  53804. return Math.pow(gradient, y);
  53805. };
  53806. return PowerEase;
  53807. }(EasingFunction));
  53808. BABYLON.PowerEase = PowerEase;
  53809. /**
  53810. * Easing function with a power of 2 shape (see link below).
  53811. * @see https://easings.net/#easeInQuad
  53812. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53813. */
  53814. var QuadraticEase = /** @class */ (function (_super) {
  53815. __extends(QuadraticEase, _super);
  53816. function QuadraticEase() {
  53817. return _super !== null && _super.apply(this, arguments) || this;
  53818. }
  53819. /** @hidden */
  53820. QuadraticEase.prototype.easeInCore = function (gradient) {
  53821. return (gradient * gradient);
  53822. };
  53823. return QuadraticEase;
  53824. }(EasingFunction));
  53825. BABYLON.QuadraticEase = QuadraticEase;
  53826. /**
  53827. * Easing function with a power of 4 shape (see link below).
  53828. * @see https://easings.net/#easeInQuart
  53829. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53830. */
  53831. var QuarticEase = /** @class */ (function (_super) {
  53832. __extends(QuarticEase, _super);
  53833. function QuarticEase() {
  53834. return _super !== null && _super.apply(this, arguments) || this;
  53835. }
  53836. /** @hidden */
  53837. QuarticEase.prototype.easeInCore = function (gradient) {
  53838. return (gradient * gradient * gradient * gradient);
  53839. };
  53840. return QuarticEase;
  53841. }(EasingFunction));
  53842. BABYLON.QuarticEase = QuarticEase;
  53843. /**
  53844. * Easing function with a power of 5 shape (see link below).
  53845. * @see https://easings.net/#easeInQuint
  53846. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53847. */
  53848. var QuinticEase = /** @class */ (function (_super) {
  53849. __extends(QuinticEase, _super);
  53850. function QuinticEase() {
  53851. return _super !== null && _super.apply(this, arguments) || this;
  53852. }
  53853. /** @hidden */
  53854. QuinticEase.prototype.easeInCore = function (gradient) {
  53855. return (gradient * gradient * gradient * gradient * gradient);
  53856. };
  53857. return QuinticEase;
  53858. }(EasingFunction));
  53859. BABYLON.QuinticEase = QuinticEase;
  53860. /**
  53861. * Easing function with a sin shape (see link below).
  53862. * @see https://easings.net/#easeInSine
  53863. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53864. */
  53865. var SineEase = /** @class */ (function (_super) {
  53866. __extends(SineEase, _super);
  53867. function SineEase() {
  53868. return _super !== null && _super.apply(this, arguments) || this;
  53869. }
  53870. /** @hidden */
  53871. SineEase.prototype.easeInCore = function (gradient) {
  53872. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53873. };
  53874. return SineEase;
  53875. }(EasingFunction));
  53876. BABYLON.SineEase = SineEase;
  53877. /**
  53878. * Easing function with a bezier shape (see link below).
  53879. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53880. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53881. */
  53882. var BezierCurveEase = /** @class */ (function (_super) {
  53883. __extends(BezierCurveEase, _super);
  53884. /**
  53885. * Instantiates a bezier function
  53886. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53887. * @param x1 Defines the x component of the start tangent in the bezier curve
  53888. * @param y1 Defines the y component of the start tangent in the bezier curve
  53889. * @param x2 Defines the x component of the end tangent in the bezier curve
  53890. * @param y2 Defines the y component of the end tangent in the bezier curve
  53891. */
  53892. function BezierCurveEase(
  53893. /** Defines the x component of the start tangent in the bezier curve */
  53894. x1,
  53895. /** Defines the y component of the start tangent in the bezier curve */
  53896. y1,
  53897. /** Defines the x component of the end tangent in the bezier curve */
  53898. x2,
  53899. /** Defines the y component of the end tangent in the bezier curve */
  53900. y2) {
  53901. if (x1 === void 0) { x1 = 0; }
  53902. if (y1 === void 0) { y1 = 0; }
  53903. if (x2 === void 0) { x2 = 1; }
  53904. if (y2 === void 0) { y2 = 1; }
  53905. var _this = _super.call(this) || this;
  53906. _this.x1 = x1;
  53907. _this.y1 = y1;
  53908. _this.x2 = x2;
  53909. _this.y2 = y2;
  53910. return _this;
  53911. }
  53912. /** @hidden */
  53913. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53914. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53915. };
  53916. return BezierCurveEase;
  53917. }(EasingFunction));
  53918. BABYLON.BezierCurveEase = BezierCurveEase;
  53919. })(BABYLON || (BABYLON = {}));
  53920. //# sourceMappingURL=babylon.easing.js.map
  53921. var BABYLON;
  53922. (function (BABYLON) {
  53923. /**
  53924. * A Condition applied to an Action
  53925. */
  53926. var Condition = /** @class */ (function () {
  53927. /**
  53928. * Creates a new Condition
  53929. * @param actionManager the manager of the action the condition is applied to
  53930. */
  53931. function Condition(actionManager) {
  53932. this._actionManager = actionManager;
  53933. }
  53934. /**
  53935. * Check if the current condition is valid
  53936. * @returns a boolean
  53937. */
  53938. Condition.prototype.isValid = function () {
  53939. return true;
  53940. };
  53941. /**
  53942. * Internal only
  53943. * @hidden
  53944. */
  53945. Condition.prototype._getProperty = function (propertyPath) {
  53946. return this._actionManager._getProperty(propertyPath);
  53947. };
  53948. /**
  53949. * Internal only
  53950. * @hidden
  53951. */
  53952. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53953. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53954. };
  53955. /**
  53956. * Serialize placeholder for child classes
  53957. * @returns the serialized object
  53958. */
  53959. Condition.prototype.serialize = function () {
  53960. };
  53961. /**
  53962. * Internal only
  53963. * @hidden
  53964. */
  53965. Condition.prototype._serialize = function (serializedCondition) {
  53966. return {
  53967. type: 2,
  53968. children: [],
  53969. name: serializedCondition.name,
  53970. properties: serializedCondition.properties
  53971. };
  53972. };
  53973. return Condition;
  53974. }());
  53975. BABYLON.Condition = Condition;
  53976. /**
  53977. * Defines specific conditional operators as extensions of Condition
  53978. */
  53979. var ValueCondition = /** @class */ (function (_super) {
  53980. __extends(ValueCondition, _super);
  53981. /**
  53982. * Creates a new ValueCondition
  53983. * @param actionManager manager for the action the condition applies to
  53984. * @param target for the action
  53985. * @param propertyPath path to specify the property of the target the conditional operator uses
  53986. * @param value the value compared by the conditional operator against the current value of the property
  53987. * @param operator the conditional operator, default ValueCondition.IsEqual
  53988. */
  53989. function ValueCondition(actionManager, target,
  53990. /** path to specify the property of the target the conditional operator uses */
  53991. propertyPath,
  53992. /** the value compared by the conditional operator against the current value of the property */
  53993. value,
  53994. /** the conditional operator, default ValueCondition.IsEqual */
  53995. operator) {
  53996. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53997. var _this = _super.call(this, actionManager) || this;
  53998. _this.propertyPath = propertyPath;
  53999. _this.value = value;
  54000. _this.operator = operator;
  54001. _this._target = target;
  54002. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54003. _this._property = _this._getProperty(_this.propertyPath);
  54004. return _this;
  54005. }
  54006. Object.defineProperty(ValueCondition, "IsEqual", {
  54007. /**
  54008. * returns the number for IsEqual
  54009. */
  54010. get: function () {
  54011. return ValueCondition._IsEqual;
  54012. },
  54013. enumerable: true,
  54014. configurable: true
  54015. });
  54016. Object.defineProperty(ValueCondition, "IsDifferent", {
  54017. /**
  54018. * Returns the number for IsDifferent
  54019. */
  54020. get: function () {
  54021. return ValueCondition._IsDifferent;
  54022. },
  54023. enumerable: true,
  54024. configurable: true
  54025. });
  54026. Object.defineProperty(ValueCondition, "IsGreater", {
  54027. /**
  54028. * Returns the number for IsGreater
  54029. */
  54030. get: function () {
  54031. return ValueCondition._IsGreater;
  54032. },
  54033. enumerable: true,
  54034. configurable: true
  54035. });
  54036. Object.defineProperty(ValueCondition, "IsLesser", {
  54037. /**
  54038. * Returns the number for IsLesser
  54039. */
  54040. get: function () {
  54041. return ValueCondition._IsLesser;
  54042. },
  54043. enumerable: true,
  54044. configurable: true
  54045. });
  54046. /**
  54047. * Compares the given value with the property value for the specified conditional operator
  54048. * @returns the result of the comparison
  54049. */
  54050. ValueCondition.prototype.isValid = function () {
  54051. switch (this.operator) {
  54052. case ValueCondition.IsGreater:
  54053. return this._effectiveTarget[this._property] > this.value;
  54054. case ValueCondition.IsLesser:
  54055. return this._effectiveTarget[this._property] < this.value;
  54056. case ValueCondition.IsEqual:
  54057. case ValueCondition.IsDifferent:
  54058. var check;
  54059. if (this.value.equals) {
  54060. check = this.value.equals(this._effectiveTarget[this._property]);
  54061. }
  54062. else {
  54063. check = this.value === this._effectiveTarget[this._property];
  54064. }
  54065. return this.operator === ValueCondition.IsEqual ? check : !check;
  54066. }
  54067. return false;
  54068. };
  54069. /**
  54070. * Serialize the ValueCondition into a JSON compatible object
  54071. * @returns serialization object
  54072. */
  54073. ValueCondition.prototype.serialize = function () {
  54074. return this._serialize({
  54075. name: "ValueCondition",
  54076. properties: [
  54077. BABYLON.Action._GetTargetProperty(this._target),
  54078. { name: "propertyPath", value: this.propertyPath },
  54079. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54080. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54081. ]
  54082. });
  54083. };
  54084. /**
  54085. * Gets the name of the conditional operator for the ValueCondition
  54086. * @param operator the conditional operator
  54087. * @returns the name
  54088. */
  54089. ValueCondition.GetOperatorName = function (operator) {
  54090. switch (operator) {
  54091. case ValueCondition._IsEqual: return "IsEqual";
  54092. case ValueCondition._IsDifferent: return "IsDifferent";
  54093. case ValueCondition._IsGreater: return "IsGreater";
  54094. case ValueCondition._IsLesser: return "IsLesser";
  54095. default: return "";
  54096. }
  54097. };
  54098. /**
  54099. * Internal only
  54100. * @hidden
  54101. */
  54102. ValueCondition._IsEqual = 0;
  54103. /**
  54104. * Internal only
  54105. * @hidden
  54106. */
  54107. ValueCondition._IsDifferent = 1;
  54108. /**
  54109. * Internal only
  54110. * @hidden
  54111. */
  54112. ValueCondition._IsGreater = 2;
  54113. /**
  54114. * Internal only
  54115. * @hidden
  54116. */
  54117. ValueCondition._IsLesser = 3;
  54118. return ValueCondition;
  54119. }(Condition));
  54120. BABYLON.ValueCondition = ValueCondition;
  54121. /**
  54122. * Defines a predicate condition as an extension of Condition
  54123. */
  54124. var PredicateCondition = /** @class */ (function (_super) {
  54125. __extends(PredicateCondition, _super);
  54126. /**
  54127. * Creates a new PredicateCondition
  54128. * @param actionManager manager for the action the condition applies to
  54129. * @param predicate defines the predicate function used to validate the condition
  54130. */
  54131. function PredicateCondition(actionManager,
  54132. /** defines the predicate function used to validate the condition */
  54133. predicate) {
  54134. var _this = _super.call(this, actionManager) || this;
  54135. _this.predicate = predicate;
  54136. return _this;
  54137. }
  54138. /**
  54139. * @returns the validity of the predicate condition
  54140. */
  54141. PredicateCondition.prototype.isValid = function () {
  54142. return this.predicate();
  54143. };
  54144. return PredicateCondition;
  54145. }(Condition));
  54146. BABYLON.PredicateCondition = PredicateCondition;
  54147. /**
  54148. * Defines a state condition as an extension of Condition
  54149. */
  54150. var StateCondition = /** @class */ (function (_super) {
  54151. __extends(StateCondition, _super);
  54152. /**
  54153. * Creates a new StateCondition
  54154. * @param actionManager manager for the action the condition applies to
  54155. * @param target of the condition
  54156. * @param value to compare with target state
  54157. */
  54158. function StateCondition(actionManager, target, value) {
  54159. var _this = _super.call(this, actionManager) || this;
  54160. _this.value = value;
  54161. _this._target = target;
  54162. return _this;
  54163. }
  54164. /**
  54165. * @returns the validity of the state
  54166. */
  54167. StateCondition.prototype.isValid = function () {
  54168. return this._target.state === this.value;
  54169. };
  54170. /**
  54171. * Serialize the StateCondition into a JSON compatible object
  54172. * @returns serialization object
  54173. */
  54174. StateCondition.prototype.serialize = function () {
  54175. return this._serialize({
  54176. name: "StateCondition",
  54177. properties: [
  54178. BABYLON.Action._GetTargetProperty(this._target),
  54179. { name: "value", value: this.value }
  54180. ]
  54181. });
  54182. };
  54183. return StateCondition;
  54184. }(Condition));
  54185. BABYLON.StateCondition = StateCondition;
  54186. })(BABYLON || (BABYLON = {}));
  54187. //# sourceMappingURL=babylon.condition.js.map
  54188. var BABYLON;
  54189. (function (BABYLON) {
  54190. /**
  54191. * The action to be carried out following a trigger
  54192. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54193. */
  54194. var Action = /** @class */ (function () {
  54195. /**
  54196. * Creates a new Action
  54197. * @param triggerOptions the trigger, with or without parameters, for the action
  54198. * @param condition an optional determinant of action
  54199. */
  54200. function Action(
  54201. /** the trigger, with or without parameters, for the action */
  54202. triggerOptions, condition) {
  54203. this.triggerOptions = triggerOptions;
  54204. /**
  54205. * An event triggered prior to action being executed.
  54206. */
  54207. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54208. if (triggerOptions.parameter) {
  54209. this.trigger = triggerOptions.trigger;
  54210. this._triggerParameter = triggerOptions.parameter;
  54211. }
  54212. else if (triggerOptions.trigger) {
  54213. this.trigger = triggerOptions.trigger;
  54214. }
  54215. else {
  54216. this.trigger = triggerOptions;
  54217. }
  54218. this._nextActiveAction = this;
  54219. this._condition = condition;
  54220. }
  54221. /**
  54222. * Internal only
  54223. * @hidden
  54224. */
  54225. Action.prototype._prepare = function () {
  54226. };
  54227. /**
  54228. * Gets the trigger parameters
  54229. * @returns the trigger parameters
  54230. */
  54231. Action.prototype.getTriggerParameter = function () {
  54232. return this._triggerParameter;
  54233. };
  54234. /**
  54235. * Internal only - executes current action event
  54236. * @hidden
  54237. */
  54238. Action.prototype._executeCurrent = function (evt) {
  54239. if (this._nextActiveAction._condition) {
  54240. var condition = this._nextActiveAction._condition;
  54241. var currentRenderId = this._actionManager.getScene().getRenderId();
  54242. // We cache the current evaluation for the current frame
  54243. if (condition._evaluationId === currentRenderId) {
  54244. if (!condition._currentResult) {
  54245. return;
  54246. }
  54247. }
  54248. else {
  54249. condition._evaluationId = currentRenderId;
  54250. if (!condition.isValid()) {
  54251. condition._currentResult = false;
  54252. return;
  54253. }
  54254. condition._currentResult = true;
  54255. }
  54256. }
  54257. this.onBeforeExecuteObservable.notifyObservers(this);
  54258. this._nextActiveAction.execute(evt);
  54259. this.skipToNextActiveAction();
  54260. };
  54261. /**
  54262. * Execute placeholder for child classes
  54263. * @param evt optional action event
  54264. */
  54265. Action.prototype.execute = function (evt) {
  54266. };
  54267. /**
  54268. * Skips to next active action
  54269. */
  54270. Action.prototype.skipToNextActiveAction = function () {
  54271. if (this._nextActiveAction._child) {
  54272. if (!this._nextActiveAction._child._actionManager) {
  54273. this._nextActiveAction._child._actionManager = this._actionManager;
  54274. }
  54275. this._nextActiveAction = this._nextActiveAction._child;
  54276. }
  54277. else {
  54278. this._nextActiveAction = this;
  54279. }
  54280. };
  54281. /**
  54282. * Adds action to chain of actions, may be a DoNothingAction
  54283. * @param action defines the next action to execute
  54284. * @returns The action passed in
  54285. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54286. */
  54287. Action.prototype.then = function (action) {
  54288. this._child = action;
  54289. action._actionManager = this._actionManager;
  54290. action._prepare();
  54291. return action;
  54292. };
  54293. /**
  54294. * Internal only
  54295. * @hidden
  54296. */
  54297. Action.prototype._getProperty = function (propertyPath) {
  54298. return this._actionManager._getProperty(propertyPath);
  54299. };
  54300. /**
  54301. * Internal only
  54302. * @hidden
  54303. */
  54304. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54305. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54306. };
  54307. /**
  54308. * Serialize placeholder for child classes
  54309. * @param parent of child
  54310. * @returns the serialized object
  54311. */
  54312. Action.prototype.serialize = function (parent) {
  54313. };
  54314. /**
  54315. * Internal only called by serialize
  54316. * @hidden
  54317. */
  54318. Action.prototype._serialize = function (serializedAction, parent) {
  54319. var serializationObject = {
  54320. type: 1,
  54321. children: [],
  54322. name: serializedAction.name,
  54323. properties: serializedAction.properties || []
  54324. };
  54325. // Serialize child
  54326. if (this._child) {
  54327. this._child.serialize(serializationObject);
  54328. }
  54329. // Check if "this" has a condition
  54330. if (this._condition) {
  54331. var serializedCondition = this._condition.serialize();
  54332. serializedCondition.children.push(serializationObject);
  54333. if (parent) {
  54334. parent.children.push(serializedCondition);
  54335. }
  54336. return serializedCondition;
  54337. }
  54338. if (parent) {
  54339. parent.children.push(serializationObject);
  54340. }
  54341. return serializationObject;
  54342. };
  54343. /**
  54344. * Internal only
  54345. * @hidden
  54346. */
  54347. Action._SerializeValueAsString = function (value) {
  54348. if (typeof value === "number") {
  54349. return value.toString();
  54350. }
  54351. if (typeof value === "boolean") {
  54352. return value ? "true" : "false";
  54353. }
  54354. if (value instanceof BABYLON.Vector2) {
  54355. return value.x + ", " + value.y;
  54356. }
  54357. if (value instanceof BABYLON.Vector3) {
  54358. return value.x + ", " + value.y + ", " + value.z;
  54359. }
  54360. if (value instanceof BABYLON.Color3) {
  54361. return value.r + ", " + value.g + ", " + value.b;
  54362. }
  54363. if (value instanceof BABYLON.Color4) {
  54364. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54365. }
  54366. return value; // string
  54367. };
  54368. /**
  54369. * Internal only
  54370. * @hidden
  54371. */
  54372. Action._GetTargetProperty = function (target) {
  54373. return {
  54374. name: "target",
  54375. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54376. : target instanceof BABYLON.Light ? "LightProperties"
  54377. : target instanceof BABYLON.Camera ? "CameraProperties"
  54378. : "SceneProperties",
  54379. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54380. };
  54381. };
  54382. return Action;
  54383. }());
  54384. BABYLON.Action = Action;
  54385. })(BABYLON || (BABYLON = {}));
  54386. //# sourceMappingURL=babylon.action.js.map
  54387. var BABYLON;
  54388. (function (BABYLON) {
  54389. /**
  54390. * ActionEvent is the event being sent when an action is triggered.
  54391. */
  54392. var ActionEvent = /** @class */ (function () {
  54393. /**
  54394. * Creates a new ActionEvent
  54395. * @param source The mesh or sprite that triggered the action
  54396. * @param pointerX The X mouse cursor position at the time of the event
  54397. * @param pointerY The Y mouse cursor position at the time of the event
  54398. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54399. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54400. * @param additionalData additional data for the event
  54401. */
  54402. function ActionEvent(
  54403. /** The mesh or sprite that triggered the action */
  54404. source,
  54405. /** The X mouse cursor position at the time of the event */
  54406. pointerX,
  54407. /** The Y mouse cursor position at the time of the event */
  54408. pointerY,
  54409. /** The mesh that is currently pointed at (can be null) */
  54410. meshUnderPointer,
  54411. /** the original (browser) event that triggered the ActionEvent */
  54412. sourceEvent,
  54413. /** additional data for the event */
  54414. additionalData) {
  54415. this.source = source;
  54416. this.pointerX = pointerX;
  54417. this.pointerY = pointerY;
  54418. this.meshUnderPointer = meshUnderPointer;
  54419. this.sourceEvent = sourceEvent;
  54420. this.additionalData = additionalData;
  54421. }
  54422. /**
  54423. * Helper function to auto-create an ActionEvent from a source mesh.
  54424. * @param source The source mesh that triggered the event
  54425. * @param evt The original (browser) event
  54426. * @param additionalData additional data for the event
  54427. * @returns the new ActionEvent
  54428. */
  54429. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54430. var scene = source.getScene();
  54431. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54432. };
  54433. /**
  54434. * Helper function to auto-create an ActionEvent from a source sprite
  54435. * @param source The source sprite that triggered the event
  54436. * @param scene Scene associated with the sprite
  54437. * @param evt The original (browser) event
  54438. * @param additionalData additional data for the event
  54439. * @returns the new ActionEvent
  54440. */
  54441. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54442. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54443. };
  54444. /**
  54445. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54446. * @param scene the scene where the event occurred
  54447. * @param evt The original (browser) event
  54448. * @returns the new ActionEvent
  54449. */
  54450. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54451. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54452. };
  54453. /**
  54454. * Helper function to auto-create an ActionEvent from a primitive
  54455. * @param prim defines the target primitive
  54456. * @param pointerPos defines the pointer position
  54457. * @param evt The original (browser) event
  54458. * @param additionalData additional data for the event
  54459. * @returns the new ActionEvent
  54460. */
  54461. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54462. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54463. };
  54464. return ActionEvent;
  54465. }());
  54466. BABYLON.ActionEvent = ActionEvent;
  54467. /**
  54468. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54469. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54470. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54471. */
  54472. var ActionManager = /** @class */ (function () {
  54473. /**
  54474. * Creates a new action manager
  54475. * @param scene defines the hosting scene
  54476. */
  54477. function ActionManager(scene) {
  54478. // Members
  54479. /** Gets the list of actions */
  54480. this.actions = new Array();
  54481. /** Gets the cursor to use when hovering items */
  54482. this.hoverCursor = '';
  54483. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54484. scene.actionManagers.push(this);
  54485. }
  54486. // Methods
  54487. /**
  54488. * Releases all associated resources
  54489. */
  54490. ActionManager.prototype.dispose = function () {
  54491. var index = this._scene.actionManagers.indexOf(this);
  54492. for (var i = 0; i < this.actions.length; i++) {
  54493. var action = this.actions[i];
  54494. ActionManager.Triggers[action.trigger]--;
  54495. if (ActionManager.Triggers[action.trigger] === 0) {
  54496. delete ActionManager.Triggers[action.trigger];
  54497. }
  54498. }
  54499. if (index > -1) {
  54500. this._scene.actionManagers.splice(index, 1);
  54501. }
  54502. };
  54503. /**
  54504. * Gets hosting scene
  54505. * @returns the hosting scene
  54506. */
  54507. ActionManager.prototype.getScene = function () {
  54508. return this._scene;
  54509. };
  54510. /**
  54511. * Does this action manager handles actions of any of the given triggers
  54512. * @param triggers defines the triggers to be tested
  54513. * @return a boolean indicating whether one (or more) of the triggers is handled
  54514. */
  54515. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54516. for (var index = 0; index < this.actions.length; index++) {
  54517. var action = this.actions[index];
  54518. if (triggers.indexOf(action.trigger) > -1) {
  54519. return true;
  54520. }
  54521. }
  54522. return false;
  54523. };
  54524. /**
  54525. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54526. * speed.
  54527. * @param triggerA defines the trigger to be tested
  54528. * @param triggerB defines the trigger to be tested
  54529. * @return a boolean indicating whether one (or more) of the triggers is handled
  54530. */
  54531. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54532. for (var index = 0; index < this.actions.length; index++) {
  54533. var action = this.actions[index];
  54534. if (triggerA == action.trigger || triggerB == action.trigger) {
  54535. return true;
  54536. }
  54537. }
  54538. return false;
  54539. };
  54540. /**
  54541. * Does this action manager handles actions of a given trigger
  54542. * @param trigger defines the trigger to be tested
  54543. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54544. * @return whether the trigger is handled
  54545. */
  54546. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54547. for (var index = 0; index < this.actions.length; index++) {
  54548. var action = this.actions[index];
  54549. if (action.trigger === trigger) {
  54550. if (parameterPredicate) {
  54551. if (parameterPredicate(action.getTriggerParameter())) {
  54552. return true;
  54553. }
  54554. }
  54555. else {
  54556. return true;
  54557. }
  54558. }
  54559. }
  54560. return false;
  54561. };
  54562. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54563. /**
  54564. * Does this action manager has pointer triggers
  54565. */
  54566. get: function () {
  54567. for (var index = 0; index < this.actions.length; index++) {
  54568. var action = this.actions[index];
  54569. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54570. return true;
  54571. }
  54572. }
  54573. return false;
  54574. },
  54575. enumerable: true,
  54576. configurable: true
  54577. });
  54578. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54579. /**
  54580. * Does this action manager has pick triggers
  54581. */
  54582. get: function () {
  54583. for (var index = 0; index < this.actions.length; index++) {
  54584. var action = this.actions[index];
  54585. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54586. return true;
  54587. }
  54588. }
  54589. return false;
  54590. },
  54591. enumerable: true,
  54592. configurable: true
  54593. });
  54594. Object.defineProperty(ActionManager, "HasTriggers", {
  54595. /**
  54596. * Does exist one action manager with at least one trigger
  54597. **/
  54598. get: function () {
  54599. for (var t in ActionManager.Triggers) {
  54600. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54601. return true;
  54602. }
  54603. }
  54604. return false;
  54605. },
  54606. enumerable: true,
  54607. configurable: true
  54608. });
  54609. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54610. /**
  54611. * Does exist one action manager with at least one pick trigger
  54612. **/
  54613. get: function () {
  54614. for (var t in ActionManager.Triggers) {
  54615. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54616. var t_int = parseInt(t);
  54617. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54618. return true;
  54619. }
  54620. }
  54621. }
  54622. return false;
  54623. },
  54624. enumerable: true,
  54625. configurable: true
  54626. });
  54627. /**
  54628. * Does exist one action manager that handles actions of a given trigger
  54629. * @param trigger defines the trigger to be tested
  54630. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54631. **/
  54632. ActionManager.HasSpecificTrigger = function (trigger) {
  54633. for (var t in ActionManager.Triggers) {
  54634. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54635. var t_int = parseInt(t);
  54636. if (t_int === trigger) {
  54637. return true;
  54638. }
  54639. }
  54640. }
  54641. return false;
  54642. };
  54643. /**
  54644. * Registers an action to this action manager
  54645. * @param action defines the action to be registered
  54646. * @return the action amended (prepared) after registration
  54647. */
  54648. ActionManager.prototype.registerAction = function (action) {
  54649. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54650. if (this.getScene().actionManager !== this) {
  54651. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54652. return null;
  54653. }
  54654. }
  54655. this.actions.push(action);
  54656. if (ActionManager.Triggers[action.trigger]) {
  54657. ActionManager.Triggers[action.trigger]++;
  54658. }
  54659. else {
  54660. ActionManager.Triggers[action.trigger] = 1;
  54661. }
  54662. action._actionManager = this;
  54663. action._prepare();
  54664. return action;
  54665. };
  54666. /**
  54667. * Unregisters an action to this action manager
  54668. * @param action defines the action to be unregistered
  54669. * @return a boolean indicating whether the action has been unregistered
  54670. */
  54671. ActionManager.prototype.unregisterAction = function (action) {
  54672. var index = this.actions.indexOf(action);
  54673. if (index !== -1) {
  54674. this.actions.splice(index, 1);
  54675. ActionManager.Triggers[action.trigger] -= 1;
  54676. if (ActionManager.Triggers[action.trigger] === 0) {
  54677. delete ActionManager.Triggers[action.trigger];
  54678. }
  54679. delete action._actionManager;
  54680. return true;
  54681. }
  54682. return false;
  54683. };
  54684. /**
  54685. * Process a specific trigger
  54686. * @param trigger defines the trigger to process
  54687. * @param evt defines the event details to be processed
  54688. */
  54689. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54690. for (var index = 0; index < this.actions.length; index++) {
  54691. var action = this.actions[index];
  54692. if (action.trigger === trigger) {
  54693. if (evt) {
  54694. if (trigger === ActionManager.OnKeyUpTrigger
  54695. || trigger === ActionManager.OnKeyDownTrigger) {
  54696. var parameter = action.getTriggerParameter();
  54697. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54698. if (!parameter.toLowerCase) {
  54699. continue;
  54700. }
  54701. var lowerCase = parameter.toLowerCase();
  54702. if (lowerCase !== evt.sourceEvent.key) {
  54703. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54704. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54705. if (actualkey !== lowerCase) {
  54706. continue;
  54707. }
  54708. }
  54709. }
  54710. }
  54711. }
  54712. action._executeCurrent(evt);
  54713. }
  54714. }
  54715. };
  54716. /** @hidden */
  54717. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54718. var properties = propertyPath.split(".");
  54719. for (var index = 0; index < properties.length - 1; index++) {
  54720. target = target[properties[index]];
  54721. }
  54722. return target;
  54723. };
  54724. /** @hidden */
  54725. ActionManager.prototype._getProperty = function (propertyPath) {
  54726. var properties = propertyPath.split(".");
  54727. return properties[properties.length - 1];
  54728. };
  54729. /**
  54730. * Serialize this manager to a JSON object
  54731. * @param name defines the property name to store this manager
  54732. * @returns a JSON representation of this manager
  54733. */
  54734. ActionManager.prototype.serialize = function (name) {
  54735. var root = {
  54736. children: new Array(),
  54737. name: name,
  54738. type: 3,
  54739. properties: new Array() // Empty for root but required
  54740. };
  54741. for (var i = 0; i < this.actions.length; i++) {
  54742. var triggerObject = {
  54743. type: 0,
  54744. children: new Array(),
  54745. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54746. properties: new Array()
  54747. };
  54748. var triggerOptions = this.actions[i].triggerOptions;
  54749. if (triggerOptions && typeof triggerOptions !== "number") {
  54750. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54751. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54752. }
  54753. else {
  54754. var parameter = {};
  54755. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54756. if (triggerOptions.parameter.mesh) {
  54757. parameter._meshId = triggerOptions.parameter.mesh.id;
  54758. }
  54759. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54760. }
  54761. }
  54762. // Serialize child action, recursively
  54763. this.actions[i].serialize(triggerObject);
  54764. // Add serialized trigger
  54765. root.children.push(triggerObject);
  54766. }
  54767. return root;
  54768. };
  54769. /**
  54770. * Creates a new ActionManager from a JSON data
  54771. * @param parsedActions defines the JSON data to read from
  54772. * @param object defines the hosting mesh
  54773. * @param scene defines the hosting scene
  54774. */
  54775. ActionManager.Parse = function (parsedActions, object, scene) {
  54776. var actionManager = new ActionManager(scene);
  54777. if (object === null)
  54778. scene.actionManager = actionManager;
  54779. else
  54780. object.actionManager = actionManager;
  54781. // instanciate a new object
  54782. var instanciate = function (name, params) {
  54783. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54784. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54785. newInstance.constructor.apply(newInstance, params);
  54786. return newInstance;
  54787. };
  54788. var parseParameter = function (name, value, target, propertyPath) {
  54789. if (propertyPath === null) {
  54790. // String, boolean or float
  54791. var floatValue = parseFloat(value);
  54792. if (value === "true" || value === "false")
  54793. return value === "true";
  54794. else
  54795. return isNaN(floatValue) ? value : floatValue;
  54796. }
  54797. var effectiveTarget = propertyPath.split(".");
  54798. var values = value.split(",");
  54799. // Get effective Target
  54800. for (var i = 0; i < effectiveTarget.length; i++) {
  54801. target = target[effectiveTarget[i]];
  54802. }
  54803. // Return appropriate value with its type
  54804. if (typeof (target) === "boolean")
  54805. return values[0] === "true";
  54806. if (typeof (target) === "string")
  54807. return values[0];
  54808. // Parameters with multiple values such as Vector3 etc.
  54809. var split = new Array();
  54810. for (var i = 0; i < values.length; i++)
  54811. split.push(parseFloat(values[i]));
  54812. if (target instanceof BABYLON.Vector3)
  54813. return BABYLON.Vector3.FromArray(split);
  54814. if (target instanceof BABYLON.Vector4)
  54815. return BABYLON.Vector4.FromArray(split);
  54816. if (target instanceof BABYLON.Color3)
  54817. return BABYLON.Color3.FromArray(split);
  54818. if (target instanceof BABYLON.Color4)
  54819. return BABYLON.Color4.FromArray(split);
  54820. return parseFloat(values[0]);
  54821. };
  54822. // traverse graph per trigger
  54823. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54824. if (combineArray === void 0) { combineArray = null; }
  54825. if (parsedAction.detached)
  54826. return;
  54827. var parameters = new Array();
  54828. var target = null;
  54829. var propertyPath = null;
  54830. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54831. // Parameters
  54832. if (parsedAction.type === 2)
  54833. parameters.push(actionManager);
  54834. else
  54835. parameters.push(trigger);
  54836. if (combine) {
  54837. var actions = new Array();
  54838. for (var j = 0; j < parsedAction.combine.length; j++) {
  54839. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54840. }
  54841. parameters.push(actions);
  54842. }
  54843. else {
  54844. for (var i = 0; i < parsedAction.properties.length; i++) {
  54845. var value = parsedAction.properties[i].value;
  54846. var name = parsedAction.properties[i].name;
  54847. var targetType = parsedAction.properties[i].targetType;
  54848. if (name === "target")
  54849. if (targetType !== null && targetType === "SceneProperties")
  54850. value = target = scene;
  54851. else
  54852. value = target = scene.getNodeByName(value);
  54853. else if (name === "parent")
  54854. value = scene.getNodeByName(value);
  54855. else if (name === "sound") {
  54856. // Can not externalize to component, so only checks for the presence off the API.
  54857. if (scene.getSoundByName) {
  54858. value = scene.getSoundByName(value);
  54859. }
  54860. }
  54861. else if (name !== "propertyPath") {
  54862. if (parsedAction.type === 2 && name === "operator")
  54863. value = BABYLON.ValueCondition[value];
  54864. else
  54865. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54866. }
  54867. else {
  54868. propertyPath = value;
  54869. }
  54870. parameters.push(value);
  54871. }
  54872. }
  54873. if (combineArray === null) {
  54874. parameters.push(condition);
  54875. }
  54876. else {
  54877. parameters.push(null);
  54878. }
  54879. // If interpolate value action
  54880. if (parsedAction.name === "InterpolateValueAction") {
  54881. var param = parameters[parameters.length - 2];
  54882. parameters[parameters.length - 1] = param;
  54883. parameters[parameters.length - 2] = condition;
  54884. }
  54885. // Action or condition(s) and not CombineAction
  54886. var newAction = instanciate(parsedAction.name, parameters);
  54887. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54888. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54889. if (action)
  54890. action.then(nothing);
  54891. else
  54892. actionManager.registerAction(nothing);
  54893. action = nothing;
  54894. }
  54895. if (combineArray === null) {
  54896. if (newAction instanceof BABYLON.Condition) {
  54897. condition = newAction;
  54898. newAction = action;
  54899. }
  54900. else {
  54901. condition = null;
  54902. if (action)
  54903. action.then(newAction);
  54904. else
  54905. actionManager.registerAction(newAction);
  54906. }
  54907. }
  54908. else {
  54909. combineArray.push(newAction);
  54910. }
  54911. for (var i = 0; i < parsedAction.children.length; i++)
  54912. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54913. };
  54914. // triggers
  54915. for (var i = 0; i < parsedActions.children.length; i++) {
  54916. var triggerParams;
  54917. var trigger = parsedActions.children[i];
  54918. if (trigger.properties.length > 0) {
  54919. var param = trigger.properties[0].value;
  54920. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54921. if (value._meshId) {
  54922. value.mesh = scene.getMeshByID(value._meshId);
  54923. }
  54924. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54925. }
  54926. else
  54927. triggerParams = ActionManager[trigger.name];
  54928. for (var j = 0; j < trigger.children.length; j++) {
  54929. if (!trigger.detached)
  54930. traverse(trigger.children[j], triggerParams, null, null);
  54931. }
  54932. }
  54933. };
  54934. /**
  54935. * Get a trigger name by index
  54936. * @param trigger defines the trigger index
  54937. * @returns a trigger name
  54938. */
  54939. ActionManager.GetTriggerName = function (trigger) {
  54940. switch (trigger) {
  54941. case 0: return "NothingTrigger";
  54942. case 1: return "OnPickTrigger";
  54943. case 2: return "OnLeftPickTrigger";
  54944. case 3: return "OnRightPickTrigger";
  54945. case 4: return "OnCenterPickTrigger";
  54946. case 5: return "OnPickDownTrigger";
  54947. case 6: return "OnPickUpTrigger";
  54948. case 7: return "OnLongPressTrigger";
  54949. case 8: return "OnPointerOverTrigger";
  54950. case 9: return "OnPointerOutTrigger";
  54951. case 10: return "OnEveryFrameTrigger";
  54952. case 11: return "OnIntersectionEnterTrigger";
  54953. case 12: return "OnIntersectionExitTrigger";
  54954. case 13: return "OnKeyDownTrigger";
  54955. case 14: return "OnKeyUpTrigger";
  54956. case 15: return "OnPickOutTrigger";
  54957. default: return "";
  54958. }
  54959. };
  54960. /**
  54961. * Nothing
  54962. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54963. */
  54964. ActionManager.NothingTrigger = 0;
  54965. /**
  54966. * On pick
  54967. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54968. */
  54969. ActionManager.OnPickTrigger = 1;
  54970. /**
  54971. * On left pick
  54972. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54973. */
  54974. ActionManager.OnLeftPickTrigger = 2;
  54975. /**
  54976. * On right pick
  54977. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54978. */
  54979. ActionManager.OnRightPickTrigger = 3;
  54980. /**
  54981. * On center pick
  54982. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54983. */
  54984. ActionManager.OnCenterPickTrigger = 4;
  54985. /**
  54986. * On pick down
  54987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54988. */
  54989. ActionManager.OnPickDownTrigger = 5;
  54990. /**
  54991. * On double pick
  54992. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54993. */
  54994. ActionManager.OnDoublePickTrigger = 6;
  54995. /**
  54996. * On pick up
  54997. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54998. */
  54999. ActionManager.OnPickUpTrigger = 7;
  55000. /**
  55001. * On pick out.
  55002. * This trigger will only be raised if you also declared a OnPickDown
  55003. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55004. */
  55005. ActionManager.OnPickOutTrigger = 16;
  55006. /**
  55007. * On long press
  55008. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55009. */
  55010. ActionManager.OnLongPressTrigger = 8;
  55011. /**
  55012. * On pointer over
  55013. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55014. */
  55015. ActionManager.OnPointerOverTrigger = 9;
  55016. /**
  55017. * On pointer out
  55018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55019. */
  55020. ActionManager.OnPointerOutTrigger = 10;
  55021. /**
  55022. * On every frame
  55023. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55024. */
  55025. ActionManager.OnEveryFrameTrigger = 11;
  55026. /**
  55027. * On intersection enter
  55028. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55029. */
  55030. ActionManager.OnIntersectionEnterTrigger = 12;
  55031. /**
  55032. * On intersection exit
  55033. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55034. */
  55035. ActionManager.OnIntersectionExitTrigger = 13;
  55036. /**
  55037. * On key down
  55038. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55039. */
  55040. ActionManager.OnKeyDownTrigger = 14;
  55041. /**
  55042. * On key up
  55043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55044. */
  55045. ActionManager.OnKeyUpTrigger = 15;
  55046. /** Gets the list of active triggers */
  55047. ActionManager.Triggers = {};
  55048. return ActionManager;
  55049. }());
  55050. BABYLON.ActionManager = ActionManager;
  55051. })(BABYLON || (BABYLON = {}));
  55052. //# sourceMappingURL=babylon.actionManager.js.map
  55053. var BABYLON;
  55054. (function (BABYLON) {
  55055. /**
  55056. * This defines an action responsible to change the value of a property
  55057. * by interpolating between its current value and the newly set one once triggered.
  55058. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55059. */
  55060. var InterpolateValueAction = /** @class */ (function (_super) {
  55061. __extends(InterpolateValueAction, _super);
  55062. /**
  55063. * Instantiate the action
  55064. * @param triggerOptions defines the trigger options
  55065. * @param target defines the object containing the value to interpolate
  55066. * @param propertyPath defines the path to the property in the target object
  55067. * @param value defines the target value at the end of the interpolation
  55068. * @param duration deines the time it will take for the property to interpolate to the value.
  55069. * @param condition defines the trigger related conditions
  55070. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55071. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55072. */
  55073. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55074. if (duration === void 0) { duration = 1000; }
  55075. var _this = _super.call(this, triggerOptions, condition) || this;
  55076. /**
  55077. * Defines the time it will take for the property to interpolate to the value.
  55078. */
  55079. _this.duration = 1000;
  55080. /**
  55081. * Observable triggered once the interpolation animation has been done.
  55082. */
  55083. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55084. _this.propertyPath = propertyPath;
  55085. _this.value = value;
  55086. _this.duration = duration;
  55087. _this.stopOtherAnimations = stopOtherAnimations;
  55088. _this.onInterpolationDone = onInterpolationDone;
  55089. _this._target = _this._effectiveTarget = target;
  55090. return _this;
  55091. }
  55092. /** @hidden */
  55093. InterpolateValueAction.prototype._prepare = function () {
  55094. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55095. this._property = this._getProperty(this.propertyPath);
  55096. };
  55097. /**
  55098. * Execute the action starts the value interpolation.
  55099. */
  55100. InterpolateValueAction.prototype.execute = function () {
  55101. var _this = this;
  55102. var scene = this._actionManager.getScene();
  55103. var keys = [
  55104. {
  55105. frame: 0,
  55106. value: this._effectiveTarget[this._property]
  55107. }, {
  55108. frame: 100,
  55109. value: this.value
  55110. }
  55111. ];
  55112. var dataType;
  55113. if (typeof this.value === "number") {
  55114. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55115. }
  55116. else if (this.value instanceof BABYLON.Color3) {
  55117. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55118. }
  55119. else if (this.value instanceof BABYLON.Vector3) {
  55120. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55121. }
  55122. else if (this.value instanceof BABYLON.Matrix) {
  55123. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55124. }
  55125. else if (this.value instanceof BABYLON.Quaternion) {
  55126. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55127. }
  55128. else {
  55129. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55130. return;
  55131. }
  55132. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55133. animation.setKeys(keys);
  55134. if (this.stopOtherAnimations) {
  55135. scene.stopAnimation(this._effectiveTarget);
  55136. }
  55137. var wrapper = function () {
  55138. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55139. if (_this.onInterpolationDone) {
  55140. _this.onInterpolationDone();
  55141. }
  55142. };
  55143. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55144. };
  55145. /**
  55146. * Serializes the actions and its related information.
  55147. * @param parent defines the object to serialize in
  55148. * @returns the serialized object
  55149. */
  55150. InterpolateValueAction.prototype.serialize = function (parent) {
  55151. return _super.prototype._serialize.call(this, {
  55152. name: "InterpolateValueAction",
  55153. properties: [
  55154. BABYLON.Action._GetTargetProperty(this._target),
  55155. { name: "propertyPath", value: this.propertyPath },
  55156. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55157. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55158. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55159. ]
  55160. }, parent);
  55161. };
  55162. return InterpolateValueAction;
  55163. }(BABYLON.Action));
  55164. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55165. })(BABYLON || (BABYLON = {}));
  55166. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55167. var BABYLON;
  55168. (function (BABYLON) {
  55169. /**
  55170. * This defines an action responsible to toggle a boolean once triggered.
  55171. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55172. */
  55173. var SwitchBooleanAction = /** @class */ (function (_super) {
  55174. __extends(SwitchBooleanAction, _super);
  55175. /**
  55176. * Instantiate the action
  55177. * @param triggerOptions defines the trigger options
  55178. * @param target defines the object containing the boolean
  55179. * @param propertyPath defines the path to the boolean property in the target object
  55180. * @param condition defines the trigger related conditions
  55181. */
  55182. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55183. var _this = _super.call(this, triggerOptions, condition) || this;
  55184. _this.propertyPath = propertyPath;
  55185. _this._target = _this._effectiveTarget = target;
  55186. return _this;
  55187. }
  55188. /** @hidden */
  55189. SwitchBooleanAction.prototype._prepare = function () {
  55190. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55191. this._property = this._getProperty(this.propertyPath);
  55192. };
  55193. /**
  55194. * Execute the action toggle the boolean value.
  55195. */
  55196. SwitchBooleanAction.prototype.execute = function () {
  55197. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55198. };
  55199. /**
  55200. * Serializes the actions and its related information.
  55201. * @param parent defines the object to serialize in
  55202. * @returns the serialized object
  55203. */
  55204. SwitchBooleanAction.prototype.serialize = function (parent) {
  55205. return _super.prototype._serialize.call(this, {
  55206. name: "SwitchBooleanAction",
  55207. properties: [
  55208. BABYLON.Action._GetTargetProperty(this._target),
  55209. { name: "propertyPath", value: this.propertyPath }
  55210. ]
  55211. }, parent);
  55212. };
  55213. return SwitchBooleanAction;
  55214. }(BABYLON.Action));
  55215. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55216. /**
  55217. * This defines an action responsible to set a the state field of the target
  55218. * to a desired value once triggered.
  55219. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55220. */
  55221. var SetStateAction = /** @class */ (function (_super) {
  55222. __extends(SetStateAction, _super);
  55223. /**
  55224. * Instantiate the action
  55225. * @param triggerOptions defines the trigger options
  55226. * @param target defines the object containing the state property
  55227. * @param value defines the value to store in the state field
  55228. * @param condition defines the trigger related conditions
  55229. */
  55230. function SetStateAction(triggerOptions, target, value, condition) {
  55231. var _this = _super.call(this, triggerOptions, condition) || this;
  55232. _this.value = value;
  55233. _this._target = target;
  55234. return _this;
  55235. }
  55236. /**
  55237. * Execute the action and store the value on the target state property.
  55238. */
  55239. SetStateAction.prototype.execute = function () {
  55240. this._target.state = this.value;
  55241. };
  55242. /**
  55243. * Serializes the actions and its related information.
  55244. * @param parent defines the object to serialize in
  55245. * @returns the serialized object
  55246. */
  55247. SetStateAction.prototype.serialize = function (parent) {
  55248. return _super.prototype._serialize.call(this, {
  55249. name: "SetStateAction",
  55250. properties: [
  55251. BABYLON.Action._GetTargetProperty(this._target),
  55252. { name: "value", value: this.value }
  55253. ]
  55254. }, parent);
  55255. };
  55256. return SetStateAction;
  55257. }(BABYLON.Action));
  55258. BABYLON.SetStateAction = SetStateAction;
  55259. /**
  55260. * This defines an action responsible to set a property of the target
  55261. * to a desired value once triggered.
  55262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55263. */
  55264. var SetValueAction = /** @class */ (function (_super) {
  55265. __extends(SetValueAction, _super);
  55266. /**
  55267. * Instantiate the action
  55268. * @param triggerOptions defines the trigger options
  55269. * @param target defines the object containing the property
  55270. * @param propertyPath defines the path of the property to set in the target
  55271. * @param value defines the value to set in the property
  55272. * @param condition defines the trigger related conditions
  55273. */
  55274. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55275. var _this = _super.call(this, triggerOptions, condition) || this;
  55276. _this.propertyPath = propertyPath;
  55277. _this.value = value;
  55278. _this._target = _this._effectiveTarget = target;
  55279. return _this;
  55280. }
  55281. /** @hidden */
  55282. SetValueAction.prototype._prepare = function () {
  55283. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55284. this._property = this._getProperty(this.propertyPath);
  55285. };
  55286. /**
  55287. * Execute the action and set the targetted property to the desired value.
  55288. */
  55289. SetValueAction.prototype.execute = function () {
  55290. this._effectiveTarget[this._property] = this.value;
  55291. if (this._target.markAsDirty) {
  55292. this._target.markAsDirty(this._property);
  55293. }
  55294. };
  55295. /**
  55296. * Serializes the actions and its related information.
  55297. * @param parent defines the object to serialize in
  55298. * @returns the serialized object
  55299. */
  55300. SetValueAction.prototype.serialize = function (parent) {
  55301. return _super.prototype._serialize.call(this, {
  55302. name: "SetValueAction",
  55303. properties: [
  55304. BABYLON.Action._GetTargetProperty(this._target),
  55305. { name: "propertyPath", value: this.propertyPath },
  55306. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55307. ]
  55308. }, parent);
  55309. };
  55310. return SetValueAction;
  55311. }(BABYLON.Action));
  55312. BABYLON.SetValueAction = SetValueAction;
  55313. /**
  55314. * This defines an action responsible to increment the target value
  55315. * to a desired value once triggered.
  55316. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55317. */
  55318. var IncrementValueAction = /** @class */ (function (_super) {
  55319. __extends(IncrementValueAction, _super);
  55320. /**
  55321. * Instantiate the action
  55322. * @param triggerOptions defines the trigger options
  55323. * @param target defines the object containing the property
  55324. * @param propertyPath defines the path of the property to increment in the target
  55325. * @param value defines the value value we should increment the property by
  55326. * @param condition defines the trigger related conditions
  55327. */
  55328. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55329. var _this = _super.call(this, triggerOptions, condition) || this;
  55330. _this.propertyPath = propertyPath;
  55331. _this.value = value;
  55332. _this._target = _this._effectiveTarget = target;
  55333. return _this;
  55334. }
  55335. /** @hidden */
  55336. IncrementValueAction.prototype._prepare = function () {
  55337. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55338. this._property = this._getProperty(this.propertyPath);
  55339. if (typeof this._effectiveTarget[this._property] !== "number") {
  55340. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55341. }
  55342. };
  55343. /**
  55344. * Execute the action and increment the target of the value amount.
  55345. */
  55346. IncrementValueAction.prototype.execute = function () {
  55347. this._effectiveTarget[this._property] += this.value;
  55348. if (this._target.markAsDirty) {
  55349. this._target.markAsDirty(this._property);
  55350. }
  55351. };
  55352. /**
  55353. * Serializes the actions and its related information.
  55354. * @param parent defines the object to serialize in
  55355. * @returns the serialized object
  55356. */
  55357. IncrementValueAction.prototype.serialize = function (parent) {
  55358. return _super.prototype._serialize.call(this, {
  55359. name: "IncrementValueAction",
  55360. properties: [
  55361. BABYLON.Action._GetTargetProperty(this._target),
  55362. { name: "propertyPath", value: this.propertyPath },
  55363. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55364. ]
  55365. }, parent);
  55366. };
  55367. return IncrementValueAction;
  55368. }(BABYLON.Action));
  55369. BABYLON.IncrementValueAction = IncrementValueAction;
  55370. /**
  55371. * This defines an action responsible to start an animation once triggered.
  55372. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55373. */
  55374. var PlayAnimationAction = /** @class */ (function (_super) {
  55375. __extends(PlayAnimationAction, _super);
  55376. /**
  55377. * Instantiate the action
  55378. * @param triggerOptions defines the trigger options
  55379. * @param target defines the target animation or animation name
  55380. * @param from defines from where the animation should start (animation frame)
  55381. * @param end defines where the animation should stop (animation frame)
  55382. * @param loop defines if the animation should loop or stop after the first play
  55383. * @param condition defines the trigger related conditions
  55384. */
  55385. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55386. var _this = _super.call(this, triggerOptions, condition) || this;
  55387. _this.from = from;
  55388. _this.to = to;
  55389. _this.loop = loop;
  55390. _this._target = target;
  55391. return _this;
  55392. }
  55393. /** @hidden */
  55394. PlayAnimationAction.prototype._prepare = function () {
  55395. };
  55396. /**
  55397. * Execute the action and play the animation.
  55398. */
  55399. PlayAnimationAction.prototype.execute = function () {
  55400. var scene = this._actionManager.getScene();
  55401. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55402. };
  55403. /**
  55404. * Serializes the actions and its related information.
  55405. * @param parent defines the object to serialize in
  55406. * @returns the serialized object
  55407. */
  55408. PlayAnimationAction.prototype.serialize = function (parent) {
  55409. return _super.prototype._serialize.call(this, {
  55410. name: "PlayAnimationAction",
  55411. properties: [
  55412. BABYLON.Action._GetTargetProperty(this._target),
  55413. { name: "from", value: String(this.from) },
  55414. { name: "to", value: String(this.to) },
  55415. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55416. ]
  55417. }, parent);
  55418. };
  55419. return PlayAnimationAction;
  55420. }(BABYLON.Action));
  55421. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55422. /**
  55423. * This defines an action responsible to stop an animation once triggered.
  55424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55425. */
  55426. var StopAnimationAction = /** @class */ (function (_super) {
  55427. __extends(StopAnimationAction, _super);
  55428. /**
  55429. * Instantiate the action
  55430. * @param triggerOptions defines the trigger options
  55431. * @param target defines the target animation or animation name
  55432. * @param condition defines the trigger related conditions
  55433. */
  55434. function StopAnimationAction(triggerOptions, target, condition) {
  55435. var _this = _super.call(this, triggerOptions, condition) || this;
  55436. _this._target = target;
  55437. return _this;
  55438. }
  55439. /** @hidden */
  55440. StopAnimationAction.prototype._prepare = function () {
  55441. };
  55442. /**
  55443. * Execute the action and stop the animation.
  55444. */
  55445. StopAnimationAction.prototype.execute = function () {
  55446. var scene = this._actionManager.getScene();
  55447. scene.stopAnimation(this._target);
  55448. };
  55449. /**
  55450. * Serializes the actions and its related information.
  55451. * @param parent defines the object to serialize in
  55452. * @returns the serialized object
  55453. */
  55454. StopAnimationAction.prototype.serialize = function (parent) {
  55455. return _super.prototype._serialize.call(this, {
  55456. name: "StopAnimationAction",
  55457. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55458. }, parent);
  55459. };
  55460. return StopAnimationAction;
  55461. }(BABYLON.Action));
  55462. BABYLON.StopAnimationAction = StopAnimationAction;
  55463. /**
  55464. * This defines an action responsible that does nothing once triggered.
  55465. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55466. */
  55467. var DoNothingAction = /** @class */ (function (_super) {
  55468. __extends(DoNothingAction, _super);
  55469. /**
  55470. * Instantiate the action
  55471. * @param triggerOptions defines the trigger options
  55472. * @param condition defines the trigger related conditions
  55473. */
  55474. function DoNothingAction(triggerOptions, condition) {
  55475. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55476. return _super.call(this, triggerOptions, condition) || this;
  55477. }
  55478. /**
  55479. * Execute the action and do nothing.
  55480. */
  55481. DoNothingAction.prototype.execute = function () {
  55482. };
  55483. /**
  55484. * Serializes the actions and its related information.
  55485. * @param parent defines the object to serialize in
  55486. * @returns the serialized object
  55487. */
  55488. DoNothingAction.prototype.serialize = function (parent) {
  55489. return _super.prototype._serialize.call(this, {
  55490. name: "DoNothingAction",
  55491. properties: []
  55492. }, parent);
  55493. };
  55494. return DoNothingAction;
  55495. }(BABYLON.Action));
  55496. BABYLON.DoNothingAction = DoNothingAction;
  55497. /**
  55498. * This defines an action responsible to trigger several actions once triggered.
  55499. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55500. */
  55501. var CombineAction = /** @class */ (function (_super) {
  55502. __extends(CombineAction, _super);
  55503. /**
  55504. * Instantiate the action
  55505. * @param triggerOptions defines the trigger options
  55506. * @param children defines the list of aggregated animations to run
  55507. * @param condition defines the trigger related conditions
  55508. */
  55509. function CombineAction(triggerOptions, children, condition) {
  55510. var _this = _super.call(this, triggerOptions, condition) || this;
  55511. _this.children = children;
  55512. return _this;
  55513. }
  55514. /** @hidden */
  55515. CombineAction.prototype._prepare = function () {
  55516. for (var index = 0; index < this.children.length; index++) {
  55517. this.children[index]._actionManager = this._actionManager;
  55518. this.children[index]._prepare();
  55519. }
  55520. };
  55521. /**
  55522. * Execute the action and executes all the aggregated actions.
  55523. */
  55524. CombineAction.prototype.execute = function (evt) {
  55525. for (var index = 0; index < this.children.length; index++) {
  55526. this.children[index].execute(evt);
  55527. }
  55528. };
  55529. /**
  55530. * Serializes the actions and its related information.
  55531. * @param parent defines the object to serialize in
  55532. * @returns the serialized object
  55533. */
  55534. CombineAction.prototype.serialize = function (parent) {
  55535. var serializationObject = _super.prototype._serialize.call(this, {
  55536. name: "CombineAction",
  55537. properties: [],
  55538. combine: []
  55539. }, parent);
  55540. for (var i = 0; i < this.children.length; i++) {
  55541. serializationObject.combine.push(this.children[i].serialize(null));
  55542. }
  55543. return serializationObject;
  55544. };
  55545. return CombineAction;
  55546. }(BABYLON.Action));
  55547. BABYLON.CombineAction = CombineAction;
  55548. /**
  55549. * This defines an action responsible to run code (external event) once triggered.
  55550. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55551. */
  55552. var ExecuteCodeAction = /** @class */ (function (_super) {
  55553. __extends(ExecuteCodeAction, _super);
  55554. /**
  55555. * Instantiate the action
  55556. * @param triggerOptions defines the trigger options
  55557. * @param func defines the callback function to run
  55558. * @param condition defines the trigger related conditions
  55559. */
  55560. function ExecuteCodeAction(triggerOptions, func, condition) {
  55561. var _this = _super.call(this, triggerOptions, condition) || this;
  55562. _this.func = func;
  55563. return _this;
  55564. }
  55565. /**
  55566. * Execute the action and run the attached code.
  55567. */
  55568. ExecuteCodeAction.prototype.execute = function (evt) {
  55569. this.func(evt);
  55570. };
  55571. return ExecuteCodeAction;
  55572. }(BABYLON.Action));
  55573. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55574. /**
  55575. * This defines an action responsible to set the parent property of the target once triggered.
  55576. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55577. */
  55578. var SetParentAction = /** @class */ (function (_super) {
  55579. __extends(SetParentAction, _super);
  55580. /**
  55581. * Instantiate the action
  55582. * @param triggerOptions defines the trigger options
  55583. * @param target defines the target containing the parent property
  55584. * @param parent defines from where the animation should start (animation frame)
  55585. * @param condition defines the trigger related conditions
  55586. */
  55587. function SetParentAction(triggerOptions, target, parent, condition) {
  55588. var _this = _super.call(this, triggerOptions, condition) || this;
  55589. _this._target = target;
  55590. _this._parent = parent;
  55591. return _this;
  55592. }
  55593. /** @hidden */
  55594. SetParentAction.prototype._prepare = function () {
  55595. };
  55596. /**
  55597. * Execute the action and set the parent property.
  55598. */
  55599. SetParentAction.prototype.execute = function () {
  55600. if (this._target.parent === this._parent) {
  55601. return;
  55602. }
  55603. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55604. invertParentWorldMatrix.invert();
  55605. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55606. this._target.parent = this._parent;
  55607. };
  55608. /**
  55609. * Serializes the actions and its related information.
  55610. * @param parent defines the object to serialize in
  55611. * @returns the serialized object
  55612. */
  55613. SetParentAction.prototype.serialize = function (parent) {
  55614. return _super.prototype._serialize.call(this, {
  55615. name: "SetParentAction",
  55616. properties: [
  55617. BABYLON.Action._GetTargetProperty(this._target),
  55618. BABYLON.Action._GetTargetProperty(this._parent),
  55619. ]
  55620. }, parent);
  55621. };
  55622. return SetParentAction;
  55623. }(BABYLON.Action));
  55624. BABYLON.SetParentAction = SetParentAction;
  55625. })(BABYLON || (BABYLON = {}));
  55626. //# sourceMappingURL=babylon.directActions.js.map
  55627. var BABYLON;
  55628. (function (BABYLON) {
  55629. var SpriteManager = /** @class */ (function () {
  55630. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55631. if (epsilon === void 0) { epsilon = 0.01; }
  55632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55633. this.name = name;
  55634. this.sprites = new Array();
  55635. this.renderingGroupId = 0;
  55636. this.layerMask = 0x0FFFFFFF;
  55637. this.fogEnabled = true;
  55638. this.isPickable = false;
  55639. /**
  55640. * An event triggered when the manager is disposed.
  55641. */
  55642. this.onDisposeObservable = new BABYLON.Observable();
  55643. this._vertexBuffers = {};
  55644. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55645. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55646. }
  55647. this._capacity = capacity;
  55648. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55649. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55650. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55651. if (cellSize.width && cellSize.height) {
  55652. this.cellWidth = cellSize.width;
  55653. this.cellHeight = cellSize.height;
  55654. }
  55655. else if (cellSize !== undefined) {
  55656. this.cellWidth = cellSize;
  55657. this.cellHeight = cellSize;
  55658. }
  55659. else {
  55660. return;
  55661. }
  55662. this._epsilon = epsilon;
  55663. this._scene = scene;
  55664. this._scene.spriteManagers.push(this);
  55665. var indices = [];
  55666. var index = 0;
  55667. for (var count = 0; count < capacity; count++) {
  55668. indices.push(index);
  55669. indices.push(index + 1);
  55670. indices.push(index + 2);
  55671. indices.push(index);
  55672. indices.push(index + 2);
  55673. indices.push(index + 3);
  55674. index += 4;
  55675. }
  55676. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55677. // VBO
  55678. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55679. this._vertexData = new Float32Array(capacity * 16 * 4);
  55680. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55681. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55682. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55683. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55684. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55686. this._vertexBuffers["options"] = options;
  55687. this._vertexBuffers["cellInfo"] = cellInfo;
  55688. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55689. // Effects
  55690. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55691. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55692. }
  55693. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55694. set: function (callback) {
  55695. if (this._onDisposeObserver) {
  55696. this.onDisposeObservable.remove(this._onDisposeObserver);
  55697. }
  55698. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55699. },
  55700. enumerable: true,
  55701. configurable: true
  55702. });
  55703. Object.defineProperty(SpriteManager.prototype, "texture", {
  55704. get: function () {
  55705. return this._spriteTexture;
  55706. },
  55707. set: function (value) {
  55708. this._spriteTexture = value;
  55709. },
  55710. enumerable: true,
  55711. configurable: true
  55712. });
  55713. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55714. var arrayOffset = index * 16;
  55715. if (offsetX === 0)
  55716. offsetX = this._epsilon;
  55717. else if (offsetX === 1)
  55718. offsetX = 1 - this._epsilon;
  55719. if (offsetY === 0)
  55720. offsetY = this._epsilon;
  55721. else if (offsetY === 1)
  55722. offsetY = 1 - this._epsilon;
  55723. this._vertexData[arrayOffset] = sprite.position.x;
  55724. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55725. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55726. this._vertexData[arrayOffset + 3] = sprite.angle;
  55727. this._vertexData[arrayOffset + 4] = sprite.width;
  55728. this._vertexData[arrayOffset + 5] = sprite.height;
  55729. this._vertexData[arrayOffset + 6] = offsetX;
  55730. this._vertexData[arrayOffset + 7] = offsetY;
  55731. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55732. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55733. var offset = (sprite.cellIndex / rowSize) >> 0;
  55734. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55735. this._vertexData[arrayOffset + 11] = offset;
  55736. // Color
  55737. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55738. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55739. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55740. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55741. };
  55742. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55743. var count = Math.min(this._capacity, this.sprites.length);
  55744. var min = BABYLON.Vector3.Zero();
  55745. var max = BABYLON.Vector3.Zero();
  55746. var distance = Number.MAX_VALUE;
  55747. var currentSprite = null;
  55748. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55749. var cameraView = camera.getViewMatrix();
  55750. for (var index = 0; index < count; index++) {
  55751. var sprite = this.sprites[index];
  55752. if (!sprite) {
  55753. continue;
  55754. }
  55755. if (predicate) {
  55756. if (!predicate(sprite)) {
  55757. continue;
  55758. }
  55759. }
  55760. else if (!sprite.isPickable) {
  55761. continue;
  55762. }
  55763. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55764. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55765. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55766. if (ray.intersectsBoxMinMax(min, max)) {
  55767. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55768. if (distance > currentDistance) {
  55769. distance = currentDistance;
  55770. currentSprite = sprite;
  55771. if (fastCheck) {
  55772. break;
  55773. }
  55774. }
  55775. }
  55776. }
  55777. if (currentSprite) {
  55778. var result = new BABYLON.PickingInfo();
  55779. result.hit = true;
  55780. result.pickedSprite = currentSprite;
  55781. result.distance = distance;
  55782. return result;
  55783. }
  55784. return null;
  55785. };
  55786. SpriteManager.prototype.render = function () {
  55787. // Check
  55788. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55789. return;
  55790. var engine = this._scene.getEngine();
  55791. var baseSize = this._spriteTexture.getBaseSize();
  55792. // Sprites
  55793. var deltaTime = engine.getDeltaTime();
  55794. var max = Math.min(this._capacity, this.sprites.length);
  55795. var rowSize = baseSize.width / this.cellWidth;
  55796. var offset = 0;
  55797. for (var index = 0; index < max; index++) {
  55798. var sprite = this.sprites[index];
  55799. if (!sprite || !sprite.isVisible) {
  55800. continue;
  55801. }
  55802. sprite._animate(deltaTime);
  55803. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55804. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55805. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55806. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55807. }
  55808. this._buffer.update(this._vertexData);
  55809. // Render
  55810. var effect = this._effectBase;
  55811. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55812. effect = this._effectFog;
  55813. }
  55814. engine.enableEffect(effect);
  55815. var viewMatrix = this._scene.getViewMatrix();
  55816. effect.setTexture("diffuseSampler", this._spriteTexture);
  55817. effect.setMatrix("view", viewMatrix);
  55818. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55819. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55820. // Fog
  55821. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55822. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55823. effect.setColor3("vFogColor", this._scene.fogColor);
  55824. }
  55825. // VBOs
  55826. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55827. // Draw order
  55828. engine.setDepthFunctionToLessOrEqual();
  55829. effect.setBool("alphaTest", true);
  55830. engine.setColorWrite(false);
  55831. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55832. engine.setColorWrite(true);
  55833. effect.setBool("alphaTest", false);
  55834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55835. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55837. };
  55838. SpriteManager.prototype.dispose = function () {
  55839. if (this._buffer) {
  55840. this._buffer.dispose();
  55841. this._buffer = null;
  55842. }
  55843. if (this._indexBuffer) {
  55844. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55845. this._indexBuffer = null;
  55846. }
  55847. if (this._spriteTexture) {
  55848. this._spriteTexture.dispose();
  55849. this._spriteTexture = null;
  55850. }
  55851. // Remove from scene
  55852. var index = this._scene.spriteManagers.indexOf(this);
  55853. this._scene.spriteManagers.splice(index, 1);
  55854. // Callback
  55855. this.onDisposeObservable.notifyObservers(this);
  55856. this.onDisposeObservable.clear();
  55857. };
  55858. return SpriteManager;
  55859. }());
  55860. BABYLON.SpriteManager = SpriteManager;
  55861. })(BABYLON || (BABYLON = {}));
  55862. //# sourceMappingURL=babylon.spriteManager.js.map
  55863. var BABYLON;
  55864. (function (BABYLON) {
  55865. var Sprite = /** @class */ (function () {
  55866. function Sprite(name, manager) {
  55867. this.name = name;
  55868. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55869. this.width = 1.0;
  55870. this.height = 1.0;
  55871. this.angle = 0;
  55872. this.cellIndex = 0;
  55873. this.invertU = 0;
  55874. this.invertV = 0;
  55875. this.animations = new Array();
  55876. this.isPickable = false;
  55877. this._animationStarted = false;
  55878. this._loopAnimation = false;
  55879. this._fromIndex = 0;
  55880. this._toIndex = 0;
  55881. this._delay = 0;
  55882. this._direction = 1;
  55883. this._time = 0;
  55884. /**
  55885. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55886. */
  55887. this.isVisible = true;
  55888. this._manager = manager;
  55889. this._manager.sprites.push(this);
  55890. this.position = BABYLON.Vector3.Zero();
  55891. }
  55892. Object.defineProperty(Sprite.prototype, "size", {
  55893. get: function () {
  55894. return this.width;
  55895. },
  55896. set: function (value) {
  55897. this.width = value;
  55898. this.height = value;
  55899. },
  55900. enumerable: true,
  55901. configurable: true
  55902. });
  55903. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55904. this._fromIndex = from;
  55905. this._toIndex = to;
  55906. this._loopAnimation = loop;
  55907. this._delay = delay;
  55908. this._animationStarted = true;
  55909. this._direction = from < to ? 1 : -1;
  55910. this.cellIndex = from;
  55911. this._time = 0;
  55912. this._onAnimationEnd = onAnimationEnd;
  55913. };
  55914. Sprite.prototype.stopAnimation = function () {
  55915. this._animationStarted = false;
  55916. };
  55917. /** @hidden */
  55918. Sprite.prototype._animate = function (deltaTime) {
  55919. if (!this._animationStarted)
  55920. return;
  55921. this._time += deltaTime;
  55922. if (this._time > this._delay) {
  55923. this._time = this._time % this._delay;
  55924. this.cellIndex += this._direction;
  55925. if (this.cellIndex > this._toIndex) {
  55926. if (this._loopAnimation) {
  55927. this.cellIndex = this._fromIndex;
  55928. }
  55929. else {
  55930. this.cellIndex = this._toIndex;
  55931. this._animationStarted = false;
  55932. if (this._onAnimationEnd) {
  55933. this._onAnimationEnd();
  55934. }
  55935. if (this.disposeWhenFinishedAnimating) {
  55936. this.dispose();
  55937. }
  55938. }
  55939. }
  55940. }
  55941. };
  55942. Sprite.prototype.dispose = function () {
  55943. for (var i = 0; i < this._manager.sprites.length; i++) {
  55944. if (this._manager.sprites[i] == this) {
  55945. this._manager.sprites.splice(i, 1);
  55946. }
  55947. }
  55948. };
  55949. return Sprite;
  55950. }());
  55951. BABYLON.Sprite = Sprite;
  55952. })(BABYLON || (BABYLON = {}));
  55953. //# sourceMappingURL=babylon.sprite.js.map
  55954. var BABYLON;
  55955. (function (BABYLON) {
  55956. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55957. if (!BABYLON.PickingInfo) {
  55958. return null;
  55959. }
  55960. var pickingInfo = null;
  55961. if (!camera) {
  55962. if (!this.activeCamera) {
  55963. return null;
  55964. }
  55965. camera = this.activeCamera;
  55966. }
  55967. if (this.spriteManagers.length > 0) {
  55968. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55969. var spriteManager = this.spriteManagers[spriteIndex];
  55970. if (!spriteManager.isPickable) {
  55971. continue;
  55972. }
  55973. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55974. if (!result || !result.hit)
  55975. continue;
  55976. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55977. continue;
  55978. pickingInfo = result;
  55979. if (fastCheck) {
  55980. break;
  55981. }
  55982. }
  55983. }
  55984. return pickingInfo || new BABYLON.PickingInfo();
  55985. };
  55986. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55987. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55988. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55989. };
  55990. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55991. if (!this._tempSpritePickingRay) {
  55992. return null;
  55993. }
  55994. if (!camera) {
  55995. if (!this.activeCamera) {
  55996. return null;
  55997. }
  55998. camera = this.activeCamera;
  55999. }
  56000. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56001. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56002. };
  56003. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56004. if (this._pointerOverSprite === sprite) {
  56005. return;
  56006. }
  56007. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56008. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56009. }
  56010. this._pointerOverSprite = sprite;
  56011. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56012. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56013. }
  56014. };
  56015. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56016. return this._pointerOverSprite;
  56017. };
  56018. /**
  56019. * Defines the sprite scene component responsible to manage sprites
  56020. * in a given scene.
  56021. */
  56022. var SpriteSceneComponent = /** @class */ (function () {
  56023. /**
  56024. * Creates a new instance of the component for the given scene
  56025. * @param scene Defines the scene to register the component in
  56026. */
  56027. function SpriteSceneComponent(scene) {
  56028. /**
  56029. * The component name helpfull to identify the component in the list of scene components.
  56030. */
  56031. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56032. this.scene = scene;
  56033. this.scene.spriteManagers = new Array();
  56034. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56035. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56036. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56037. this._spritePredicate = function (sprite) {
  56038. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56039. };
  56040. }
  56041. /**
  56042. * Registers the component in a given scene
  56043. */
  56044. SpriteSceneComponent.prototype.register = function () {
  56045. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56046. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56047. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56048. };
  56049. /**
  56050. * Rebuilds the elements related to this component in case of
  56051. * context lost for instance.
  56052. */
  56053. SpriteSceneComponent.prototype.rebuild = function () {
  56054. /** Nothing to do for sprites */
  56055. };
  56056. /**
  56057. * Disposes the component and the associated ressources.
  56058. */
  56059. SpriteSceneComponent.prototype.dispose = function () {
  56060. this.scene.onBeforeSpritesRenderingObservable.clear();
  56061. this.scene.onAfterSpritesRenderingObservable.clear();
  56062. var spriteManagers = this.scene.spriteManagers;
  56063. while (spriteManagers.length) {
  56064. spriteManagers[0].dispose();
  56065. }
  56066. };
  56067. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56068. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56069. if (result) {
  56070. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56071. }
  56072. return result;
  56073. };
  56074. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56075. var scene = this.scene;
  56076. if (isMeshPicked) {
  56077. scene.setPointerOverSprite(null);
  56078. }
  56079. else {
  56080. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56081. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56082. scene.setPointerOverSprite(pickResult.pickedSprite);
  56083. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56084. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56085. }
  56086. else {
  56087. canvas.style.cursor = scene.hoverCursor;
  56088. }
  56089. }
  56090. else {
  56091. scene.setPointerOverSprite(null);
  56092. }
  56093. }
  56094. return pickResult;
  56095. };
  56096. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56097. var scene = this.scene;
  56098. scene._pickedDownSprite = null;
  56099. if (scene.spriteManagers.length > 0) {
  56100. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56101. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56102. if (pickResult.pickedSprite.actionManager) {
  56103. scene._pickedDownSprite = pickResult.pickedSprite;
  56104. switch (evt.button) {
  56105. case 0:
  56106. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56107. break;
  56108. case 1:
  56109. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56110. break;
  56111. case 2:
  56112. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56113. break;
  56114. }
  56115. if (pickResult.pickedSprite.actionManager) {
  56116. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56117. }
  56118. }
  56119. }
  56120. }
  56121. return pickResult;
  56122. };
  56123. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56124. var scene = this.scene;
  56125. if (scene.spriteManagers.length > 0) {
  56126. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56127. if (spritePickResult) {
  56128. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56129. if (spritePickResult.pickedSprite.actionManager) {
  56130. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56131. if (spritePickResult.pickedSprite.actionManager) {
  56132. if (!this.scene._isPointerSwiping()) {
  56133. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56134. }
  56135. }
  56136. }
  56137. }
  56138. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56139. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56140. }
  56141. }
  56142. }
  56143. return pickResult;
  56144. };
  56145. return SpriteSceneComponent;
  56146. }());
  56147. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56148. })(BABYLON || (BABYLON = {}));
  56149. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56150. var BABYLON;
  56151. (function (BABYLON) {
  56152. /**
  56153. * @hidden
  56154. */
  56155. var IntersectionInfo = /** @class */ (function () {
  56156. function IntersectionInfo(bu, bv, distance) {
  56157. this.bu = bu;
  56158. this.bv = bv;
  56159. this.distance = distance;
  56160. this.faceId = 0;
  56161. this.subMeshId = 0;
  56162. }
  56163. return IntersectionInfo;
  56164. }());
  56165. BABYLON.IntersectionInfo = IntersectionInfo;
  56166. /**
  56167. * Information about the result of picking within a scene
  56168. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56169. */
  56170. var PickingInfo = /** @class */ (function () {
  56171. function PickingInfo() {
  56172. /**
  56173. * If the pick collided with an object
  56174. */
  56175. this.hit = false;
  56176. /**
  56177. * Distance away where the pick collided
  56178. */
  56179. this.distance = 0;
  56180. /**
  56181. * The location of pick collision
  56182. */
  56183. this.pickedPoint = null;
  56184. /**
  56185. * The mesh corresponding the the pick collision
  56186. */
  56187. this.pickedMesh = null;
  56188. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56189. this.bu = 0;
  56190. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56191. this.bv = 0;
  56192. /** The id of the face on the mesh that was picked */
  56193. this.faceId = -1;
  56194. /** Id of the the submesh that was picked */
  56195. this.subMeshId = 0;
  56196. /** If a sprite was picked, this will be the sprite the pick collided with */
  56197. this.pickedSprite = null;
  56198. /**
  56199. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56200. */
  56201. this.originMesh = null;
  56202. /**
  56203. * The ray that was used to perform the picking.
  56204. */
  56205. this.ray = null;
  56206. }
  56207. /**
  56208. * Gets the normal correspodning to the face the pick collided with
  56209. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56210. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56211. * @returns The normal correspodning to the face the pick collided with
  56212. */
  56213. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56214. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56215. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56216. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56217. return null;
  56218. }
  56219. var indices = this.pickedMesh.getIndices();
  56220. if (!indices) {
  56221. return null;
  56222. }
  56223. var result;
  56224. if (useVerticesNormals) {
  56225. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56226. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56227. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56228. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56229. normal0 = normal0.scale(this.bu);
  56230. normal1 = normal1.scale(this.bv);
  56231. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56232. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56233. }
  56234. else {
  56235. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56236. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56237. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56238. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56239. var p1p2 = vertex1.subtract(vertex2);
  56240. var p3p2 = vertex3.subtract(vertex2);
  56241. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56242. }
  56243. if (useWorldCoordinates) {
  56244. var wm = this.pickedMesh.getWorldMatrix();
  56245. if (this.pickedMesh.nonUniformScaling) {
  56246. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56247. wm = BABYLON.Tmp.Matrix[0];
  56248. wm.setTranslationFromFloats(0, 0, 0);
  56249. wm.invert();
  56250. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56251. wm = BABYLON.Tmp.Matrix[1];
  56252. }
  56253. result = BABYLON.Vector3.TransformNormal(result, wm);
  56254. }
  56255. result.normalize();
  56256. return result;
  56257. };
  56258. /**
  56259. * Gets the texture coordinates of where the pick occured
  56260. * @returns the vector containing the coordnates of the texture
  56261. */
  56262. PickingInfo.prototype.getTextureCoordinates = function () {
  56263. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56264. return null;
  56265. }
  56266. var indices = this.pickedMesh.getIndices();
  56267. if (!indices) {
  56268. return null;
  56269. }
  56270. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56271. if (!uvs) {
  56272. return null;
  56273. }
  56274. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56275. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56276. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56277. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56278. uv1 = uv1.scale(this.bu);
  56279. uv2 = uv2.scale(this.bv);
  56280. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56281. };
  56282. return PickingInfo;
  56283. }());
  56284. BABYLON.PickingInfo = PickingInfo;
  56285. })(BABYLON || (BABYLON = {}));
  56286. //# sourceMappingURL=babylon.pickingInfo.js.map
  56287. var BABYLON;
  56288. (function (BABYLON) {
  56289. var Ray = /** @class */ (function () {
  56290. function Ray(origin, direction, length) {
  56291. if (length === void 0) { length = Number.MAX_VALUE; }
  56292. this.origin = origin;
  56293. this.direction = direction;
  56294. this.length = length;
  56295. }
  56296. // Methods
  56297. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56298. var d = 0.0;
  56299. var maxValue = Number.MAX_VALUE;
  56300. var inv;
  56301. var min;
  56302. var max;
  56303. var temp;
  56304. if (Math.abs(this.direction.x) < 0.0000001) {
  56305. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56306. return false;
  56307. }
  56308. }
  56309. else {
  56310. inv = 1.0 / this.direction.x;
  56311. min = (minimum.x - this.origin.x) * inv;
  56312. max = (maximum.x - this.origin.x) * inv;
  56313. if (max === -Infinity) {
  56314. max = Infinity;
  56315. }
  56316. if (min > max) {
  56317. temp = min;
  56318. min = max;
  56319. max = temp;
  56320. }
  56321. d = Math.max(min, d);
  56322. maxValue = Math.min(max, maxValue);
  56323. if (d > maxValue) {
  56324. return false;
  56325. }
  56326. }
  56327. if (Math.abs(this.direction.y) < 0.0000001) {
  56328. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56329. return false;
  56330. }
  56331. }
  56332. else {
  56333. inv = 1.0 / this.direction.y;
  56334. min = (minimum.y - this.origin.y) * inv;
  56335. max = (maximum.y - this.origin.y) * inv;
  56336. if (max === -Infinity) {
  56337. max = Infinity;
  56338. }
  56339. if (min > max) {
  56340. temp = min;
  56341. min = max;
  56342. max = temp;
  56343. }
  56344. d = Math.max(min, d);
  56345. maxValue = Math.min(max, maxValue);
  56346. if (d > maxValue) {
  56347. return false;
  56348. }
  56349. }
  56350. if (Math.abs(this.direction.z) < 0.0000001) {
  56351. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56352. return false;
  56353. }
  56354. }
  56355. else {
  56356. inv = 1.0 / this.direction.z;
  56357. min = (minimum.z - this.origin.z) * inv;
  56358. max = (maximum.z - this.origin.z) * inv;
  56359. if (max === -Infinity) {
  56360. max = Infinity;
  56361. }
  56362. if (min > max) {
  56363. temp = min;
  56364. min = max;
  56365. max = temp;
  56366. }
  56367. d = Math.max(min, d);
  56368. maxValue = Math.min(max, maxValue);
  56369. if (d > maxValue) {
  56370. return false;
  56371. }
  56372. }
  56373. return true;
  56374. };
  56375. Ray.prototype.intersectsBox = function (box) {
  56376. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56377. };
  56378. Ray.prototype.intersectsSphere = function (sphere) {
  56379. var x = sphere.center.x - this.origin.x;
  56380. var y = sphere.center.y - this.origin.y;
  56381. var z = sphere.center.z - this.origin.z;
  56382. var pyth = (x * x) + (y * y) + (z * z);
  56383. var rr = sphere.radius * sphere.radius;
  56384. if (pyth <= rr) {
  56385. return true;
  56386. }
  56387. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56388. if (dot < 0.0) {
  56389. return false;
  56390. }
  56391. var temp = pyth - (dot * dot);
  56392. return temp <= rr;
  56393. };
  56394. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56395. if (!this._edge1) {
  56396. this._edge1 = BABYLON.Vector3.Zero();
  56397. this._edge2 = BABYLON.Vector3.Zero();
  56398. this._pvec = BABYLON.Vector3.Zero();
  56399. this._tvec = BABYLON.Vector3.Zero();
  56400. this._qvec = BABYLON.Vector3.Zero();
  56401. }
  56402. vertex1.subtractToRef(vertex0, this._edge1);
  56403. vertex2.subtractToRef(vertex0, this._edge2);
  56404. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56405. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56406. if (det === 0) {
  56407. return null;
  56408. }
  56409. var invdet = 1 / det;
  56410. this.origin.subtractToRef(vertex0, this._tvec);
  56411. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56412. if (bu < 0 || bu > 1.0) {
  56413. return null;
  56414. }
  56415. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56416. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56417. if (bv < 0 || bu + bv > 1.0) {
  56418. return null;
  56419. }
  56420. //check if the distance is longer than the predefined length.
  56421. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56422. if (distance > this.length) {
  56423. return null;
  56424. }
  56425. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56426. };
  56427. Ray.prototype.intersectsPlane = function (plane) {
  56428. var distance;
  56429. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56430. if (Math.abs(result1) < 9.99999997475243E-07) {
  56431. return null;
  56432. }
  56433. else {
  56434. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56435. distance = (-plane.d - result2) / result1;
  56436. if (distance < 0.0) {
  56437. if (distance < -9.99999997475243E-07) {
  56438. return null;
  56439. }
  56440. else {
  56441. return 0;
  56442. }
  56443. }
  56444. return distance;
  56445. }
  56446. };
  56447. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56448. var tm = BABYLON.Tmp.Matrix[0];
  56449. mesh.getWorldMatrix().invertToRef(tm);
  56450. if (this._tmpRay) {
  56451. Ray.TransformToRef(this, tm, this._tmpRay);
  56452. }
  56453. else {
  56454. this._tmpRay = Ray.Transform(this, tm);
  56455. }
  56456. return mesh.intersects(this._tmpRay, fastCheck);
  56457. };
  56458. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56459. if (results) {
  56460. results.length = 0;
  56461. }
  56462. else {
  56463. results = [];
  56464. }
  56465. for (var i = 0; i < meshes.length; i++) {
  56466. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56467. if (pickInfo.hit) {
  56468. results.push(pickInfo);
  56469. }
  56470. }
  56471. results.sort(this._comparePickingInfo);
  56472. return results;
  56473. };
  56474. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56475. if (pickingInfoA.distance < pickingInfoB.distance) {
  56476. return -1;
  56477. }
  56478. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56479. return 1;
  56480. }
  56481. else {
  56482. return 0;
  56483. }
  56484. };
  56485. /**
  56486. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56487. * @param sega the first point of the segment to test the intersection against
  56488. * @param segb the second point of the segment to test the intersection against
  56489. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56490. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56491. */
  56492. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56493. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56494. var u = segb.subtract(sega);
  56495. var v = rsegb.subtract(this.origin);
  56496. var w = sega.subtract(this.origin);
  56497. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56498. var b = BABYLON.Vector3.Dot(u, v);
  56499. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56500. var d = BABYLON.Vector3.Dot(u, w);
  56501. var e = BABYLON.Vector3.Dot(v, w);
  56502. var D = a * c - b * b; // always >= 0
  56503. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56504. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56505. // compute the line parameters of the two closest points
  56506. if (D < Ray.smallnum) { // the lines are almost parallel
  56507. sN = 0.0; // force using point P0 on segment S1
  56508. sD = 1.0; // to prevent possible division by 0.0 later
  56509. tN = e;
  56510. tD = c;
  56511. }
  56512. else { // get the closest points on the infinite lines
  56513. sN = (b * e - c * d);
  56514. tN = (a * e - b * d);
  56515. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56516. sN = 0.0;
  56517. tN = e;
  56518. tD = c;
  56519. }
  56520. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56521. sN = sD;
  56522. tN = e + b;
  56523. tD = c;
  56524. }
  56525. }
  56526. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56527. tN = 0.0;
  56528. // recompute sc for this edge
  56529. if (-d < 0.0) {
  56530. sN = 0.0;
  56531. }
  56532. else if (-d > a)
  56533. sN = sD;
  56534. else {
  56535. sN = -d;
  56536. sD = a;
  56537. }
  56538. }
  56539. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56540. tN = tD;
  56541. // recompute sc for this edge
  56542. if ((-d + b) < 0.0) {
  56543. sN = 0;
  56544. }
  56545. else if ((-d + b) > a) {
  56546. sN = sD;
  56547. }
  56548. else {
  56549. sN = (-d + b);
  56550. sD = a;
  56551. }
  56552. }
  56553. // finally do the division to get sc and tc
  56554. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56555. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56556. // get the difference of the two closest points
  56557. var qtc = v.multiplyByFloats(tc, tc, tc);
  56558. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56559. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56560. if (isIntersected) {
  56561. return qtc.length();
  56562. }
  56563. return -1;
  56564. };
  56565. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56566. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56567. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56568. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56569. this.direction.normalize();
  56570. return this;
  56571. };
  56572. // Statics
  56573. Ray.Zero = function () {
  56574. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56575. };
  56576. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56577. var result = Ray.Zero();
  56578. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56579. };
  56580. /**
  56581. * 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
  56582. * transformed to the given world matrix.
  56583. * @param origin The origin point
  56584. * @param end The end point
  56585. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56586. */
  56587. Ray.CreateNewFromTo = function (origin, end, world) {
  56588. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56589. var direction = end.subtract(origin);
  56590. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56591. direction.normalize();
  56592. return Ray.Transform(new Ray(origin, direction, length), world);
  56593. };
  56594. Ray.Transform = function (ray, matrix) {
  56595. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56596. Ray.TransformToRef(ray, matrix, result);
  56597. return result;
  56598. };
  56599. Ray.TransformToRef = function (ray, matrix, result) {
  56600. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56601. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56602. result.length = ray.length;
  56603. var dir = result.direction;
  56604. var len = dir.length();
  56605. if (!(len === 0 || len === 1)) {
  56606. var num = 1.0 / len;
  56607. dir.x *= num;
  56608. dir.y *= num;
  56609. dir.z *= num;
  56610. result.length *= len;
  56611. }
  56612. };
  56613. Ray.smallnum = 0.00000001;
  56614. Ray.rayl = 10e8;
  56615. return Ray;
  56616. }());
  56617. BABYLON.Ray = Ray;
  56618. })(BABYLON || (BABYLON = {}));
  56619. //# sourceMappingURL=babylon.ray.js.map
  56620. var BABYLON;
  56621. (function (BABYLON) {
  56622. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56623. if (boxMin.x > sphereCenter.x + sphereRadius)
  56624. return false;
  56625. if (sphereCenter.x - sphereRadius > boxMax.x)
  56626. return false;
  56627. if (boxMin.y > sphereCenter.y + sphereRadius)
  56628. return false;
  56629. if (sphereCenter.y - sphereRadius > boxMax.y)
  56630. return false;
  56631. if (boxMin.z > sphereCenter.z + sphereRadius)
  56632. return false;
  56633. if (sphereCenter.z - sphereRadius > boxMax.z)
  56634. return false;
  56635. return true;
  56636. };
  56637. var getLowestRoot = (function () {
  56638. var result = { root: 0, found: false };
  56639. return function (a, b, c, maxR) {
  56640. result.root = 0;
  56641. result.found = false;
  56642. var determinant = b * b - 4.0 * a * c;
  56643. if (determinant < 0)
  56644. return result;
  56645. var sqrtD = Math.sqrt(determinant);
  56646. var r1 = (-b - sqrtD) / (2.0 * a);
  56647. var r2 = (-b + sqrtD) / (2.0 * a);
  56648. if (r1 > r2) {
  56649. var temp = r2;
  56650. r2 = r1;
  56651. r1 = temp;
  56652. }
  56653. if (r1 > 0 && r1 < maxR) {
  56654. result.root = r1;
  56655. result.found = true;
  56656. return result;
  56657. }
  56658. if (r2 > 0 && r2 < maxR) {
  56659. result.root = r2;
  56660. result.found = true;
  56661. return result;
  56662. }
  56663. return result;
  56664. };
  56665. })();
  56666. /** @hidden */
  56667. var Collider = /** @class */ (function () {
  56668. function Collider() {
  56669. this._collisionPoint = BABYLON.Vector3.Zero();
  56670. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56671. this._tempVector = BABYLON.Vector3.Zero();
  56672. this._tempVector2 = BABYLON.Vector3.Zero();
  56673. this._tempVector3 = BABYLON.Vector3.Zero();
  56674. this._tempVector4 = BABYLON.Vector3.Zero();
  56675. this._edge = BABYLON.Vector3.Zero();
  56676. this._baseToVertex = BABYLON.Vector3.Zero();
  56677. this._destinationPoint = BABYLON.Vector3.Zero();
  56678. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56679. this._displacementVector = BABYLON.Vector3.Zero();
  56680. /** @hidden */
  56681. this._radius = BABYLON.Vector3.One();
  56682. /** @hidden */
  56683. this._retry = 0;
  56684. /** @hidden */
  56685. this._basePointWorld = BABYLON.Vector3.Zero();
  56686. this._velocityWorld = BABYLON.Vector3.Zero();
  56687. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56688. this._collisionMask = -1;
  56689. }
  56690. Object.defineProperty(Collider.prototype, "collisionMask", {
  56691. get: function () {
  56692. return this._collisionMask;
  56693. },
  56694. set: function (mask) {
  56695. this._collisionMask = !isNaN(mask) ? mask : -1;
  56696. },
  56697. enumerable: true,
  56698. configurable: true
  56699. });
  56700. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56701. /**
  56702. * Gets the plane normal used to compute the sliding response (in local space)
  56703. */
  56704. get: function () {
  56705. return this._slidePlaneNormal;
  56706. },
  56707. enumerable: true,
  56708. configurable: true
  56709. });
  56710. // Methods
  56711. /** @hidden */
  56712. Collider.prototype._initialize = function (source, dir, e) {
  56713. this._velocity = dir;
  56714. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56715. this._basePoint = source;
  56716. source.multiplyToRef(this._radius, this._basePointWorld);
  56717. dir.multiplyToRef(this._radius, this._velocityWorld);
  56718. this._velocityWorldLength = this._velocityWorld.length();
  56719. this._epsilon = e;
  56720. this.collisionFound = false;
  56721. };
  56722. /** @hidden */
  56723. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56724. pa.subtractToRef(point, this._tempVector);
  56725. pb.subtractToRef(point, this._tempVector2);
  56726. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56727. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56728. if (d < 0)
  56729. return false;
  56730. pc.subtractToRef(point, this._tempVector3);
  56731. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56732. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56733. if (d < 0)
  56734. return false;
  56735. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56736. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56737. return d >= 0;
  56738. };
  56739. /** @hidden */
  56740. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56741. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56742. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56743. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56744. return false;
  56745. }
  56746. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56747. return false;
  56748. return true;
  56749. };
  56750. /** @hidden */
  56751. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56752. var t0;
  56753. var embeddedInPlane = false;
  56754. //defensive programming, actually not needed.
  56755. if (!trianglePlaneArray) {
  56756. trianglePlaneArray = [];
  56757. }
  56758. if (!trianglePlaneArray[faceIndex]) {
  56759. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56760. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56761. }
  56762. var trianglePlane = trianglePlaneArray[faceIndex];
  56763. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56764. return;
  56765. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56766. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56767. if (normalDotVelocity == 0) {
  56768. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56769. return;
  56770. embeddedInPlane = true;
  56771. t0 = 0;
  56772. }
  56773. else {
  56774. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56775. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56776. if (t0 > t1) {
  56777. var temp = t1;
  56778. t1 = t0;
  56779. t0 = temp;
  56780. }
  56781. if (t0 > 1.0 || t1 < 0.0)
  56782. return;
  56783. if (t0 < 0)
  56784. t0 = 0;
  56785. if (t0 > 1.0)
  56786. t0 = 1.0;
  56787. }
  56788. this._collisionPoint.copyFromFloats(0, 0, 0);
  56789. var found = false;
  56790. var t = 1.0;
  56791. if (!embeddedInPlane) {
  56792. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56793. this._velocity.scaleToRef(t0, this._tempVector);
  56794. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56795. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56796. found = true;
  56797. t = t0;
  56798. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56799. }
  56800. }
  56801. if (!found) {
  56802. var velocitySquaredLength = this._velocity.lengthSquared();
  56803. var a = velocitySquaredLength;
  56804. this._basePoint.subtractToRef(p1, this._tempVector);
  56805. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56806. var c = this._tempVector.lengthSquared() - 1.0;
  56807. var lowestRoot = getLowestRoot(a, b, c, t);
  56808. if (lowestRoot.found) {
  56809. t = lowestRoot.root;
  56810. found = true;
  56811. this._collisionPoint.copyFrom(p1);
  56812. }
  56813. this._basePoint.subtractToRef(p2, this._tempVector);
  56814. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56815. c = this._tempVector.lengthSquared() - 1.0;
  56816. lowestRoot = getLowestRoot(a, b, c, t);
  56817. if (lowestRoot.found) {
  56818. t = lowestRoot.root;
  56819. found = true;
  56820. this._collisionPoint.copyFrom(p2);
  56821. }
  56822. this._basePoint.subtractToRef(p3, this._tempVector);
  56823. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56824. c = this._tempVector.lengthSquared() - 1.0;
  56825. lowestRoot = getLowestRoot(a, b, c, t);
  56826. if (lowestRoot.found) {
  56827. t = lowestRoot.root;
  56828. found = true;
  56829. this._collisionPoint.copyFrom(p3);
  56830. }
  56831. p2.subtractToRef(p1, this._edge);
  56832. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56833. var edgeSquaredLength = this._edge.lengthSquared();
  56834. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56835. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56836. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56837. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56838. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56839. lowestRoot = getLowestRoot(a, b, c, t);
  56840. if (lowestRoot.found) {
  56841. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56842. if (f >= 0.0 && f <= 1.0) {
  56843. t = lowestRoot.root;
  56844. found = true;
  56845. this._edge.scaleInPlace(f);
  56846. p1.addToRef(this._edge, this._collisionPoint);
  56847. }
  56848. }
  56849. p3.subtractToRef(p2, this._edge);
  56850. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56851. edgeSquaredLength = this._edge.lengthSquared();
  56852. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56853. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56854. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56855. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56856. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56857. lowestRoot = getLowestRoot(a, b, c, t);
  56858. if (lowestRoot.found) {
  56859. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56860. if (f >= 0.0 && f <= 1.0) {
  56861. t = lowestRoot.root;
  56862. found = true;
  56863. this._edge.scaleInPlace(f);
  56864. p2.addToRef(this._edge, this._collisionPoint);
  56865. }
  56866. }
  56867. p1.subtractToRef(p3, this._edge);
  56868. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56869. edgeSquaredLength = this._edge.lengthSquared();
  56870. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56871. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56872. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56873. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56874. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56875. lowestRoot = getLowestRoot(a, b, c, t);
  56876. if (lowestRoot.found) {
  56877. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56878. if (f >= 0.0 && f <= 1.0) {
  56879. t = lowestRoot.root;
  56880. found = true;
  56881. this._edge.scaleInPlace(f);
  56882. p3.addToRef(this._edge, this._collisionPoint);
  56883. }
  56884. }
  56885. }
  56886. if (found) {
  56887. var distToCollision = t * this._velocity.length();
  56888. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56889. if (!this.intersectionPoint) {
  56890. this.intersectionPoint = this._collisionPoint.clone();
  56891. }
  56892. else {
  56893. this.intersectionPoint.copyFrom(this._collisionPoint);
  56894. }
  56895. this._nearestDistance = distToCollision;
  56896. this.collisionFound = true;
  56897. }
  56898. }
  56899. };
  56900. /** @hidden */
  56901. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56902. for (var i = indexStart; i < indexEnd; i += 3) {
  56903. var p1 = pts[indices[i] - decal];
  56904. var p2 = pts[indices[i + 1] - decal];
  56905. var p3 = pts[indices[i + 2] - decal];
  56906. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56907. }
  56908. };
  56909. /** @hidden */
  56910. Collider.prototype._getResponse = function (pos, vel) {
  56911. pos.addToRef(vel, this._destinationPoint);
  56912. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56913. this._basePoint.addToRef(vel, pos);
  56914. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56915. this._slidePlaneNormal.normalize();
  56916. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56917. pos.addInPlace(this._displacementVector);
  56918. this.intersectionPoint.addInPlace(this._displacementVector);
  56919. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56920. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56921. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56922. };
  56923. return Collider;
  56924. }());
  56925. BABYLON.Collider = Collider;
  56926. })(BABYLON || (BABYLON = {}));
  56927. //# sourceMappingURL=babylon.collider.js.map
  56928. var BABYLON;
  56929. (function (BABYLON) {
  56930. //WebWorker code will be inserted to this variable.
  56931. /** @hidden */
  56932. BABYLON.CollisionWorker = "";
  56933. /** Defines supported task for worker process */
  56934. var WorkerTaskType;
  56935. (function (WorkerTaskType) {
  56936. /** Initialization */
  56937. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56938. /** Update of geometry */
  56939. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56940. /** Evaluate collision */
  56941. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56942. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56943. /** Defines kind of replies returned by worker */
  56944. var WorkerReplyType;
  56945. (function (WorkerReplyType) {
  56946. /** Success */
  56947. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56948. /** Unkown error */
  56949. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56950. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56951. /** @hidden */
  56952. var CollisionCoordinatorWorker = /** @class */ (function () {
  56953. function CollisionCoordinatorWorker() {
  56954. var _this = this;
  56955. this._scaledPosition = BABYLON.Vector3.Zero();
  56956. this._scaledVelocity = BABYLON.Vector3.Zero();
  56957. this.onMeshUpdated = function (transformNode) {
  56958. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56959. };
  56960. this.onGeometryUpdated = function (geometry) {
  56961. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56962. };
  56963. this._afterRender = function () {
  56964. if (!_this._init)
  56965. return;
  56966. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56967. return;
  56968. }
  56969. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56970. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56971. if (_this._runningUpdated > 4) {
  56972. return;
  56973. }
  56974. ++_this._runningUpdated;
  56975. var payload = {
  56976. updatedMeshes: _this._addUpdateMeshesList,
  56977. updatedGeometries: _this._addUpdateGeometriesList,
  56978. removedGeometries: _this._toRemoveGeometryArray,
  56979. removedMeshes: _this._toRemoveMeshesArray
  56980. };
  56981. var message = {
  56982. payload: payload,
  56983. taskType: WorkerTaskType.UPDATE
  56984. };
  56985. var serializable = [];
  56986. for (var id in payload.updatedGeometries) {
  56987. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56988. //prepare transferables
  56989. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56990. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56991. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56992. }
  56993. }
  56994. _this._worker.postMessage(message, serializable);
  56995. _this._addUpdateMeshesList = {};
  56996. _this._addUpdateGeometriesList = {};
  56997. _this._toRemoveGeometryArray = [];
  56998. _this._toRemoveMeshesArray = [];
  56999. };
  57000. this._onMessageFromWorker = function (e) {
  57001. var returnData = e.data;
  57002. if (returnData.error != WorkerReplyType.SUCCESS) {
  57003. //TODO what errors can be returned from the worker?
  57004. BABYLON.Tools.Warn("error returned from worker!");
  57005. return;
  57006. }
  57007. switch (returnData.taskType) {
  57008. case WorkerTaskType.INIT:
  57009. _this._init = true;
  57010. //Update the worked with ALL of the scene's current state
  57011. _this._scene.meshes.forEach(function (mesh) {
  57012. _this.onMeshAdded(mesh);
  57013. });
  57014. _this._scene.getGeometries().forEach(function (geometry) {
  57015. _this.onGeometryAdded(geometry);
  57016. });
  57017. break;
  57018. case WorkerTaskType.UPDATE:
  57019. _this._runningUpdated--;
  57020. break;
  57021. case WorkerTaskType.COLLIDE:
  57022. var returnPayload = returnData.payload;
  57023. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57024. return;
  57025. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57026. if (callback) {
  57027. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57028. if (mesh) {
  57029. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57030. }
  57031. }
  57032. //cleanup
  57033. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57034. break;
  57035. }
  57036. };
  57037. this._collisionsCallbackArray = [];
  57038. this._init = false;
  57039. this._runningUpdated = 0;
  57040. this._addUpdateMeshesList = {};
  57041. this._addUpdateGeometriesList = {};
  57042. this._toRemoveGeometryArray = [];
  57043. this._toRemoveMeshesArray = [];
  57044. }
  57045. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57046. if (!this._init)
  57047. return;
  57048. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57049. return;
  57050. position.divideToRef(collider._radius, this._scaledPosition);
  57051. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57052. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57053. var payload = {
  57054. collider: {
  57055. position: this._scaledPosition.asArray(),
  57056. velocity: this._scaledVelocity.asArray(),
  57057. radius: collider._radius.asArray()
  57058. },
  57059. collisionId: collisionIndex,
  57060. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57061. maximumRetry: maximumRetry
  57062. };
  57063. var message = {
  57064. payload: payload,
  57065. taskType: WorkerTaskType.COLLIDE
  57066. };
  57067. this._worker.postMessage(message);
  57068. };
  57069. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57070. this._scene = scene;
  57071. this._scene.registerAfterRender(this._afterRender);
  57072. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57073. this._worker = new Worker(workerUrl);
  57074. this._worker.onmessage = this._onMessageFromWorker;
  57075. var message = {
  57076. payload: {},
  57077. taskType: WorkerTaskType.INIT
  57078. };
  57079. this._worker.postMessage(message);
  57080. };
  57081. CollisionCoordinatorWorker.prototype.destroy = function () {
  57082. this._scene.unregisterAfterRender(this._afterRender);
  57083. this._worker.terminate();
  57084. };
  57085. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57086. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57087. this.onMeshUpdated(mesh);
  57088. };
  57089. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57090. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57091. };
  57092. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57093. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57094. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57095. this.onGeometryUpdated(geometry);
  57096. };
  57097. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57098. this._toRemoveGeometryArray.push(geometry.id);
  57099. };
  57100. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57101. var submeshes = [];
  57102. if (mesh.subMeshes) {
  57103. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57104. var boundingInfo = sm.getBoundingInfo();
  57105. return {
  57106. position: idx,
  57107. verticesStart: sm.verticesStart,
  57108. verticesCount: sm.verticesCount,
  57109. indexStart: sm.indexStart,
  57110. indexCount: sm.indexCount,
  57111. hasMaterial: !!sm.getMaterial(),
  57112. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57113. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57114. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57115. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57116. };
  57117. });
  57118. }
  57119. var geometryId = null;
  57120. if (mesh instanceof BABYLON.Mesh) {
  57121. var geometry = mesh.geometry;
  57122. geometryId = geometry ? geometry.id : null;
  57123. }
  57124. else if (mesh instanceof BABYLON.InstancedMesh) {
  57125. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57126. geometryId = geometry ? geometry.id : null;
  57127. }
  57128. var boundingInfo = mesh.getBoundingInfo();
  57129. return {
  57130. uniqueId: mesh.uniqueId,
  57131. id: mesh.id,
  57132. name: mesh.name,
  57133. geometryId: geometryId,
  57134. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57135. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57136. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57137. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57138. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57139. subMeshes: submeshes,
  57140. checkCollisions: mesh.checkCollisions
  57141. };
  57142. };
  57143. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57144. return {
  57145. id: geometry.id,
  57146. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57147. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57148. indices: new Uint32Array(geometry.getIndices() || []),
  57149. };
  57150. };
  57151. return CollisionCoordinatorWorker;
  57152. }());
  57153. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57154. /** @hidden */
  57155. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57156. function CollisionCoordinatorLegacy() {
  57157. this._scaledPosition = BABYLON.Vector3.Zero();
  57158. this._scaledVelocity = BABYLON.Vector3.Zero();
  57159. this._finalPosition = BABYLON.Vector3.Zero();
  57160. }
  57161. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57162. position.divideToRef(collider._radius, this._scaledPosition);
  57163. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57164. collider.collidedMesh = null;
  57165. collider._retry = 0;
  57166. collider._initialVelocity = this._scaledVelocity;
  57167. collider._initialPosition = this._scaledPosition;
  57168. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57169. this._finalPosition.multiplyInPlace(collider._radius);
  57170. //run the callback
  57171. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57172. };
  57173. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57174. this._scene = scene;
  57175. };
  57176. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57177. //Legacy need no destruction method.
  57178. };
  57179. //No update in legacy mode
  57180. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57181. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57182. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57183. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57184. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57185. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57186. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57187. if (excludedMesh === void 0) { excludedMesh = null; }
  57188. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57189. if (collider._retry >= maximumRetry) {
  57190. finalPosition.copyFrom(position);
  57191. return;
  57192. }
  57193. // Check if this is a mesh else camera or -1
  57194. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57195. collider._initialize(position, velocity, closeDistance);
  57196. // Check all meshes
  57197. for (var index = 0; index < this._scene.meshes.length; index++) {
  57198. var mesh = this._scene.meshes[index];
  57199. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57200. mesh._checkCollision(collider);
  57201. }
  57202. }
  57203. if (!collider.collisionFound) {
  57204. position.addToRef(velocity, finalPosition);
  57205. return;
  57206. }
  57207. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57208. collider._getResponse(position, velocity);
  57209. }
  57210. if (velocity.length() <= closeDistance) {
  57211. finalPosition.copyFrom(position);
  57212. return;
  57213. }
  57214. collider._retry++;
  57215. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57216. };
  57217. return CollisionCoordinatorLegacy;
  57218. }());
  57219. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57220. })(BABYLON || (BABYLON = {}));
  57221. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57222. var BABYLON;
  57223. (function (BABYLON) {
  57224. /**
  57225. * A particle represents one of the element emitted by a particle system.
  57226. * This is mainly define by its coordinates, direction, velocity and age.
  57227. */
  57228. var Particle = /** @class */ (function () {
  57229. /**
  57230. * Creates a new instance Particle
  57231. * @param particleSystem the particle system the particle belongs to
  57232. */
  57233. function Particle(
  57234. /**
  57235. * The particle system the particle belongs to.
  57236. */
  57237. particleSystem) {
  57238. this.particleSystem = particleSystem;
  57239. /**
  57240. * The world position of the particle in the scene.
  57241. */
  57242. this.position = BABYLON.Vector3.Zero();
  57243. /**
  57244. * The world direction of the particle in the scene.
  57245. */
  57246. this.direction = BABYLON.Vector3.Zero();
  57247. /**
  57248. * The color of the particle.
  57249. */
  57250. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57251. /**
  57252. * The color change of the particle per step.
  57253. */
  57254. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57255. /**
  57256. * Defines how long will the life of the particle be.
  57257. */
  57258. this.lifeTime = 1.0;
  57259. /**
  57260. * The current age of the particle.
  57261. */
  57262. this.age = 0;
  57263. /**
  57264. * The current size of the particle.
  57265. */
  57266. this.size = 0;
  57267. /**
  57268. * The current scale of the particle.
  57269. */
  57270. this.scale = new BABYLON.Vector2(1, 1);
  57271. /**
  57272. * The current angle of the particle.
  57273. */
  57274. this.angle = 0;
  57275. /**
  57276. * Defines how fast is the angle changing.
  57277. */
  57278. this.angularSpeed = 0;
  57279. /**
  57280. * Defines the cell index used by the particle to be rendered from a sprite.
  57281. */
  57282. this.cellIndex = 0;
  57283. /** @hidden */
  57284. this._attachedSubEmitters = null;
  57285. /** @hidden */
  57286. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57287. /** @hidden */
  57288. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57289. /** @hidden */
  57290. this._currentSize1 = 0;
  57291. /** @hidden */
  57292. this._currentSize2 = 0;
  57293. /** @hidden */
  57294. this._currentAngularSpeed1 = 0;
  57295. /** @hidden */
  57296. this._currentAngularSpeed2 = 0;
  57297. /** @hidden */
  57298. this._currentVelocity1 = 0;
  57299. /** @hidden */
  57300. this._currentVelocity2 = 0;
  57301. /** @hidden */
  57302. this._currentLimitVelocity1 = 0;
  57303. /** @hidden */
  57304. this._currentLimitVelocity2 = 0;
  57305. /** @hidden */
  57306. this._currentDrag1 = 0;
  57307. /** @hidden */
  57308. this._currentDrag2 = 0;
  57309. this.id = Particle._Count++;
  57310. if (!this.particleSystem.isAnimationSheetEnabled) {
  57311. return;
  57312. }
  57313. this.updateCellInfoFromSystem();
  57314. }
  57315. Particle.prototype.updateCellInfoFromSystem = function () {
  57316. this.cellIndex = this.particleSystem.startSpriteCellID;
  57317. };
  57318. /**
  57319. * Defines how the sprite cell index is updated for the particle
  57320. */
  57321. Particle.prototype.updateCellIndex = function () {
  57322. var offsetAge = this.age;
  57323. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57324. if (this.particleSystem.spriteRandomStartCell) {
  57325. if (this._randomCellOffset === undefined) {
  57326. this._randomCellOffset = Math.random() * this.lifeTime;
  57327. }
  57328. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57329. changeSpeed = 1;
  57330. offsetAge = this._randomCellOffset;
  57331. }
  57332. else {
  57333. offsetAge += this._randomCellOffset;
  57334. }
  57335. }
  57336. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57337. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57338. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57339. };
  57340. /** @hidden */
  57341. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57342. if (subEmitter.particleSystem.emitter.position) {
  57343. var emitterMesh = subEmitter.particleSystem.emitter;
  57344. emitterMesh.position.copyFrom(this.position);
  57345. if (subEmitter.inheritDirection) {
  57346. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57347. // Look at using Y as forward
  57348. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57349. }
  57350. }
  57351. else {
  57352. var emitterPosition = subEmitter.particleSystem.emitter;
  57353. emitterPosition.copyFrom(this.position);
  57354. }
  57355. // Set inheritedVelocityOffset to be used when new particles are created
  57356. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57357. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57358. };
  57359. /** @hidden */
  57360. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57361. var _this = this;
  57362. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57363. this._attachedSubEmitters.forEach(function (subEmitter) {
  57364. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57365. });
  57366. }
  57367. };
  57368. /** @hidden */
  57369. Particle.prototype._reset = function () {
  57370. this.age = 0;
  57371. this._currentColorGradient = null;
  57372. this._currentSizeGradient = null;
  57373. this._currentAngularSpeedGradient = null;
  57374. this._currentVelocityGradient = null;
  57375. this._currentLimitVelocityGradient = null;
  57376. this._currentDragGradient = null;
  57377. this.cellIndex = this.particleSystem.startSpriteCellID;
  57378. this._randomCellOffset = undefined;
  57379. };
  57380. /**
  57381. * Copy the properties of particle to another one.
  57382. * @param other the particle to copy the information to.
  57383. */
  57384. Particle.prototype.copyTo = function (other) {
  57385. other.position.copyFrom(this.position);
  57386. if (this._initialDirection) {
  57387. if (other._initialDirection) {
  57388. other._initialDirection.copyFrom(this._initialDirection);
  57389. }
  57390. else {
  57391. other._initialDirection = this._initialDirection.clone();
  57392. }
  57393. }
  57394. else {
  57395. other._initialDirection = null;
  57396. }
  57397. other.direction.copyFrom(this.direction);
  57398. other.color.copyFrom(this.color);
  57399. other.colorStep.copyFrom(this.colorStep);
  57400. other.lifeTime = this.lifeTime;
  57401. other.age = this.age;
  57402. other._randomCellOffset = this._randomCellOffset;
  57403. other.size = this.size;
  57404. other.scale.copyFrom(this.scale);
  57405. other.angle = this.angle;
  57406. other.angularSpeed = this.angularSpeed;
  57407. other.particleSystem = this.particleSystem;
  57408. other.cellIndex = this.cellIndex;
  57409. other.id = this.id;
  57410. other._attachedSubEmitters = this._attachedSubEmitters;
  57411. if (this._currentColorGradient) {
  57412. other._currentColorGradient = this._currentColorGradient;
  57413. other._currentColor1.copyFrom(this._currentColor1);
  57414. other._currentColor2.copyFrom(this._currentColor2);
  57415. }
  57416. if (this._currentSizeGradient) {
  57417. other._currentSizeGradient = this._currentSizeGradient;
  57418. other._currentSize1 = this._currentSize1;
  57419. other._currentSize2 = this._currentSize2;
  57420. }
  57421. if (this._currentAngularSpeedGradient) {
  57422. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57423. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57424. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57425. }
  57426. if (this._currentVelocityGradient) {
  57427. other._currentVelocityGradient = this._currentVelocityGradient;
  57428. other._currentVelocity1 = this._currentVelocity1;
  57429. other._currentVelocity2 = this._currentVelocity2;
  57430. }
  57431. if (this._currentLimitVelocityGradient) {
  57432. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57433. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57434. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57435. }
  57436. if (this._currentDragGradient) {
  57437. other._currentDragGradient = this._currentDragGradient;
  57438. other._currentDrag1 = this._currentDrag1;
  57439. other._currentDrag2 = this._currentDrag2;
  57440. }
  57441. if (this.particleSystem.isAnimationSheetEnabled) {
  57442. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57443. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57444. }
  57445. if (this.particleSystem.useRampGradients) {
  57446. other.remapData.copyFrom(this.remapData);
  57447. }
  57448. if (this._randomNoiseCoordinates1) {
  57449. if (other._randomNoiseCoordinates1) {
  57450. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57451. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57452. }
  57453. else {
  57454. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57455. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57456. }
  57457. }
  57458. };
  57459. Particle._Count = 0;
  57460. return Particle;
  57461. }());
  57462. BABYLON.Particle = Particle;
  57463. })(BABYLON || (BABYLON = {}));
  57464. //# sourceMappingURL=babylon.particle.js.map
  57465. var BABYLON;
  57466. (function (BABYLON) {
  57467. /**
  57468. * This represents the base class for particle system in Babylon.
  57469. * 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.
  57470. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57471. * @example https://doc.babylonjs.com/babylon101/particles
  57472. */
  57473. var BaseParticleSystem = /** @class */ (function () {
  57474. /**
  57475. * Instantiates a particle system.
  57476. * 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.
  57477. * @param name The name of the particle system
  57478. */
  57479. function BaseParticleSystem(name) {
  57480. /**
  57481. * List of animations used by the particle system.
  57482. */
  57483. this.animations = [];
  57484. /**
  57485. * The rendering group used by the Particle system to chose when to render.
  57486. */
  57487. this.renderingGroupId = 0;
  57488. /**
  57489. * The emitter represents the Mesh or position we are attaching the particle system to.
  57490. */
  57491. this.emitter = null;
  57492. /**
  57493. * The maximum number of particles to emit per frame
  57494. */
  57495. this.emitRate = 10;
  57496. /**
  57497. * If you want to launch only a few particles at once, that can be done, as well.
  57498. */
  57499. this.manualEmitCount = -1;
  57500. /**
  57501. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57502. */
  57503. this.updateSpeed = 0.01;
  57504. /**
  57505. * The amount of time the particle system is running (depends of the overall update speed).
  57506. */
  57507. this.targetStopDuration = 0;
  57508. /**
  57509. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57510. */
  57511. this.disposeOnStop = false;
  57512. /**
  57513. * Minimum power of emitting particles.
  57514. */
  57515. this.minEmitPower = 1;
  57516. /**
  57517. * Maximum power of emitting particles.
  57518. */
  57519. this.maxEmitPower = 1;
  57520. /**
  57521. * Minimum life time of emitting particles.
  57522. */
  57523. this.minLifeTime = 1;
  57524. /**
  57525. * Maximum life time of emitting particles.
  57526. */
  57527. this.maxLifeTime = 1;
  57528. /**
  57529. * Minimum Size of emitting particles.
  57530. */
  57531. this.minSize = 1;
  57532. /**
  57533. * Maximum Size of emitting particles.
  57534. */
  57535. this.maxSize = 1;
  57536. /**
  57537. * Minimum scale of emitting particles on X axis.
  57538. */
  57539. this.minScaleX = 1;
  57540. /**
  57541. * Maximum scale of emitting particles on X axis.
  57542. */
  57543. this.maxScaleX = 1;
  57544. /**
  57545. * Minimum scale of emitting particles on Y axis.
  57546. */
  57547. this.minScaleY = 1;
  57548. /**
  57549. * Maximum scale of emitting particles on Y axis.
  57550. */
  57551. this.maxScaleY = 1;
  57552. /**
  57553. * Gets or sets the minimal initial rotation in radians.
  57554. */
  57555. this.minInitialRotation = 0;
  57556. /**
  57557. * Gets or sets the maximal initial rotation in radians.
  57558. */
  57559. this.maxInitialRotation = 0;
  57560. /**
  57561. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57562. */
  57563. this.minAngularSpeed = 0;
  57564. /**
  57565. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57566. */
  57567. this.maxAngularSpeed = 0;
  57568. /**
  57569. * The layer mask we are rendering the particles through.
  57570. */
  57571. this.layerMask = 0x0FFFFFFF;
  57572. /**
  57573. * This can help using your own shader to render the particle system.
  57574. * The according effect will be created
  57575. */
  57576. this.customShader = null;
  57577. /**
  57578. * By default particle system starts as soon as they are created. This prevents the
  57579. * automatic start to happen and let you decide when to start emitting particles.
  57580. */
  57581. this.preventAutoStart = false;
  57582. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57583. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57584. /**
  57585. * Callback triggered when the particle animation is ending.
  57586. */
  57587. this.onAnimationEnd = null;
  57588. /**
  57589. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57590. */
  57591. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57592. /**
  57593. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57594. * to override the particles.
  57595. */
  57596. this.forceDepthWrite = false;
  57597. /** 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 */
  57598. this.preWarmCycles = 0;
  57599. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57600. this.preWarmStepOffset = 1;
  57601. /**
  57602. * 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)
  57603. */
  57604. this.spriteCellChangeSpeed = 1;
  57605. /**
  57606. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57607. */
  57608. this.startSpriteCellID = 0;
  57609. /**
  57610. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57611. */
  57612. this.endSpriteCellID = 0;
  57613. /**
  57614. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57615. */
  57616. this.spriteCellWidth = 0;
  57617. /**
  57618. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57619. */
  57620. this.spriteCellHeight = 0;
  57621. /**
  57622. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57623. */
  57624. this.spriteRandomStartCell = false;
  57625. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57626. this.translationPivot = new BABYLON.Vector2(0, 0);
  57627. /**
  57628. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57629. */
  57630. this.beginAnimationOnStart = false;
  57631. /**
  57632. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57633. */
  57634. this.beginAnimationFrom = 0;
  57635. /**
  57636. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57637. */
  57638. this.beginAnimationTo = 60;
  57639. /**
  57640. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57641. */
  57642. this.beginAnimationLoop = false;
  57643. /**
  57644. * You can use gravity if you want to give an orientation to your particles.
  57645. */
  57646. this.gravity = BABYLON.Vector3.Zero();
  57647. this._colorGradients = null;
  57648. this._sizeGradients = null;
  57649. this._lifeTimeGradients = null;
  57650. this._angularSpeedGradients = null;
  57651. this._velocityGradients = null;
  57652. this._limitVelocityGradients = null;
  57653. this._dragGradients = null;
  57654. this._emitRateGradients = null;
  57655. this._startSizeGradients = null;
  57656. this._rampGradients = null;
  57657. this._colorRemapGradients = null;
  57658. this._alphaRemapGradients = null;
  57659. /**
  57660. * Defines the delay in milliseconds before starting the system (0 by default)
  57661. */
  57662. this.startDelay = 0;
  57663. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57664. this.limitVelocityDamping = 0.4;
  57665. /**
  57666. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57667. */
  57668. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57669. /**
  57670. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57671. */
  57672. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57673. /**
  57674. * Color the particle will have at the end of its lifetime
  57675. */
  57676. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57677. /**
  57678. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57679. */
  57680. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57681. /** @hidden */
  57682. this._isSubEmitter = false;
  57683. /**
  57684. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57685. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57686. */
  57687. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57688. this._isBillboardBased = true;
  57689. /**
  57690. * Local cache of defines for image processing.
  57691. */
  57692. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57693. this.id = name;
  57694. this.name = name;
  57695. }
  57696. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57697. /**
  57698. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57699. */
  57700. get: function () {
  57701. return this._isAnimationSheetEnabled;
  57702. },
  57703. set: function (value) {
  57704. if (this._isAnimationSheetEnabled == value) {
  57705. return;
  57706. }
  57707. this._isAnimationSheetEnabled = value;
  57708. this._reset();
  57709. },
  57710. enumerable: true,
  57711. configurable: true
  57712. });
  57713. /**
  57714. * Get hosting scene
  57715. * @returns the scene
  57716. */
  57717. BaseParticleSystem.prototype.getScene = function () {
  57718. return this._scene;
  57719. };
  57720. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57721. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57722. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57723. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57724. };
  57725. /**
  57726. * Gets the current list of drag gradients.
  57727. * You must use addDragGradient and removeDragGradient to udpate this list
  57728. * @returns the list of drag gradients
  57729. */
  57730. BaseParticleSystem.prototype.getDragGradients = function () {
  57731. return this._dragGradients;
  57732. };
  57733. /**
  57734. * Gets the current list of limit velocity gradients.
  57735. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57736. * @returns the list of limit velocity gradients
  57737. */
  57738. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57739. return this._limitVelocityGradients;
  57740. };
  57741. /**
  57742. * Gets the current list of color gradients.
  57743. * You must use addColorGradient and removeColorGradient to udpate this list
  57744. * @returns the list of color gradients
  57745. */
  57746. BaseParticleSystem.prototype.getColorGradients = function () {
  57747. return this._colorGradients;
  57748. };
  57749. /**
  57750. * Gets the current list of size gradients.
  57751. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57752. * @returns the list of size gradients
  57753. */
  57754. BaseParticleSystem.prototype.getSizeGradients = function () {
  57755. return this._sizeGradients;
  57756. };
  57757. /**
  57758. * Gets the current list of color remap gradients.
  57759. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57760. * @returns the list of color remap gradients
  57761. */
  57762. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57763. return this._colorRemapGradients;
  57764. };
  57765. /**
  57766. * Gets the current list of alpha remap gradients.
  57767. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57768. * @returns the list of alpha remap gradients
  57769. */
  57770. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57771. return this._alphaRemapGradients;
  57772. };
  57773. /**
  57774. * Gets the current list of life time gradients.
  57775. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57776. * @returns the list of life time gradients
  57777. */
  57778. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57779. return this._lifeTimeGradients;
  57780. };
  57781. /**
  57782. * Gets the current list of angular speed gradients.
  57783. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57784. * @returns the list of angular speed gradients
  57785. */
  57786. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57787. return this._angularSpeedGradients;
  57788. };
  57789. /**
  57790. * Gets the current list of velocity gradients.
  57791. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57792. * @returns the list of velocity gradients
  57793. */
  57794. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57795. return this._velocityGradients;
  57796. };
  57797. /**
  57798. * Gets the current list of start size gradients.
  57799. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57800. * @returns the list of start size gradients
  57801. */
  57802. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57803. return this._startSizeGradients;
  57804. };
  57805. /**
  57806. * Gets the current list of emit rate gradients.
  57807. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57808. * @returns the list of emit rate gradients
  57809. */
  57810. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57811. return this._emitRateGradients;
  57812. };
  57813. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57814. /**
  57815. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57816. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57817. */
  57818. get: function () {
  57819. if (this.particleEmitterType.direction1) {
  57820. return this.particleEmitterType.direction1;
  57821. }
  57822. return BABYLON.Vector3.Zero();
  57823. },
  57824. set: function (value) {
  57825. if (this.particleEmitterType.direction1) {
  57826. this.particleEmitterType.direction1 = value;
  57827. }
  57828. },
  57829. enumerable: true,
  57830. configurable: true
  57831. });
  57832. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57833. /**
  57834. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57835. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57836. */
  57837. get: function () {
  57838. if (this.particleEmitterType.direction2) {
  57839. return this.particleEmitterType.direction2;
  57840. }
  57841. return BABYLON.Vector3.Zero();
  57842. },
  57843. set: function (value) {
  57844. if (this.particleEmitterType.direction2) {
  57845. this.particleEmitterType.direction2 = value;
  57846. }
  57847. },
  57848. enumerable: true,
  57849. configurable: true
  57850. });
  57851. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57852. /**
  57853. * 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.
  57854. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57855. */
  57856. get: function () {
  57857. if (this.particleEmitterType.minEmitBox) {
  57858. return this.particleEmitterType.minEmitBox;
  57859. }
  57860. return BABYLON.Vector3.Zero();
  57861. },
  57862. set: function (value) {
  57863. if (this.particleEmitterType.minEmitBox) {
  57864. this.particleEmitterType.minEmitBox = value;
  57865. }
  57866. },
  57867. enumerable: true,
  57868. configurable: true
  57869. });
  57870. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57871. /**
  57872. * 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.
  57873. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57874. */
  57875. get: function () {
  57876. if (this.particleEmitterType.maxEmitBox) {
  57877. return this.particleEmitterType.maxEmitBox;
  57878. }
  57879. return BABYLON.Vector3.Zero();
  57880. },
  57881. set: function (value) {
  57882. if (this.particleEmitterType.maxEmitBox) {
  57883. this.particleEmitterType.maxEmitBox = value;
  57884. }
  57885. },
  57886. enumerable: true,
  57887. configurable: true
  57888. });
  57889. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57890. /**
  57891. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57892. */
  57893. get: function () {
  57894. return this._isBillboardBased;
  57895. },
  57896. set: function (value) {
  57897. if (this._isBillboardBased === value) {
  57898. return;
  57899. }
  57900. this._isBillboardBased = value;
  57901. this._reset();
  57902. },
  57903. enumerable: true,
  57904. configurable: true
  57905. });
  57906. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57907. /**
  57908. * Gets the image processing configuration used either in this material.
  57909. */
  57910. get: function () {
  57911. return this._imageProcessingConfiguration;
  57912. },
  57913. /**
  57914. * Sets the Default image processing configuration used either in the this material.
  57915. *
  57916. * If sets to null, the scene one is in use.
  57917. */
  57918. set: function (value) {
  57919. this._attachImageProcessingConfiguration(value);
  57920. },
  57921. enumerable: true,
  57922. configurable: true
  57923. });
  57924. /**
  57925. * Attaches a new image processing configuration to the Standard Material.
  57926. * @param configuration
  57927. */
  57928. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57929. if (configuration === this._imageProcessingConfiguration) {
  57930. return;
  57931. }
  57932. // Pick the scene configuration if needed.
  57933. if (!configuration) {
  57934. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57935. }
  57936. else {
  57937. this._imageProcessingConfiguration = configuration;
  57938. }
  57939. };
  57940. /** @hidden */
  57941. BaseParticleSystem.prototype._reset = function () {
  57942. };
  57943. /** @hidden */
  57944. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57945. if (!gradients) {
  57946. return this;
  57947. }
  57948. var index = 0;
  57949. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57950. var valueGradient = gradients_1[_i];
  57951. if (valueGradient.gradient === gradient) {
  57952. gradients.splice(index, 1);
  57953. break;
  57954. }
  57955. index++;
  57956. }
  57957. if (texture) {
  57958. texture.dispose();
  57959. }
  57960. return this;
  57961. };
  57962. /**
  57963. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57964. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57965. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57966. * @returns the emitter
  57967. */
  57968. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57969. var particleEmitter = new BABYLON.PointParticleEmitter();
  57970. particleEmitter.direction1 = direction1;
  57971. particleEmitter.direction2 = direction2;
  57972. this.particleEmitterType = particleEmitter;
  57973. return particleEmitter;
  57974. };
  57975. /**
  57976. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57977. * @param radius The radius of the hemisphere to emit from
  57978. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57979. * @returns the emitter
  57980. */
  57981. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57982. if (radius === void 0) { radius = 1; }
  57983. if (radiusRange === void 0) { radiusRange = 1; }
  57984. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57985. this.particleEmitterType = particleEmitter;
  57986. return particleEmitter;
  57987. };
  57988. /**
  57989. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57990. * @param radius The radius of the sphere to emit from
  57991. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57992. * @returns the emitter
  57993. */
  57994. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57995. if (radius === void 0) { radius = 1; }
  57996. if (radiusRange === void 0) { radiusRange = 1; }
  57997. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57998. this.particleEmitterType = particleEmitter;
  57999. return particleEmitter;
  58000. };
  58001. /**
  58002. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58003. * @param radius The radius of the sphere to emit from
  58004. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58005. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58006. * @returns the emitter
  58007. */
  58008. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58009. if (radius === void 0) { radius = 1; }
  58010. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58011. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58012. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58013. this.particleEmitterType = particleEmitter;
  58014. return particleEmitter;
  58015. };
  58016. /**
  58017. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58018. * @param radius The radius of the emission cylinder
  58019. * @param height The height of the emission cylinder
  58020. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58021. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58022. * @returns the emitter
  58023. */
  58024. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58025. if (radius === void 0) { radius = 1; }
  58026. if (height === void 0) { height = 1; }
  58027. if (radiusRange === void 0) { radiusRange = 1; }
  58028. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58029. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58030. this.particleEmitterType = particleEmitter;
  58031. return particleEmitter;
  58032. };
  58033. /**
  58034. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58035. * @param radius The radius of the cylinder to emit from
  58036. * @param height The height of the emission cylinder
  58037. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58038. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58039. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58040. * @returns the emitter
  58041. */
  58042. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58043. if (radius === void 0) { radius = 1; }
  58044. if (height === void 0) { height = 1; }
  58045. if (radiusRange === void 0) { radiusRange = 1; }
  58046. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58047. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58048. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58049. this.particleEmitterType = particleEmitter;
  58050. return particleEmitter;
  58051. };
  58052. /**
  58053. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58054. * @param radius The radius of the cone to emit from
  58055. * @param angle The base angle of the cone
  58056. * @returns the emitter
  58057. */
  58058. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58059. if (radius === void 0) { radius = 1; }
  58060. if (angle === void 0) { angle = Math.PI / 4; }
  58061. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58062. this.particleEmitterType = particleEmitter;
  58063. return particleEmitter;
  58064. };
  58065. /**
  58066. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58067. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58068. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58069. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58070. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58071. * @returns the emitter
  58072. */
  58073. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58074. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58075. this.particleEmitterType = particleEmitter;
  58076. this.direction1 = direction1;
  58077. this.direction2 = direction2;
  58078. this.minEmitBox = minEmitBox;
  58079. this.maxEmitBox = maxEmitBox;
  58080. return particleEmitter;
  58081. };
  58082. /**
  58083. * Source color is added to the destination color without alpha affecting the result
  58084. */
  58085. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58086. /**
  58087. * Blend current color and particle color using particle’s alpha
  58088. */
  58089. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58090. /**
  58091. * Add current color and particle color multiplied by particle’s alpha
  58092. */
  58093. BaseParticleSystem.BLENDMODE_ADD = 2;
  58094. /**
  58095. * Multiply current color with particle color
  58096. */
  58097. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58098. /**
  58099. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58100. */
  58101. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58102. return BaseParticleSystem;
  58103. }());
  58104. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58105. })(BABYLON || (BABYLON = {}));
  58106. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58107. var BABYLON;
  58108. (function (BABYLON) {
  58109. /**
  58110. * This represents a particle system in Babylon.
  58111. * 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.
  58112. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58113. * @example https://doc.babylonjs.com/babylon101/particles
  58114. */
  58115. var ParticleSystem = /** @class */ (function (_super) {
  58116. __extends(ParticleSystem, _super);
  58117. /**
  58118. * Instantiates a particle system.
  58119. * 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.
  58120. * @param name The name of the particle system
  58121. * @param capacity The max number of particles alive at the same time
  58122. * @param scene The scene the particle system belongs to
  58123. * @param customEffect a custom effect used to change the way particles are rendered by default
  58124. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58125. * @param epsilon Offset used to render the particles
  58126. */
  58127. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58128. if (customEffect === void 0) { customEffect = null; }
  58129. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58130. if (epsilon === void 0) { epsilon = 0.01; }
  58131. var _this = _super.call(this, name) || this;
  58132. /**
  58133. * @hidden
  58134. */
  58135. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58136. /**
  58137. * An event triggered when the system is disposed
  58138. */
  58139. _this.onDisposeObservable = new BABYLON.Observable();
  58140. _this._particles = new Array();
  58141. _this._stockParticles = new Array();
  58142. _this._newPartsExcess = 0;
  58143. _this._vertexBuffers = {};
  58144. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58145. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58146. _this._scaledDirection = BABYLON.Vector3.Zero();
  58147. _this._scaledGravity = BABYLON.Vector3.Zero();
  58148. _this._currentRenderId = -1;
  58149. _this._useInstancing = false;
  58150. _this._started = false;
  58151. _this._stopped = false;
  58152. _this._actualFrame = 0;
  58153. /** @hidden */
  58154. _this._currentEmitRate1 = 0;
  58155. /** @hidden */
  58156. _this._currentEmitRate2 = 0;
  58157. /** @hidden */
  58158. _this._currentStartSize1 = 0;
  58159. /** @hidden */
  58160. _this._currentStartSize2 = 0;
  58161. _this._rawTextureWidth = 256;
  58162. _this._useRampGradients = false;
  58163. /**
  58164. * @hidden
  58165. * If the particle systems emitter should be disposed when the particle system is disposed
  58166. */
  58167. _this._disposeEmitterOnDispose = false;
  58168. // start of sub system methods
  58169. /**
  58170. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58171. * Its lifetime will start back at 0.
  58172. */
  58173. _this.recycleParticle = function (particle) {
  58174. // move particle from activeParticle list to stock particles
  58175. var lastParticle = _this._particles.pop();
  58176. if (lastParticle !== particle) {
  58177. lastParticle.copyTo(particle);
  58178. }
  58179. _this._stockParticles.push(lastParticle);
  58180. };
  58181. _this._createParticle = function () {
  58182. var particle;
  58183. if (_this._stockParticles.length !== 0) {
  58184. particle = _this._stockParticles.pop();
  58185. particle._reset();
  58186. }
  58187. else {
  58188. particle = new BABYLON.Particle(_this);
  58189. }
  58190. // Attach emitters
  58191. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58192. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58193. particle._attachedSubEmitters = [];
  58194. subEmitters.forEach(function (subEmitter) {
  58195. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58196. var newEmitter = subEmitter.clone();
  58197. particle._attachedSubEmitters.push(newEmitter);
  58198. newEmitter.particleSystem.start();
  58199. }
  58200. });
  58201. }
  58202. return particle;
  58203. };
  58204. _this._emitFromParticle = function (particle) {
  58205. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58206. return;
  58207. }
  58208. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58209. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58210. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58211. var subSystem = subEmitter.clone();
  58212. particle._inheritParticleInfoToSubEmitter(subSystem);
  58213. subSystem.particleSystem._rootParticleSystem = _this;
  58214. _this.activeSubSystems.push(subSystem.particleSystem);
  58215. subSystem.particleSystem.start();
  58216. }
  58217. });
  58218. };
  58219. _this._capacity = capacity;
  58220. _this._epsilon = epsilon;
  58221. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58222. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58223. // Setup the default processing configuration to the scene.
  58224. _this._attachImageProcessingConfiguration(null);
  58225. _this._customEffect = customEffect;
  58226. _this._scene.particleSystems.push(_this);
  58227. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58228. _this._createIndexBuffer();
  58229. _this._createVertexBuffers();
  58230. // Default emitter type
  58231. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58232. // Update
  58233. _this.updateFunction = function (particles) {
  58234. var noiseTextureSize = null;
  58235. var noiseTextureData = null;
  58236. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58237. noiseTextureSize = _this.noiseTexture.getSize();
  58238. noiseTextureData = (_this.noiseTexture.getContent());
  58239. }
  58240. var _loop_1 = function () {
  58241. particle = particles[index];
  58242. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58243. var previousAge = particle.age;
  58244. particle.age += scaledUpdateSpeed;
  58245. // Evaluate step to death
  58246. if (particle.age > particle.lifeTime) {
  58247. var diff = particle.age - previousAge;
  58248. var oldDiff = particle.lifeTime - previousAge;
  58249. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58250. particle.age = particle.lifeTime;
  58251. }
  58252. var ratio = particle.age / particle.lifeTime;
  58253. // Color
  58254. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58255. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58256. if (currentGradient !== particle._currentColorGradient) {
  58257. particle._currentColor1.copyFrom(particle._currentColor2);
  58258. nextGradient.getColorToRef(particle._currentColor2);
  58259. particle._currentColorGradient = currentGradient;
  58260. }
  58261. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58262. });
  58263. }
  58264. else {
  58265. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58266. particle.color.addInPlace(_this._scaledColorStep);
  58267. if (particle.color.a < 0) {
  58268. particle.color.a = 0;
  58269. }
  58270. }
  58271. // Angular speed
  58272. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58273. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58274. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58275. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58276. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58277. particle._currentAngularSpeedGradient = currentGradient;
  58278. }
  58279. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58280. });
  58281. }
  58282. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58283. // Direction
  58284. var directionScale = scaledUpdateSpeed;
  58285. /// Velocity
  58286. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58287. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58288. if (currentGradient !== particle._currentVelocityGradient) {
  58289. particle._currentVelocity1 = particle._currentVelocity2;
  58290. particle._currentVelocity2 = nextGradient.getFactor();
  58291. particle._currentVelocityGradient = currentGradient;
  58292. }
  58293. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58294. });
  58295. }
  58296. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58297. /// Limit velocity
  58298. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58299. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58300. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58301. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58302. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58303. particle._currentLimitVelocityGradient = currentGradient;
  58304. }
  58305. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58306. var currentVelocity = particle.direction.length();
  58307. if (currentVelocity > limitVelocity) {
  58308. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58309. }
  58310. });
  58311. }
  58312. /// Drag
  58313. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58314. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58315. if (currentGradient !== particle._currentDragGradient) {
  58316. particle._currentDrag1 = particle._currentDrag2;
  58317. particle._currentDrag2 = nextGradient.getFactor();
  58318. particle._currentDragGradient = currentGradient;
  58319. }
  58320. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58321. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58322. });
  58323. }
  58324. particle.position.addInPlace(_this._scaledDirection);
  58325. // Noise
  58326. if (noiseTextureData && noiseTextureSize) {
  58327. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58328. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58329. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58330. var force = BABYLON.Tmp.Vector3[0];
  58331. var scaledForce = BABYLON.Tmp.Vector3[1];
  58332. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58333. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58334. particle.direction.addInPlace(scaledForce);
  58335. }
  58336. // Gravity
  58337. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58338. particle.direction.addInPlace(_this._scaledGravity);
  58339. // Size
  58340. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58341. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58342. if (currentGradient !== particle._currentSizeGradient) {
  58343. particle._currentSize1 = particle._currentSize2;
  58344. particle._currentSize2 = nextGradient.getFactor();
  58345. particle._currentSizeGradient = currentGradient;
  58346. }
  58347. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58348. });
  58349. }
  58350. // Remap data
  58351. if (_this._useRampGradients) {
  58352. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58353. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58354. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58355. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58356. particle.remapData.x = min;
  58357. particle.remapData.y = max - min;
  58358. });
  58359. }
  58360. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58361. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58362. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58363. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58364. particle.remapData.z = min;
  58365. particle.remapData.w = max - min;
  58366. });
  58367. }
  58368. }
  58369. if (_this._isAnimationSheetEnabled) {
  58370. particle.updateCellIndex();
  58371. }
  58372. // Update the position of the attached sub-emitters to match their attached particle
  58373. particle._inheritParticleInfoToSubEmitters();
  58374. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58375. _this._emitFromParticle(particle);
  58376. if (particle._attachedSubEmitters) {
  58377. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58378. subEmitter.particleSystem.disposeOnStop = true;
  58379. subEmitter.particleSystem.stop();
  58380. });
  58381. particle._attachedSubEmitters = null;
  58382. }
  58383. _this.recycleParticle(particle);
  58384. index--;
  58385. return "continue";
  58386. }
  58387. };
  58388. var particle;
  58389. for (var index = 0; index < particles.length; index++) {
  58390. _loop_1();
  58391. }
  58392. };
  58393. return _this;
  58394. }
  58395. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58396. /**
  58397. * Sets a callback that will be triggered when the system is disposed
  58398. */
  58399. set: function (callback) {
  58400. if (this._onDisposeObserver) {
  58401. this.onDisposeObservable.remove(this._onDisposeObserver);
  58402. }
  58403. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58404. },
  58405. enumerable: true,
  58406. configurable: true
  58407. });
  58408. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58409. /** Gets or sets a boolean indicating that ramp gradients must be used
  58410. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58411. */
  58412. get: function () {
  58413. return this._useRampGradients;
  58414. },
  58415. set: function (value) {
  58416. if (this._useRampGradients === value) {
  58417. return;
  58418. }
  58419. this._useRampGradients = value;
  58420. this._resetEffect();
  58421. },
  58422. enumerable: true,
  58423. configurable: true
  58424. });
  58425. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58426. //end of Sub-emitter
  58427. /**
  58428. * Gets the current list of active particles
  58429. */
  58430. get: function () {
  58431. return this._particles;
  58432. },
  58433. enumerable: true,
  58434. configurable: true
  58435. });
  58436. /**
  58437. * Returns the string "ParticleSystem"
  58438. * @returns a string containing the class name
  58439. */
  58440. ParticleSystem.prototype.getClassName = function () {
  58441. return "ParticleSystem";
  58442. };
  58443. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58444. var newGradient = new BABYLON.FactorGradient();
  58445. newGradient.gradient = gradient;
  58446. newGradient.factor1 = factor;
  58447. newGradient.factor2 = factor2;
  58448. factorGradients.push(newGradient);
  58449. factorGradients.sort(function (a, b) {
  58450. if (a.gradient < b.gradient) {
  58451. return -1;
  58452. }
  58453. else if (a.gradient > b.gradient) {
  58454. return 1;
  58455. }
  58456. return 0;
  58457. });
  58458. };
  58459. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58460. if (!factorGradients) {
  58461. return;
  58462. }
  58463. var index = 0;
  58464. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58465. var factorGradient = factorGradients_1[_i];
  58466. if (factorGradient.gradient === gradient) {
  58467. factorGradients.splice(index, 1);
  58468. break;
  58469. }
  58470. index++;
  58471. }
  58472. };
  58473. /**
  58474. * Adds a new life time gradient
  58475. * @param gradient defines the gradient to use (between 0 and 1)
  58476. * @param factor defines the life time factor to affect to the specified gradient
  58477. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58478. * @returns the current particle system
  58479. */
  58480. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58481. if (!this._lifeTimeGradients) {
  58482. this._lifeTimeGradients = [];
  58483. }
  58484. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58485. return this;
  58486. };
  58487. /**
  58488. * Remove a specific life time gradient
  58489. * @param gradient defines the gradient to remove
  58490. * @returns the current particle system
  58491. */
  58492. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58493. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58494. return this;
  58495. };
  58496. /**
  58497. * Adds a new size gradient
  58498. * @param gradient defines the gradient to use (between 0 and 1)
  58499. * @param factor defines the size factor to affect to the specified gradient
  58500. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58501. * @returns the current particle system
  58502. */
  58503. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58504. if (!this._sizeGradients) {
  58505. this._sizeGradients = [];
  58506. }
  58507. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58508. return this;
  58509. };
  58510. /**
  58511. * Remove a specific size gradient
  58512. * @param gradient defines the gradient to remove
  58513. * @returns the current particle system
  58514. */
  58515. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58516. this._removeFactorGradient(this._sizeGradients, gradient);
  58517. return this;
  58518. };
  58519. /**
  58520. * Adds a new color remap gradient
  58521. * @param gradient defines the gradient to use (between 0 and 1)
  58522. * @param min defines the color remap minimal range
  58523. * @param max defines the color remap maximal range
  58524. * @returns the current particle system
  58525. */
  58526. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58527. if (!this._colorRemapGradients) {
  58528. this._colorRemapGradients = [];
  58529. }
  58530. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58531. return this;
  58532. };
  58533. /**
  58534. * Remove a specific color remap gradient
  58535. * @param gradient defines the gradient to remove
  58536. * @returns the current particle system
  58537. */
  58538. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58539. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58540. return this;
  58541. };
  58542. /**
  58543. * Adds a new alpha remap gradient
  58544. * @param gradient defines the gradient to use (between 0 and 1)
  58545. * @param min defines the alpha remap minimal range
  58546. * @param max defines the alpha remap maximal range
  58547. * @returns the current particle system
  58548. */
  58549. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58550. if (!this._alphaRemapGradients) {
  58551. this._alphaRemapGradients = [];
  58552. }
  58553. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58554. return this;
  58555. };
  58556. /**
  58557. * Remove a specific alpha remap gradient
  58558. * @param gradient defines the gradient to remove
  58559. * @returns the current particle system
  58560. */
  58561. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58562. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58563. return this;
  58564. };
  58565. /**
  58566. * Adds a new angular speed gradient
  58567. * @param gradient defines the gradient to use (between 0 and 1)
  58568. * @param factor defines the angular speed to affect to the specified gradient
  58569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58570. * @returns the current particle system
  58571. */
  58572. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58573. if (!this._angularSpeedGradients) {
  58574. this._angularSpeedGradients = [];
  58575. }
  58576. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58577. return this;
  58578. };
  58579. /**
  58580. * Remove a specific angular speed gradient
  58581. * @param gradient defines the gradient to remove
  58582. * @returns the current particle system
  58583. */
  58584. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58585. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58586. return this;
  58587. };
  58588. /**
  58589. * Adds a new velocity gradient
  58590. * @param gradient defines the gradient to use (between 0 and 1)
  58591. * @param factor defines the velocity to affect to the specified gradient
  58592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58593. * @returns the current particle system
  58594. */
  58595. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58596. if (!this._velocityGradients) {
  58597. this._velocityGradients = [];
  58598. }
  58599. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58600. return this;
  58601. };
  58602. /**
  58603. * Remove a specific velocity gradient
  58604. * @param gradient defines the gradient to remove
  58605. * @returns the current particle system
  58606. */
  58607. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58608. this._removeFactorGradient(this._velocityGradients, gradient);
  58609. return this;
  58610. };
  58611. /**
  58612. * Adds a new limit velocity gradient
  58613. * @param gradient defines the gradient to use (between 0 and 1)
  58614. * @param factor defines the limit velocity value to affect to the specified gradient
  58615. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58616. * @returns the current particle system
  58617. */
  58618. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58619. if (!this._limitVelocityGradients) {
  58620. this._limitVelocityGradients = [];
  58621. }
  58622. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58623. return this;
  58624. };
  58625. /**
  58626. * Remove a specific limit velocity gradient
  58627. * @param gradient defines the gradient to remove
  58628. * @returns the current particle system
  58629. */
  58630. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58631. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58632. return this;
  58633. };
  58634. /**
  58635. * Adds a new drag gradient
  58636. * @param gradient defines the gradient to use (between 0 and 1)
  58637. * @param factor defines the drag value to affect to the specified gradient
  58638. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58639. * @returns the current particle system
  58640. */
  58641. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58642. if (!this._dragGradients) {
  58643. this._dragGradients = [];
  58644. }
  58645. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58646. return this;
  58647. };
  58648. /**
  58649. * Remove a specific drag gradient
  58650. * @param gradient defines the gradient to remove
  58651. * @returns the current particle system
  58652. */
  58653. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58654. this._removeFactorGradient(this._dragGradients, gradient);
  58655. return this;
  58656. };
  58657. /**
  58658. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58659. * @param gradient defines the gradient to use (between 0 and 1)
  58660. * @param factor defines the emit rate value to affect to the specified gradient
  58661. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58662. * @returns the current particle system
  58663. */
  58664. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58665. if (!this._emitRateGradients) {
  58666. this._emitRateGradients = [];
  58667. }
  58668. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58669. if (!this._currentEmitRateGradient) {
  58670. this._currentEmitRateGradient = this._emitRateGradients[0];
  58671. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58672. this._currentEmitRate2 = this._currentEmitRate1;
  58673. }
  58674. if (this._emitRateGradients.length === 2) {
  58675. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58676. }
  58677. return this;
  58678. };
  58679. /**
  58680. * Remove a specific emit rate gradient
  58681. * @param gradient defines the gradient to remove
  58682. * @returns the current particle system
  58683. */
  58684. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58685. this._removeFactorGradient(this._emitRateGradients, gradient);
  58686. return this;
  58687. };
  58688. /**
  58689. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58690. * @param gradient defines the gradient to use (between 0 and 1)
  58691. * @param factor defines the start size value to affect to the specified gradient
  58692. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58693. * @returns the current particle system
  58694. */
  58695. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58696. if (!this._startSizeGradients) {
  58697. this._startSizeGradients = [];
  58698. }
  58699. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58700. if (!this._currentStartSizeGradient) {
  58701. this._currentStartSizeGradient = this._startSizeGradients[0];
  58702. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58703. this._currentStartSize2 = this._currentStartSize1;
  58704. }
  58705. if (this._startSizeGradients.length === 2) {
  58706. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58707. }
  58708. return this;
  58709. };
  58710. /**
  58711. * Remove a specific start size gradient
  58712. * @param gradient defines the gradient to remove
  58713. * @returns the current particle system
  58714. */
  58715. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58716. this._removeFactorGradient(this._emitRateGradients, gradient);
  58717. return this;
  58718. };
  58719. ParticleSystem.prototype._createRampGradientTexture = function () {
  58720. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58721. return;
  58722. }
  58723. var data = new Uint8Array(this._rawTextureWidth * 4);
  58724. var tmpColor = BABYLON.Tmp.Color3[0];
  58725. for (var x = 0; x < this._rawTextureWidth; x++) {
  58726. var ratio = x / this._rawTextureWidth;
  58727. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58728. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58729. data[x * 4] = tmpColor.r * 255;
  58730. data[x * 4 + 1] = tmpColor.g * 255;
  58731. data[x * 4 + 2] = tmpColor.b * 255;
  58732. data[x * 4 + 3] = 255;
  58733. });
  58734. }
  58735. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58736. };
  58737. /**
  58738. * Gets the current list of ramp gradients.
  58739. * You must use addRampGradient and removeRampGradient to udpate this list
  58740. * @returns the list of ramp gradients
  58741. */
  58742. ParticleSystem.prototype.getRampGradients = function () {
  58743. return this._rampGradients;
  58744. };
  58745. /**
  58746. * Adds a new ramp gradient used to remap particle colors
  58747. * @param gradient defines the gradient to use (between 0 and 1)
  58748. * @param color defines the color to affect to the specified gradient
  58749. * @returns the current particle system
  58750. */
  58751. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58752. if (!this._rampGradients) {
  58753. this._rampGradients = [];
  58754. }
  58755. var rampGradient = new BABYLON.Color3Gradient();
  58756. rampGradient.gradient = gradient;
  58757. rampGradient.color = color;
  58758. this._rampGradients.push(rampGradient);
  58759. this._rampGradients.sort(function (a, b) {
  58760. if (a.gradient < b.gradient) {
  58761. return -1;
  58762. }
  58763. else if (a.gradient > b.gradient) {
  58764. return 1;
  58765. }
  58766. return 0;
  58767. });
  58768. if (this._rampGradientsTexture) {
  58769. this._rampGradientsTexture.dispose();
  58770. this._rampGradientsTexture = null;
  58771. }
  58772. this._createRampGradientTexture();
  58773. return this;
  58774. };
  58775. /**
  58776. * Remove a specific ramp gradient
  58777. * @param gradient defines the gradient to remove
  58778. * @returns the current particle system
  58779. */
  58780. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58781. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58782. this._rampGradientsTexture = null;
  58783. if (this._rampGradients && this._rampGradients.length > 0) {
  58784. this._createRampGradientTexture();
  58785. }
  58786. return this;
  58787. };
  58788. /**
  58789. * Adds a new color gradient
  58790. * @param gradient defines the gradient to use (between 0 and 1)
  58791. * @param color1 defines the color to affect to the specified gradient
  58792. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58793. */
  58794. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58795. if (!this._colorGradients) {
  58796. this._colorGradients = [];
  58797. }
  58798. var colorGradient = new BABYLON.ColorGradient();
  58799. colorGradient.gradient = gradient;
  58800. colorGradient.color1 = color1;
  58801. colorGradient.color2 = color2;
  58802. this._colorGradients.push(colorGradient);
  58803. this._colorGradients.sort(function (a, b) {
  58804. if (a.gradient < b.gradient) {
  58805. return -1;
  58806. }
  58807. else if (a.gradient > b.gradient) {
  58808. return 1;
  58809. }
  58810. return 0;
  58811. });
  58812. return this;
  58813. };
  58814. /**
  58815. * Remove a specific color gradient
  58816. * @param gradient defines the gradient to remove
  58817. */
  58818. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58819. if (!this._colorGradients) {
  58820. return this;
  58821. }
  58822. var index = 0;
  58823. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58824. var colorGradient = _a[_i];
  58825. if (colorGradient.gradient === gradient) {
  58826. this._colorGradients.splice(index, 1);
  58827. break;
  58828. }
  58829. index++;
  58830. }
  58831. return this;
  58832. };
  58833. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58834. u = Math.abs(u) * 0.5 + 0.5;
  58835. v = Math.abs(v) * 0.5 + 0.5;
  58836. var wrappedU = ((u * width) % width) | 0;
  58837. var wrappedV = ((v * height) % height) | 0;
  58838. var position = (wrappedU + wrappedV * width) * 4;
  58839. return pixels[position] / 255;
  58840. };
  58841. ParticleSystem.prototype._reset = function () {
  58842. this._resetEffect();
  58843. };
  58844. ParticleSystem.prototype._resetEffect = function () {
  58845. if (this._vertexBuffer) {
  58846. this._vertexBuffer.dispose();
  58847. this._vertexBuffer = null;
  58848. }
  58849. if (this._spriteBuffer) {
  58850. this._spriteBuffer.dispose();
  58851. this._spriteBuffer = null;
  58852. }
  58853. this._createVertexBuffers();
  58854. };
  58855. ParticleSystem.prototype._createVertexBuffers = function () {
  58856. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58857. if (this._isAnimationSheetEnabled) {
  58858. this._vertexBufferSize += 1;
  58859. }
  58860. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58861. this._vertexBufferSize += 3;
  58862. }
  58863. if (this._useRampGradients) {
  58864. this._vertexBufferSize += 4;
  58865. }
  58866. var engine = this._scene.getEngine();
  58867. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58868. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58869. var dataOffset = 0;
  58870. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58871. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58872. dataOffset += 3;
  58873. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58874. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58875. dataOffset += 4;
  58876. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58877. this._vertexBuffers["angle"] = options;
  58878. dataOffset += 1;
  58879. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58880. this._vertexBuffers["size"] = size;
  58881. dataOffset += 2;
  58882. if (this._isAnimationSheetEnabled) {
  58883. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58884. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58885. dataOffset += 1;
  58886. }
  58887. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58888. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58889. this._vertexBuffers["direction"] = directionBuffer;
  58890. dataOffset += 3;
  58891. }
  58892. if (this._useRampGradients) {
  58893. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58894. this._vertexBuffers["remapData"] = rampDataBuffer;
  58895. dataOffset += 4;
  58896. }
  58897. var offsets;
  58898. if (this._useInstancing) {
  58899. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58900. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58901. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58902. }
  58903. else {
  58904. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58905. dataOffset += 2;
  58906. }
  58907. this._vertexBuffers["offset"] = offsets;
  58908. };
  58909. ParticleSystem.prototype._createIndexBuffer = function () {
  58910. if (this._useInstancing) {
  58911. return;
  58912. }
  58913. var indices = [];
  58914. var index = 0;
  58915. for (var count = 0; count < this._capacity; count++) {
  58916. indices.push(index);
  58917. indices.push(index + 1);
  58918. indices.push(index + 2);
  58919. indices.push(index);
  58920. indices.push(index + 2);
  58921. indices.push(index + 3);
  58922. index += 4;
  58923. }
  58924. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58925. };
  58926. /**
  58927. * Gets the maximum number of particles active at the same time.
  58928. * @returns The max number of active particles.
  58929. */
  58930. ParticleSystem.prototype.getCapacity = function () {
  58931. return this._capacity;
  58932. };
  58933. /**
  58934. * Gets whether there are still active particles in the system.
  58935. * @returns True if it is alive, otherwise false.
  58936. */
  58937. ParticleSystem.prototype.isAlive = function () {
  58938. return this._alive;
  58939. };
  58940. /**
  58941. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58942. * @returns True if it has been started, otherwise false.
  58943. */
  58944. ParticleSystem.prototype.isStarted = function () {
  58945. return this._started;
  58946. };
  58947. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58948. var _this = this;
  58949. this._subEmitters = new Array();
  58950. if (this.subEmitters) {
  58951. this.subEmitters.forEach(function (subEmitter) {
  58952. if (subEmitter instanceof ParticleSystem) {
  58953. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58954. }
  58955. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58956. _this._subEmitters.push([subEmitter]);
  58957. }
  58958. else if (subEmitter instanceof Array) {
  58959. _this._subEmitters.push(subEmitter);
  58960. }
  58961. });
  58962. }
  58963. };
  58964. /**
  58965. * Starts the particle system and begins to emit
  58966. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58967. */
  58968. ParticleSystem.prototype.start = function (delay) {
  58969. var _this = this;
  58970. if (delay === void 0) { delay = this.startDelay; }
  58971. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58972. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58973. }
  58974. if (delay) {
  58975. setTimeout(function () {
  58976. _this.start(0);
  58977. }, delay);
  58978. return;
  58979. }
  58980. // Convert the subEmitters field to the constant type field _subEmitters
  58981. this._prepareSubEmitterInternalArray();
  58982. this._started = true;
  58983. this._stopped = false;
  58984. this._actualFrame = 0;
  58985. if (this._subEmitters && this._subEmitters.length != 0) {
  58986. this.activeSubSystems = new Array();
  58987. }
  58988. if (this.preWarmCycles) {
  58989. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58990. this.emitter.computeWorldMatrix(true);
  58991. }
  58992. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58993. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58994. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58995. setTimeout(function () {
  58996. for (var index = 0; index < _this.preWarmCycles; index++) {
  58997. _this.animate(true);
  58998. noiseTextureAsProcedural_1.render();
  58999. }
  59000. });
  59001. });
  59002. }
  59003. else {
  59004. for (var index = 0; index < this.preWarmCycles; index++) {
  59005. this.animate(true);
  59006. }
  59007. }
  59008. }
  59009. // Animations
  59010. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59011. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59012. }
  59013. };
  59014. /**
  59015. * Stops the particle system.
  59016. * @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.
  59017. */
  59018. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59019. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59020. this._stopped = true;
  59021. if (stopSubEmitters) {
  59022. this._stopSubEmitters();
  59023. }
  59024. };
  59025. // animation sheet
  59026. /**
  59027. * Remove all active particles
  59028. */
  59029. ParticleSystem.prototype.reset = function () {
  59030. this._stockParticles = [];
  59031. this._particles = [];
  59032. };
  59033. /**
  59034. * @hidden (for internal use only)
  59035. */
  59036. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59037. var offset = index * this._vertexBufferSize;
  59038. this._vertexData[offset++] = particle.position.x;
  59039. this._vertexData[offset++] = particle.position.y;
  59040. this._vertexData[offset++] = particle.position.z;
  59041. this._vertexData[offset++] = particle.color.r;
  59042. this._vertexData[offset++] = particle.color.g;
  59043. this._vertexData[offset++] = particle.color.b;
  59044. this._vertexData[offset++] = particle.color.a;
  59045. this._vertexData[offset++] = particle.angle;
  59046. this._vertexData[offset++] = particle.scale.x * particle.size;
  59047. this._vertexData[offset++] = particle.scale.y * particle.size;
  59048. if (this._isAnimationSheetEnabled) {
  59049. this._vertexData[offset++] = particle.cellIndex;
  59050. }
  59051. if (!this._isBillboardBased) {
  59052. if (particle._initialDirection) {
  59053. this._vertexData[offset++] = particle._initialDirection.x;
  59054. this._vertexData[offset++] = particle._initialDirection.y;
  59055. this._vertexData[offset++] = particle._initialDirection.z;
  59056. }
  59057. else {
  59058. this._vertexData[offset++] = particle.direction.x;
  59059. this._vertexData[offset++] = particle.direction.y;
  59060. this._vertexData[offset++] = particle.direction.z;
  59061. }
  59062. }
  59063. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59064. this._vertexData[offset++] = particle.direction.x;
  59065. this._vertexData[offset++] = particle.direction.y;
  59066. this._vertexData[offset++] = particle.direction.z;
  59067. }
  59068. if (this._useRampGradients) {
  59069. this._vertexData[offset++] = particle.remapData.x;
  59070. this._vertexData[offset++] = particle.remapData.y;
  59071. this._vertexData[offset++] = particle.remapData.z;
  59072. this._vertexData[offset++] = particle.remapData.w;
  59073. }
  59074. if (!this._useInstancing) {
  59075. if (this._isAnimationSheetEnabled) {
  59076. if (offsetX === 0)
  59077. offsetX = this._epsilon;
  59078. else if (offsetX === 1)
  59079. offsetX = 1 - this._epsilon;
  59080. if (offsetY === 0)
  59081. offsetY = this._epsilon;
  59082. else if (offsetY === 1)
  59083. offsetY = 1 - this._epsilon;
  59084. }
  59085. this._vertexData[offset++] = offsetX;
  59086. this._vertexData[offset++] = offsetY;
  59087. }
  59088. };
  59089. ParticleSystem.prototype._stopSubEmitters = function () {
  59090. if (!this.activeSubSystems) {
  59091. return;
  59092. }
  59093. this.activeSubSystems.forEach(function (subSystem) {
  59094. subSystem.stop(true);
  59095. });
  59096. this.activeSubSystems = new Array();
  59097. };
  59098. ParticleSystem.prototype._removeFromRoot = function () {
  59099. if (!this._rootParticleSystem) {
  59100. return;
  59101. }
  59102. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59103. if (index !== -1) {
  59104. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59105. }
  59106. this._rootParticleSystem = null;
  59107. };
  59108. // End of sub system methods
  59109. ParticleSystem.prototype._update = function (newParticles) {
  59110. var _this = this;
  59111. // Update current
  59112. this._alive = this._particles.length > 0;
  59113. if (this.emitter.position) {
  59114. var emitterMesh = this.emitter;
  59115. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59116. }
  59117. else {
  59118. var emitterPosition = this.emitter;
  59119. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59120. }
  59121. this.updateFunction(this._particles);
  59122. // Add new ones
  59123. var particle;
  59124. var _loop_2 = function () {
  59125. if (this_1._particles.length === this_1._capacity) {
  59126. return "break";
  59127. }
  59128. particle = this_1._createParticle();
  59129. this_1._particles.push(particle);
  59130. // Emitter
  59131. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59132. if (this_1.startPositionFunction) {
  59133. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59134. }
  59135. else {
  59136. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59137. }
  59138. if (this_1.startDirectionFunction) {
  59139. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59140. }
  59141. else {
  59142. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59143. }
  59144. if (emitPower === 0) {
  59145. if (!particle._initialDirection) {
  59146. particle._initialDirection = particle.direction.clone();
  59147. }
  59148. else {
  59149. particle._initialDirection.copyFrom(particle.direction);
  59150. }
  59151. }
  59152. else {
  59153. particle._initialDirection = null;
  59154. }
  59155. particle.direction.scaleInPlace(emitPower);
  59156. // Life time
  59157. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59158. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59159. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59160. var factorGradient1 = currentGradient;
  59161. var factorGradient2 = nextGradient;
  59162. var lifeTime1 = factorGradient1.getFactor();
  59163. var lifeTime2 = factorGradient2.getFactor();
  59164. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59165. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59166. });
  59167. }
  59168. else {
  59169. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59170. }
  59171. // Size
  59172. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59173. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59174. }
  59175. else {
  59176. particle._currentSizeGradient = this_1._sizeGradients[0];
  59177. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59178. particle.size = particle._currentSize1;
  59179. if (this_1._sizeGradients.length > 1) {
  59180. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59181. }
  59182. else {
  59183. particle._currentSize2 = particle._currentSize1;
  59184. }
  59185. }
  59186. // Size and scale
  59187. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59188. // Adjust scale by start size
  59189. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59190. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59191. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59192. if (currentGradient !== _this._currentStartSizeGradient) {
  59193. _this._currentStartSize1 = _this._currentStartSize2;
  59194. _this._currentStartSize2 = nextGradient.getFactor();
  59195. _this._currentStartSizeGradient = currentGradient;
  59196. }
  59197. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59198. particle.scale.scaleInPlace(value);
  59199. });
  59200. }
  59201. // Angle
  59202. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59203. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59204. }
  59205. else {
  59206. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59207. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59208. particle._currentAngularSpeed1 = particle.angularSpeed;
  59209. if (this_1._angularSpeedGradients.length > 1) {
  59210. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59211. }
  59212. else {
  59213. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59214. }
  59215. }
  59216. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59217. // Velocity
  59218. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59219. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59220. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59221. if (this_1._velocityGradients.length > 1) {
  59222. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59223. }
  59224. else {
  59225. particle._currentVelocity2 = particle._currentVelocity1;
  59226. }
  59227. }
  59228. // Limit velocity
  59229. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59230. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59231. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59232. if (this_1._limitVelocityGradients.length > 1) {
  59233. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59234. }
  59235. else {
  59236. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59237. }
  59238. }
  59239. // Drag
  59240. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59241. particle._currentDragGradient = this_1._dragGradients[0];
  59242. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59243. if (this_1._dragGradients.length > 1) {
  59244. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59245. }
  59246. else {
  59247. particle._currentDrag2 = particle._currentDrag1;
  59248. }
  59249. }
  59250. // Color
  59251. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59252. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59253. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59254. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59255. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59256. }
  59257. else {
  59258. particle._currentColorGradient = this_1._colorGradients[0];
  59259. particle._currentColorGradient.getColorToRef(particle.color);
  59260. particle._currentColor1.copyFrom(particle.color);
  59261. if (this_1._colorGradients.length > 1) {
  59262. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59263. }
  59264. else {
  59265. particle._currentColor2.copyFrom(particle.color);
  59266. }
  59267. }
  59268. // Sheet
  59269. if (this_1._isAnimationSheetEnabled) {
  59270. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59271. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59272. }
  59273. // Inherited Velocity
  59274. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59275. // Ramp
  59276. if (this_1._useRampGradients) {
  59277. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59278. }
  59279. // Noise texture coordinates
  59280. if (this_1.noiseTexture) {
  59281. if (particle._randomNoiseCoordinates1) {
  59282. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59283. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59284. }
  59285. else {
  59286. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59287. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59288. }
  59289. }
  59290. // Update the position of the attached sub-emitters to match their attached particle
  59291. particle._inheritParticleInfoToSubEmitters();
  59292. };
  59293. var this_1 = this, step;
  59294. for (var index = 0; index < newParticles; index++) {
  59295. var state_1 = _loop_2();
  59296. if (state_1 === "break")
  59297. break;
  59298. }
  59299. };
  59300. /** @hidden */
  59301. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59302. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59303. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59304. if (useRampGradients === void 0) { useRampGradients = false; }
  59305. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59306. if (isAnimationSheetEnabled) {
  59307. attributeNamesOrOptions.push("cellIndex");
  59308. }
  59309. if (!isBillboardBased) {
  59310. attributeNamesOrOptions.push("direction");
  59311. }
  59312. if (useRampGradients) {
  59313. attributeNamesOrOptions.push("remapData");
  59314. }
  59315. return attributeNamesOrOptions;
  59316. };
  59317. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59318. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59319. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59320. if (isAnimationSheetEnabled) {
  59321. effectCreationOption.push("particlesInfos");
  59322. }
  59323. return effectCreationOption;
  59324. };
  59325. ParticleSystem.prototype._getEffect = function (blendMode) {
  59326. if (this._customEffect) {
  59327. return this._customEffect;
  59328. }
  59329. ;
  59330. var defines = [];
  59331. if (this._scene.clipPlane) {
  59332. defines.push("#define CLIPPLANE");
  59333. }
  59334. if (this._scene.clipPlane2) {
  59335. defines.push("#define CLIPPLANE2");
  59336. }
  59337. if (this._scene.clipPlane3) {
  59338. defines.push("#define CLIPPLANE3");
  59339. }
  59340. if (this._scene.clipPlane4) {
  59341. defines.push("#define CLIPPLANE4");
  59342. }
  59343. if (this._isAnimationSheetEnabled) {
  59344. defines.push("#define ANIMATESHEET");
  59345. }
  59346. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59347. defines.push("#define BLENDMULTIPLYMODE");
  59348. }
  59349. if (this._useRampGradients) {
  59350. defines.push("#define RAMPGRADIENT");
  59351. }
  59352. if (this._isBillboardBased) {
  59353. defines.push("#define BILLBOARD");
  59354. switch (this.billboardMode) {
  59355. case ParticleSystem.BILLBOARDMODE_Y:
  59356. defines.push("#define BILLBOARDY");
  59357. break;
  59358. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59359. defines.push("#define BILLBOARDSTRETCHED");
  59360. break;
  59361. case ParticleSystem.BILLBOARDMODE_ALL:
  59362. default:
  59363. break;
  59364. }
  59365. }
  59366. if (this._imageProcessingConfiguration) {
  59367. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59368. defines.push(this._imageProcessingConfigurationDefines.toString());
  59369. }
  59370. // Effect
  59371. var join = defines.join("\n");
  59372. if (this._cachedDefines !== join) {
  59373. this._cachedDefines = join;
  59374. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59375. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59376. var samplers = ["diffuseSampler", "rampSampler"];
  59377. if (BABYLON.ImageProcessingConfiguration) {
  59378. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59379. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59380. }
  59381. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59382. }
  59383. return this._effect;
  59384. };
  59385. /**
  59386. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59387. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59388. */
  59389. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59390. var _this = this;
  59391. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59392. if (!this._started)
  59393. return;
  59394. if (!preWarmOnly) {
  59395. // Check
  59396. if (!this.isReady())
  59397. return;
  59398. if (this._currentRenderId === this._scene.getRenderId()) {
  59399. return;
  59400. }
  59401. this._currentRenderId = this._scene.getRenderId();
  59402. }
  59403. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59404. // Determine the number of particles we need to create
  59405. var newParticles;
  59406. if (this.manualEmitCount > -1) {
  59407. newParticles = this.manualEmitCount;
  59408. this._newPartsExcess = 0;
  59409. this.manualEmitCount = 0;
  59410. }
  59411. else {
  59412. var rate_1 = this.emitRate;
  59413. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59414. var ratio = this._actualFrame / this.targetStopDuration;
  59415. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59416. if (currentGradient !== _this._currentEmitRateGradient) {
  59417. _this._currentEmitRate1 = _this._currentEmitRate2;
  59418. _this._currentEmitRate2 = nextGradient.getFactor();
  59419. _this._currentEmitRateGradient = currentGradient;
  59420. }
  59421. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59422. });
  59423. }
  59424. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59425. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59426. }
  59427. if (this._newPartsExcess > 1.0) {
  59428. newParticles += this._newPartsExcess >> 0;
  59429. this._newPartsExcess -= this._newPartsExcess >> 0;
  59430. }
  59431. this._alive = false;
  59432. if (!this._stopped) {
  59433. this._actualFrame += this._scaledUpdateSpeed;
  59434. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59435. this.stop();
  59436. }
  59437. else {
  59438. newParticles = 0;
  59439. }
  59440. this._update(newParticles);
  59441. // Stopped?
  59442. if (this._stopped) {
  59443. if (!this._alive) {
  59444. this._started = false;
  59445. if (this.onAnimationEnd) {
  59446. this.onAnimationEnd();
  59447. }
  59448. if (this.disposeOnStop) {
  59449. this._scene._toBeDisposed.push(this);
  59450. }
  59451. }
  59452. }
  59453. if (!preWarmOnly) {
  59454. // Update VBO
  59455. var offset = 0;
  59456. for (var index = 0; index < this._particles.length; index++) {
  59457. var particle = this._particles[index];
  59458. this._appendParticleVertices(offset, particle);
  59459. offset += this._useInstancing ? 1 : 4;
  59460. }
  59461. if (this._vertexBuffer) {
  59462. this._vertexBuffer.update(this._vertexData);
  59463. }
  59464. }
  59465. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59466. this.stop();
  59467. }
  59468. };
  59469. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59470. this._appendParticleVertex(offset++, particle, 0, 0);
  59471. if (!this._useInstancing) {
  59472. this._appendParticleVertex(offset++, particle, 1, 0);
  59473. this._appendParticleVertex(offset++, particle, 1, 1);
  59474. this._appendParticleVertex(offset++, particle, 0, 1);
  59475. }
  59476. };
  59477. /**
  59478. * Rebuilds the particle system.
  59479. */
  59480. ParticleSystem.prototype.rebuild = function () {
  59481. this._createIndexBuffer();
  59482. if (this._vertexBuffer) {
  59483. this._vertexBuffer._rebuild();
  59484. }
  59485. };
  59486. /**
  59487. * Is this system ready to be used/rendered
  59488. * @return true if the system is ready
  59489. */
  59490. ParticleSystem.prototype.isReady = function () {
  59491. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59492. return false;
  59493. }
  59494. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59495. if (!this._getEffect(this.blendMode).isReady()) {
  59496. return false;
  59497. }
  59498. }
  59499. else {
  59500. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59501. return false;
  59502. }
  59503. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59504. return false;
  59505. }
  59506. }
  59507. return true;
  59508. };
  59509. ParticleSystem.prototype._render = function (blendMode) {
  59510. var effect = this._getEffect(blendMode);
  59511. var engine = this._scene.getEngine();
  59512. // Render
  59513. engine.enableEffect(effect);
  59514. var viewMatrix = this._scene.getViewMatrix();
  59515. effect.setTexture("diffuseSampler", this.particleTexture);
  59516. effect.setMatrix("view", viewMatrix);
  59517. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59518. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59519. var baseSize = this.particleTexture.getBaseSize();
  59520. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59521. }
  59522. effect.setVector2("translationPivot", this.translationPivot);
  59523. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59524. if (this._isBillboardBased) {
  59525. var camera = this._scene.activeCamera;
  59526. effect.setVector3("eyePosition", camera.globalPosition);
  59527. }
  59528. if (this._rampGradientsTexture) {
  59529. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59530. }
  59531. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59532. var invView = viewMatrix.clone();
  59533. invView.invert();
  59534. effect.setMatrix("invView", invView);
  59535. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59536. }
  59537. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59538. // image processing
  59539. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59540. this._imageProcessingConfiguration.bind(effect);
  59541. }
  59542. // Draw order
  59543. switch (blendMode) {
  59544. case ParticleSystem.BLENDMODE_ADD:
  59545. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59546. break;
  59547. case ParticleSystem.BLENDMODE_ONEONE:
  59548. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59549. break;
  59550. case ParticleSystem.BLENDMODE_STANDARD:
  59551. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59552. break;
  59553. case ParticleSystem.BLENDMODE_MULTIPLY:
  59554. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59555. break;
  59556. }
  59557. if (this._useInstancing) {
  59558. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59559. }
  59560. else {
  59561. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59562. }
  59563. return this._particles.length;
  59564. };
  59565. /**
  59566. * Renders the particle system in its current state.
  59567. * @returns the current number of particles
  59568. */
  59569. ParticleSystem.prototype.render = function () {
  59570. // Check
  59571. if (!this.isReady() || !this._particles.length) {
  59572. return 0;
  59573. }
  59574. var engine = this._scene.getEngine();
  59575. engine.setState(false);
  59576. if (this.forceDepthWrite) {
  59577. engine.setDepthWrite(true);
  59578. }
  59579. var outparticles = 0;
  59580. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59581. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59582. }
  59583. outparticles = this._render(this.blendMode);
  59584. engine.unbindInstanceAttributes();
  59585. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59586. return outparticles;
  59587. };
  59588. /**
  59589. * Disposes the particle system and free the associated resources
  59590. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59591. */
  59592. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59593. if (disposeTexture === void 0) { disposeTexture = true; }
  59594. if (this._vertexBuffer) {
  59595. this._vertexBuffer.dispose();
  59596. this._vertexBuffer = null;
  59597. }
  59598. if (this._spriteBuffer) {
  59599. this._spriteBuffer.dispose();
  59600. this._spriteBuffer = null;
  59601. }
  59602. if (this._indexBuffer) {
  59603. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59604. this._indexBuffer = null;
  59605. }
  59606. if (disposeTexture && this.particleTexture) {
  59607. this.particleTexture.dispose();
  59608. this.particleTexture = null;
  59609. }
  59610. if (disposeTexture && this.noiseTexture) {
  59611. this.noiseTexture.dispose();
  59612. this.noiseTexture = null;
  59613. }
  59614. if (this._rampGradientsTexture) {
  59615. this._rampGradientsTexture.dispose();
  59616. this._rampGradientsTexture = null;
  59617. }
  59618. this._removeFromRoot();
  59619. if (this._subEmitters && this._subEmitters.length) {
  59620. for (var index = 0; index < this._subEmitters.length; index++) {
  59621. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59622. var subEmitter = _a[_i];
  59623. subEmitter.dispose();
  59624. }
  59625. }
  59626. this._subEmitters = [];
  59627. this.subEmitters = [];
  59628. }
  59629. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59630. this.emitter.dispose(true);
  59631. }
  59632. // Remove from scene
  59633. var index = this._scene.particleSystems.indexOf(this);
  59634. if (index > -1) {
  59635. this._scene.particleSystems.splice(index, 1);
  59636. }
  59637. this._scene._activeParticleSystems.dispose();
  59638. // Callback
  59639. this.onDisposeObservable.notifyObservers(this);
  59640. this.onDisposeObservable.clear();
  59641. this.reset();
  59642. };
  59643. // Clone
  59644. /**
  59645. * Clones the particle system.
  59646. * @param name The name of the cloned object
  59647. * @param newEmitter The new emitter to use
  59648. * @returns the cloned particle system
  59649. */
  59650. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59651. var custom = null;
  59652. var program = null;
  59653. if (this.customShader != null) {
  59654. program = this.customShader;
  59655. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59656. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59657. }
  59658. else if (this._customEffect) {
  59659. custom = this._customEffect;
  59660. }
  59661. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59662. result.customShader = program;
  59663. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59664. if (newEmitter === undefined) {
  59665. newEmitter = this.emitter;
  59666. }
  59667. result.noiseTexture = this.noiseTexture;
  59668. result.emitter = newEmitter;
  59669. if (this.particleTexture) {
  59670. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59671. }
  59672. // Clone gradients
  59673. if (this._colorGradients) {
  59674. this._colorGradients.forEach(function (v) {
  59675. result.addColorGradient(v.gradient, v.color1, v.color2);
  59676. });
  59677. }
  59678. if (this._dragGradients) {
  59679. this._dragGradients.forEach(function (v) {
  59680. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59681. });
  59682. }
  59683. if (this._angularSpeedGradients) {
  59684. this._angularSpeedGradients.forEach(function (v) {
  59685. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59686. });
  59687. }
  59688. if (this._emitRateGradients) {
  59689. this._emitRateGradients.forEach(function (v) {
  59690. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59691. });
  59692. }
  59693. if (this._lifeTimeGradients) {
  59694. this._lifeTimeGradients.forEach(function (v) {
  59695. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59696. });
  59697. }
  59698. if (this._limitVelocityGradients) {
  59699. this._limitVelocityGradients.forEach(function (v) {
  59700. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59701. });
  59702. }
  59703. if (this._sizeGradients) {
  59704. this._sizeGradients.forEach(function (v) {
  59705. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59706. });
  59707. }
  59708. if (this._startSizeGradients) {
  59709. this._startSizeGradients.forEach(function (v) {
  59710. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59711. });
  59712. }
  59713. if (this._velocityGradients) {
  59714. this._velocityGradients.forEach(function (v) {
  59715. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59716. });
  59717. }
  59718. if (this._rampGradients) {
  59719. this._rampGradients.forEach(function (v) {
  59720. result.addRampGradient(v.gradient, v.color);
  59721. });
  59722. }
  59723. if (this._colorRemapGradients) {
  59724. this._colorRemapGradients.forEach(function (v) {
  59725. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59726. });
  59727. }
  59728. if (this._alphaRemapGradients) {
  59729. this._alphaRemapGradients.forEach(function (v) {
  59730. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59731. });
  59732. }
  59733. if (!this.preventAutoStart) {
  59734. result.start();
  59735. }
  59736. return result;
  59737. };
  59738. /**
  59739. * Serializes the particle system to a JSON object.
  59740. * @returns the JSON object
  59741. */
  59742. ParticleSystem.prototype.serialize = function () {
  59743. var serializationObject = {};
  59744. ParticleSystem._Serialize(serializationObject, this);
  59745. serializationObject.textureMask = this.textureMask.asArray();
  59746. serializationObject.customShader = this.customShader;
  59747. serializationObject.preventAutoStart = this.preventAutoStart;
  59748. // SubEmitters
  59749. if (this.subEmitters) {
  59750. serializationObject.subEmitters = [];
  59751. if (!this._subEmitters) {
  59752. this._prepareSubEmitterInternalArray();
  59753. }
  59754. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59755. var subs = _a[_i];
  59756. var cell = [];
  59757. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59758. var sub = subs_1[_b];
  59759. cell.push(sub.serialize());
  59760. }
  59761. serializationObject.subEmitters.push(cell);
  59762. }
  59763. }
  59764. return serializationObject;
  59765. };
  59766. /** @hidden */
  59767. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59768. serializationObject.name = particleSystem.name;
  59769. serializationObject.id = particleSystem.id;
  59770. serializationObject.capacity = particleSystem.getCapacity();
  59771. // Emitter
  59772. if (particleSystem.emitter.position) {
  59773. var emitterMesh = particleSystem.emitter;
  59774. serializationObject.emitterId = emitterMesh.id;
  59775. }
  59776. else {
  59777. var emitterPosition = particleSystem.emitter;
  59778. serializationObject.emitter = emitterPosition.asArray();
  59779. }
  59780. // Emitter
  59781. if (particleSystem.particleEmitterType) {
  59782. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59783. }
  59784. if (particleSystem.particleTexture) {
  59785. serializationObject.textureName = particleSystem.particleTexture.name;
  59786. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59787. }
  59788. // Animations
  59789. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59790. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59791. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59792. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59793. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59794. // Particle system
  59795. serializationObject.startDelay = particleSystem.startDelay;
  59796. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59797. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59798. serializationObject.billboardMode = particleSystem.billboardMode;
  59799. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59800. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59801. serializationObject.minSize = particleSystem.minSize;
  59802. serializationObject.maxSize = particleSystem.maxSize;
  59803. serializationObject.minScaleX = particleSystem.minScaleX;
  59804. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59805. serializationObject.minScaleY = particleSystem.minScaleY;
  59806. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59807. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59808. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59809. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59810. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59811. serializationObject.emitRate = particleSystem.emitRate;
  59812. serializationObject.gravity = particleSystem.gravity.asArray();
  59813. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59814. serializationObject.color1 = particleSystem.color1.asArray();
  59815. serializationObject.color2 = particleSystem.color2.asArray();
  59816. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59817. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59818. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59819. serializationObject.blendMode = particleSystem.blendMode;
  59820. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59821. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59822. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59823. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59824. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59825. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59826. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59827. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59828. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59829. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59830. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59831. var colorGradients = particleSystem.getColorGradients();
  59832. if (colorGradients) {
  59833. serializationObject.colorGradients = [];
  59834. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59835. var colorGradient = colorGradients_1[_i];
  59836. var serializedGradient = {
  59837. gradient: colorGradient.gradient,
  59838. color1: colorGradient.color1.asArray()
  59839. };
  59840. if (colorGradient.color2) {
  59841. serializedGradient.color2 = colorGradient.color2.asArray();
  59842. }
  59843. serializationObject.colorGradients.push(serializedGradient);
  59844. }
  59845. }
  59846. var rampGradients = particleSystem.getRampGradients();
  59847. if (rampGradients) {
  59848. serializationObject.rampGradients = [];
  59849. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59850. var rampGradient = rampGradients_1[_a];
  59851. var serializedGradient = {
  59852. gradient: rampGradient.gradient,
  59853. color: rampGradient.color.asArray()
  59854. };
  59855. serializationObject.rampGradients.push(serializedGradient);
  59856. }
  59857. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59858. }
  59859. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59860. if (colorRemapGradients) {
  59861. serializationObject.colorRemapGradients = [];
  59862. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59863. var colorRemapGradient = colorRemapGradients_1[_b];
  59864. var serializedGradient = {
  59865. gradient: colorRemapGradient.gradient,
  59866. factor1: colorRemapGradient.factor1
  59867. };
  59868. if (colorRemapGradient.factor2 !== undefined) {
  59869. serializedGradient.factor2 = colorRemapGradient.factor2;
  59870. }
  59871. serializationObject.colorRemapGradients.push(serializedGradient);
  59872. }
  59873. }
  59874. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59875. if (alphaRemapGradients) {
  59876. serializationObject.alphaRemapGradients = [];
  59877. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59878. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59879. var serializedGradient = {
  59880. gradient: alphaRemapGradient.gradient,
  59881. factor1: alphaRemapGradient.factor1
  59882. };
  59883. if (alphaRemapGradient.factor2 !== undefined) {
  59884. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59885. }
  59886. serializationObject.alphaRemapGradients.push(serializedGradient);
  59887. }
  59888. }
  59889. var sizeGradients = particleSystem.getSizeGradients();
  59890. if (sizeGradients) {
  59891. serializationObject.sizeGradients = [];
  59892. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59893. var sizeGradient = sizeGradients_1[_d];
  59894. var serializedGradient = {
  59895. gradient: sizeGradient.gradient,
  59896. factor1: sizeGradient.factor1
  59897. };
  59898. if (sizeGradient.factor2 !== undefined) {
  59899. serializedGradient.factor2 = sizeGradient.factor2;
  59900. }
  59901. serializationObject.sizeGradients.push(serializedGradient);
  59902. }
  59903. }
  59904. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59905. if (angularSpeedGradients) {
  59906. serializationObject.angularSpeedGradients = [];
  59907. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59908. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59909. var serializedGradient = {
  59910. gradient: angularSpeedGradient.gradient,
  59911. factor1: angularSpeedGradient.factor1
  59912. };
  59913. if (angularSpeedGradient.factor2 !== undefined) {
  59914. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59915. }
  59916. serializationObject.angularSpeedGradients.push(serializedGradient);
  59917. }
  59918. }
  59919. var velocityGradients = particleSystem.getVelocityGradients();
  59920. if (velocityGradients) {
  59921. serializationObject.velocityGradients = [];
  59922. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59923. var velocityGradient = velocityGradients_1[_f];
  59924. var serializedGradient = {
  59925. gradient: velocityGradient.gradient,
  59926. factor1: velocityGradient.factor1
  59927. };
  59928. if (velocityGradient.factor2 !== undefined) {
  59929. serializedGradient.factor2 = velocityGradient.factor2;
  59930. }
  59931. serializationObject.velocityGradients.push(serializedGradient);
  59932. }
  59933. }
  59934. var dragGradients = particleSystem.getDragGradients();
  59935. if (dragGradients) {
  59936. serializationObject.dragyGradients = [];
  59937. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59938. var dragGradient = dragGradients_1[_g];
  59939. var serializedGradient = {
  59940. gradient: dragGradient.gradient,
  59941. factor1: dragGradient.factor1
  59942. };
  59943. if (dragGradient.factor2 !== undefined) {
  59944. serializedGradient.factor2 = dragGradient.factor2;
  59945. }
  59946. serializationObject.dragGradients.push(serializedGradient);
  59947. }
  59948. }
  59949. var emitRateGradients = particleSystem.getEmitRateGradients();
  59950. if (emitRateGradients) {
  59951. serializationObject.emitRateGradients = [];
  59952. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59953. var emitRateGradient = emitRateGradients_1[_h];
  59954. var serializedGradient = {
  59955. gradient: emitRateGradient.gradient,
  59956. factor1: emitRateGradient.factor1
  59957. };
  59958. if (emitRateGradient.factor2 !== undefined) {
  59959. serializedGradient.factor2 = emitRateGradient.factor2;
  59960. }
  59961. serializationObject.emitRateGradients.push(serializedGradient);
  59962. }
  59963. }
  59964. var startSizeGradients = particleSystem.getStartSizeGradients();
  59965. if (startSizeGradients) {
  59966. serializationObject.startSizeGradients = [];
  59967. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59968. var startSizeGradient = startSizeGradients_1[_j];
  59969. var serializedGradient = {
  59970. gradient: startSizeGradient.gradient,
  59971. factor1: startSizeGradient.factor1
  59972. };
  59973. if (startSizeGradient.factor2 !== undefined) {
  59974. serializedGradient.factor2 = startSizeGradient.factor2;
  59975. }
  59976. serializationObject.startSizeGradients.push(serializedGradient);
  59977. }
  59978. }
  59979. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59980. if (lifeTimeGradients) {
  59981. serializationObject.lifeTimeGradients = [];
  59982. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59983. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59984. var serializedGradient = {
  59985. gradient: lifeTimeGradient.gradient,
  59986. factor1: lifeTimeGradient.factor1
  59987. };
  59988. if (lifeTimeGradient.factor2 !== undefined) {
  59989. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59990. }
  59991. serializationObject.lifeTimeGradients.push(serializedGradient);
  59992. }
  59993. }
  59994. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59995. if (limitVelocityGradients) {
  59996. serializationObject.limitVelocityGradients = [];
  59997. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59998. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59999. var serializedGradient = {
  60000. gradient: limitVelocityGradient.gradient,
  60001. factor1: limitVelocityGradient.factor1
  60002. };
  60003. if (limitVelocityGradient.factor2 !== undefined) {
  60004. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60005. }
  60006. serializationObject.limitVelocityGradients.push(serializedGradient);
  60007. }
  60008. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60009. }
  60010. if (particleSystem.noiseTexture) {
  60011. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60012. }
  60013. };
  60014. /** @hidden */
  60015. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60016. // Texture
  60017. if (parsedParticleSystem.textureName) {
  60018. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60019. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60020. }
  60021. // Emitter
  60022. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60023. particleSystem.emitter = BABYLON.Vector3.Zero();
  60024. }
  60025. else if (parsedParticleSystem.emitterId) {
  60026. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60027. }
  60028. else {
  60029. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60030. }
  60031. // Misc.
  60032. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60033. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60034. }
  60035. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60036. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60037. }
  60038. if (parsedParticleSystem.billboardMode !== undefined) {
  60039. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60040. }
  60041. // Animations
  60042. if (parsedParticleSystem.animations) {
  60043. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60044. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60045. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60046. }
  60047. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60048. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60049. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60050. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60051. }
  60052. if (parsedParticleSystem.autoAnimate) {
  60053. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60054. }
  60055. // Particle system
  60056. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60057. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60058. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60059. particleSystem.minSize = parsedParticleSystem.minSize;
  60060. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60061. if (parsedParticleSystem.minScaleX) {
  60062. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60063. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60064. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60065. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60066. }
  60067. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60068. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60069. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60070. }
  60071. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60072. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60073. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60074. }
  60075. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60076. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60077. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60078. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60079. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60080. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60081. if (parsedParticleSystem.noiseStrength) {
  60082. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60083. }
  60084. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60085. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60086. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60087. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60088. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60089. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60090. if (parsedParticleSystem.colorGradients) {
  60091. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60092. var colorGradient = _a[_i];
  60093. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60094. }
  60095. }
  60096. if (parsedParticleSystem.rampGradients) {
  60097. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60098. var rampGradient = _c[_b];
  60099. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60100. }
  60101. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60102. }
  60103. if (parsedParticleSystem.colorRemapGradients) {
  60104. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60105. var colorRemapGradient = _e[_d];
  60106. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60107. }
  60108. }
  60109. if (parsedParticleSystem.alphaRemapGradients) {
  60110. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60111. var alphaRemapGradient = _g[_f];
  60112. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60113. }
  60114. }
  60115. if (parsedParticleSystem.sizeGradients) {
  60116. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60117. var sizeGradient = _j[_h];
  60118. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60119. }
  60120. }
  60121. if (parsedParticleSystem.sizeGradients) {
  60122. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60123. var sizeGradient = _l[_k];
  60124. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60125. }
  60126. }
  60127. if (parsedParticleSystem.angularSpeedGradients) {
  60128. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60129. var angularSpeedGradient = _o[_m];
  60130. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60131. }
  60132. }
  60133. if (parsedParticleSystem.velocityGradients) {
  60134. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60135. var velocityGradient = _q[_p];
  60136. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60137. }
  60138. }
  60139. if (parsedParticleSystem.dragGradients) {
  60140. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60141. var dragGradient = _s[_r];
  60142. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60143. }
  60144. }
  60145. if (parsedParticleSystem.emitRateGradients) {
  60146. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60147. var emitRateGradient = _u[_t];
  60148. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60149. }
  60150. }
  60151. if (parsedParticleSystem.startSizeGradients) {
  60152. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60153. var startSizeGradient = _w[_v];
  60154. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60155. }
  60156. }
  60157. if (parsedParticleSystem.lifeTimeGradients) {
  60158. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60159. var lifeTimeGradient = _y[_x];
  60160. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60161. }
  60162. }
  60163. if (parsedParticleSystem.limitVelocityGradients) {
  60164. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60165. var limitVelocityGradient = _0[_z];
  60166. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60167. }
  60168. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60169. }
  60170. if (parsedParticleSystem.noiseTexture) {
  60171. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60172. }
  60173. // Emitter
  60174. var emitterType;
  60175. if (parsedParticleSystem.particleEmitterType) {
  60176. switch (parsedParticleSystem.particleEmitterType.type) {
  60177. case "SphereParticleEmitter":
  60178. emitterType = new BABYLON.SphereParticleEmitter();
  60179. break;
  60180. case "SphereDirectedParticleEmitter":
  60181. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60182. break;
  60183. case "ConeEmitter":
  60184. case "ConeParticleEmitter":
  60185. emitterType = new BABYLON.ConeParticleEmitter();
  60186. break;
  60187. case "CylinderParticleEmitter":
  60188. emitterType = new BABYLON.CylinderParticleEmitter();
  60189. break;
  60190. case "HemisphericParticleEmitter":
  60191. emitterType = new BABYLON.HemisphericParticleEmitter();
  60192. break;
  60193. case "BoxEmitter":
  60194. case "BoxParticleEmitter":
  60195. default:
  60196. emitterType = new BABYLON.BoxParticleEmitter();
  60197. break;
  60198. }
  60199. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60200. }
  60201. else {
  60202. emitterType = new BABYLON.BoxParticleEmitter();
  60203. emitterType.parse(parsedParticleSystem);
  60204. }
  60205. particleSystem.particleEmitterType = emitterType;
  60206. // Animation sheet
  60207. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60208. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60209. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60210. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60211. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60212. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60213. };
  60214. /**
  60215. * Parses a JSON object to create a particle system.
  60216. * @param parsedParticleSystem The JSON object to parse
  60217. * @param scene The scene to create the particle system in
  60218. * @param rootUrl The root url to use to load external dependencies like texture
  60219. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60220. * @returns the Parsed particle system
  60221. */
  60222. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60223. if (doNotStart === void 0) { doNotStart = false; }
  60224. var name = parsedParticleSystem.name;
  60225. var custom = null;
  60226. var program = null;
  60227. if (parsedParticleSystem.customShader) {
  60228. program = parsedParticleSystem.customShader;
  60229. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60230. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60231. }
  60232. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60233. particleSystem.customShader = program;
  60234. if (parsedParticleSystem.id) {
  60235. particleSystem.id = parsedParticleSystem.id;
  60236. }
  60237. // SubEmitters
  60238. if (parsedParticleSystem.subEmitters) {
  60239. particleSystem.subEmitters = [];
  60240. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60241. var cell = _a[_i];
  60242. var cellArray = [];
  60243. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60244. var sub = cell_1[_b];
  60245. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60246. }
  60247. particleSystem.subEmitters.push(cellArray);
  60248. }
  60249. }
  60250. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60251. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60252. // Auto start
  60253. if (parsedParticleSystem.preventAutoStart) {
  60254. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60255. }
  60256. if (!doNotStart && !particleSystem.preventAutoStart) {
  60257. particleSystem.start();
  60258. }
  60259. return particleSystem;
  60260. };
  60261. /**
  60262. * Billboard mode will only apply to Y axis
  60263. */
  60264. ParticleSystem.BILLBOARDMODE_Y = 2;
  60265. /**
  60266. * Billboard mode will apply to all axes
  60267. */
  60268. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60269. /**
  60270. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60271. */
  60272. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60273. return ParticleSystem;
  60274. }(BABYLON.BaseParticleSystem));
  60275. BABYLON.ParticleSystem = ParticleSystem;
  60276. })(BABYLON || (BABYLON = {}));
  60277. //# sourceMappingURL=babylon.particleSystem.js.map
  60278. var BABYLON;
  60279. (function (BABYLON) {
  60280. /**
  60281. * Particle emitter emitting particles from the inside of a box.
  60282. * It emits the particles randomly between 2 given directions.
  60283. */
  60284. var BoxParticleEmitter = /** @class */ (function () {
  60285. /**
  60286. * Creates a new instance BoxParticleEmitter
  60287. */
  60288. function BoxParticleEmitter() {
  60289. /**
  60290. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60291. */
  60292. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60293. /**
  60294. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60295. */
  60296. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60297. /**
  60298. * 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.
  60299. */
  60300. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60301. /**
  60302. * 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.
  60303. */
  60304. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60305. }
  60306. /**
  60307. * Called by the particle System when the direction is computed for the created particle.
  60308. * @param worldMatrix is the world matrix of the particle system
  60309. * @param directionToUpdate is the direction vector to update with the result
  60310. * @param particle is the particle we are computed the direction for
  60311. */
  60312. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60313. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60314. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60315. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60316. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60317. };
  60318. /**
  60319. * Called by the particle System when the position is computed for the created particle.
  60320. * @param worldMatrix is the world matrix of the particle system
  60321. * @param positionToUpdate is the position vector to update with the result
  60322. * @param particle is the particle we are computed the position for
  60323. */
  60324. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60325. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60326. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60327. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60328. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60329. };
  60330. /**
  60331. * Clones the current emitter and returns a copy of it
  60332. * @returns the new emitter
  60333. */
  60334. BoxParticleEmitter.prototype.clone = function () {
  60335. var newOne = new BoxParticleEmitter();
  60336. BABYLON.Tools.DeepCopy(this, newOne);
  60337. return newOne;
  60338. };
  60339. /**
  60340. * Called by the GPUParticleSystem to setup the update shader
  60341. * @param effect defines the update shader
  60342. */
  60343. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60344. effect.setVector3("direction1", this.direction1);
  60345. effect.setVector3("direction2", this.direction2);
  60346. effect.setVector3("minEmitBox", this.minEmitBox);
  60347. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60348. };
  60349. /**
  60350. * Returns a string to use to update the GPU particles update shader
  60351. * @returns a string containng the defines string
  60352. */
  60353. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60354. return "#define BOXEMITTER";
  60355. };
  60356. /**
  60357. * Returns the string "BoxParticleEmitter"
  60358. * @returns a string containing the class name
  60359. */
  60360. BoxParticleEmitter.prototype.getClassName = function () {
  60361. return "BoxParticleEmitter";
  60362. };
  60363. /**
  60364. * Serializes the particle system to a JSON object.
  60365. * @returns the JSON object
  60366. */
  60367. BoxParticleEmitter.prototype.serialize = function () {
  60368. var serializationObject = {};
  60369. serializationObject.type = this.getClassName();
  60370. serializationObject.direction1 = this.direction1.asArray();
  60371. serializationObject.direction2 = this.direction2.asArray();
  60372. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60373. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60374. return serializationObject;
  60375. };
  60376. /**
  60377. * Parse properties from a JSON object
  60378. * @param serializationObject defines the JSON object
  60379. */
  60380. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60381. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60382. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60383. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60384. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60385. };
  60386. return BoxParticleEmitter;
  60387. }());
  60388. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60389. })(BABYLON || (BABYLON = {}));
  60390. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60391. var BABYLON;
  60392. (function (BABYLON) {
  60393. /**
  60394. * Particle emitter emitting particles from the inside of a cylinder.
  60395. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60396. */
  60397. var CylinderParticleEmitter = /** @class */ (function () {
  60398. /**
  60399. * Creates a new instance CylinderParticleEmitter
  60400. * @param radius the radius of the emission cylinder (1 by default)
  60401. * @param height the height of the emission cylinder (1 by default)
  60402. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60403. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60404. */
  60405. function CylinderParticleEmitter(
  60406. /**
  60407. * The radius of the emission cylinder.
  60408. */
  60409. radius,
  60410. /**
  60411. * The height of the emission cylinder.
  60412. */
  60413. height,
  60414. /**
  60415. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60416. */
  60417. radiusRange,
  60418. /**
  60419. * How much to randomize the particle direction [0-1].
  60420. */
  60421. directionRandomizer) {
  60422. if (radius === void 0) { radius = 1; }
  60423. if (height === void 0) { height = 1; }
  60424. if (radiusRange === void 0) { radiusRange = 1; }
  60425. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60426. this.radius = radius;
  60427. this.height = height;
  60428. this.radiusRange = radiusRange;
  60429. this.directionRandomizer = directionRandomizer;
  60430. }
  60431. /**
  60432. * Called by the particle System when the direction is computed for the created particle.
  60433. * @param worldMatrix is the world matrix of the particle system
  60434. * @param directionToUpdate is the direction vector to update with the result
  60435. * @param particle is the particle we are computed the direction for
  60436. */
  60437. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60438. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60439. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60440. var angle = Math.atan2(direction.x, direction.z);
  60441. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60442. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60443. direction.x = Math.sin(angle);
  60444. direction.z = Math.cos(angle);
  60445. direction.normalize();
  60446. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60447. };
  60448. /**
  60449. * Called by the particle System when the position is computed for the created particle.
  60450. * @param worldMatrix is the world matrix of the particle system
  60451. * @param positionToUpdate is the position vector to update with the result
  60452. * @param particle is the particle we are computed the position for
  60453. */
  60454. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60455. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60456. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60457. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60458. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60459. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60460. var xPos = positionRadius * Math.cos(angle);
  60461. var zPos = positionRadius * Math.sin(angle);
  60462. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60463. };
  60464. /**
  60465. * Clones the current emitter and returns a copy of it
  60466. * @returns the new emitter
  60467. */
  60468. CylinderParticleEmitter.prototype.clone = function () {
  60469. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60470. BABYLON.Tools.DeepCopy(this, newOne);
  60471. return newOne;
  60472. };
  60473. /**
  60474. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60475. * @param effect defines the update shader
  60476. */
  60477. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60478. effect.setFloat("radius", this.radius);
  60479. effect.setFloat("height", this.height);
  60480. effect.setFloat("radiusRange", this.radiusRange);
  60481. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60482. };
  60483. /**
  60484. * Returns a string to use to update the GPU particles update shader
  60485. * @returns a string containng the defines string
  60486. */
  60487. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60488. return "#define CYLINDEREMITTER";
  60489. };
  60490. /**
  60491. * Returns the string "CylinderParticleEmitter"
  60492. * @returns a string containing the class name
  60493. */
  60494. CylinderParticleEmitter.prototype.getClassName = function () {
  60495. return "CylinderParticleEmitter";
  60496. };
  60497. /**
  60498. * Serializes the particle system to a JSON object.
  60499. * @returns the JSON object
  60500. */
  60501. CylinderParticleEmitter.prototype.serialize = function () {
  60502. var serializationObject = {};
  60503. serializationObject.type = this.getClassName();
  60504. serializationObject.radius = this.radius;
  60505. serializationObject.height = this.height;
  60506. serializationObject.radiusRange = this.radiusRange;
  60507. serializationObject.directionRandomizer = this.directionRandomizer;
  60508. return serializationObject;
  60509. };
  60510. /**
  60511. * Parse properties from a JSON object
  60512. * @param serializationObject defines the JSON object
  60513. */
  60514. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60515. this.radius = serializationObject.radius;
  60516. this.height = serializationObject.height;
  60517. this.radiusRange = serializationObject.radiusRange;
  60518. this.directionRandomizer = serializationObject.directionRandomizer;
  60519. };
  60520. return CylinderParticleEmitter;
  60521. }());
  60522. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60523. /**
  60524. * Particle emitter emitting particles from the inside of a cylinder.
  60525. * It emits the particles randomly between two vectors.
  60526. */
  60527. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60528. __extends(CylinderDirectedParticleEmitter, _super);
  60529. /**
  60530. * Creates a new instance CylinderDirectedParticleEmitter
  60531. * @param radius the radius of the emission cylinder (1 by default)
  60532. * @param height the height of the emission cylinder (1 by default)
  60533. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60534. * @param direction1 the min limit of the emission direction (up vector by default)
  60535. * @param direction2 the max limit of the emission direction (up vector by default)
  60536. */
  60537. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60538. /**
  60539. * The min limit of the emission direction.
  60540. */
  60541. direction1,
  60542. /**
  60543. * The max limit of the emission direction.
  60544. */
  60545. direction2) {
  60546. if (radius === void 0) { radius = 1; }
  60547. if (height === void 0) { height = 1; }
  60548. if (radiusRange === void 0) { radiusRange = 1; }
  60549. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60550. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60551. var _this = _super.call(this, radius, height, radiusRange) || this;
  60552. _this.direction1 = direction1;
  60553. _this.direction2 = direction2;
  60554. return _this;
  60555. }
  60556. /**
  60557. * Called by the particle System when the direction is computed for the created particle.
  60558. * @param worldMatrix is the world matrix of the particle system
  60559. * @param directionToUpdate is the direction vector to update with the result
  60560. * @param particle is the particle we are computed the direction for
  60561. */
  60562. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60563. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60564. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60565. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60566. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60567. };
  60568. /**
  60569. * Clones the current emitter and returns a copy of it
  60570. * @returns the new emitter
  60571. */
  60572. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60573. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60574. BABYLON.Tools.DeepCopy(this, newOne);
  60575. return newOne;
  60576. };
  60577. /**
  60578. * Called by the GPUParticleSystem to setup the update shader
  60579. * @param effect defines the update shader
  60580. */
  60581. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60582. effect.setFloat("radius", this.radius);
  60583. effect.setFloat("height", this.height);
  60584. effect.setFloat("radiusRange", this.radiusRange);
  60585. effect.setVector3("direction1", this.direction1);
  60586. effect.setVector3("direction2", this.direction2);
  60587. };
  60588. /**
  60589. * Returns a string to use to update the GPU particles update shader
  60590. * @returns a string containng the defines string
  60591. */
  60592. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60593. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60594. };
  60595. /**
  60596. * Returns the string "CylinderDirectedParticleEmitter"
  60597. * @returns a string containing the class name
  60598. */
  60599. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60600. return "CylinderDirectedParticleEmitter";
  60601. };
  60602. /**
  60603. * Serializes the particle system to a JSON object.
  60604. * @returns the JSON object
  60605. */
  60606. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60607. var serializationObject = _super.prototype.serialize.call(this);
  60608. serializationObject.direction1 = this.direction1.asArray();
  60609. serializationObject.direction2 = this.direction2.asArray();
  60610. return serializationObject;
  60611. };
  60612. /**
  60613. * Parse properties from a JSON object
  60614. * @param serializationObject defines the JSON object
  60615. */
  60616. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60617. _super.prototype.parse.call(this, serializationObject);
  60618. this.direction1.copyFrom(serializationObject.direction1);
  60619. this.direction2.copyFrom(serializationObject.direction2);
  60620. };
  60621. return CylinderDirectedParticleEmitter;
  60622. }(CylinderParticleEmitter));
  60623. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60624. })(BABYLON || (BABYLON = {}));
  60625. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60626. var BABYLON;
  60627. (function (BABYLON) {
  60628. /**
  60629. * Particle emitter emitting particles from the inside of a cone.
  60630. * It emits the particles alongside the cone volume from the base to the particle.
  60631. * The emission direction might be randomized.
  60632. */
  60633. var ConeParticleEmitter = /** @class */ (function () {
  60634. /**
  60635. * Creates a new instance ConeParticleEmitter
  60636. * @param radius the radius of the emission cone (1 by default)
  60637. * @param angles the cone base angle (PI by default)
  60638. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60639. */
  60640. function ConeParticleEmitter(radius, angle,
  60641. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60642. directionRandomizer) {
  60643. if (radius === void 0) { radius = 1; }
  60644. if (angle === void 0) { angle = Math.PI; }
  60645. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60646. this.directionRandomizer = directionRandomizer;
  60647. /**
  60648. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60649. */
  60650. this.radiusRange = 1;
  60651. /**
  60652. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60653. */
  60654. this.heightRange = 1;
  60655. /**
  60656. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60657. */
  60658. this.emitFromSpawnPointOnly = false;
  60659. this.angle = angle;
  60660. this.radius = radius;
  60661. }
  60662. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60663. /**
  60664. * Gets or sets the radius of the emission cone
  60665. */
  60666. get: function () {
  60667. return this._radius;
  60668. },
  60669. set: function (value) {
  60670. this._radius = value;
  60671. this._buildHeight();
  60672. },
  60673. enumerable: true,
  60674. configurable: true
  60675. });
  60676. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60677. /**
  60678. * Gets or sets the angle of the emission cone
  60679. */
  60680. get: function () {
  60681. return this._angle;
  60682. },
  60683. set: function (value) {
  60684. this._angle = value;
  60685. this._buildHeight();
  60686. },
  60687. enumerable: true,
  60688. configurable: true
  60689. });
  60690. ConeParticleEmitter.prototype._buildHeight = function () {
  60691. if (this._angle !== 0) {
  60692. this._height = this._radius / Math.tan(this._angle / 2);
  60693. }
  60694. else {
  60695. this._height = 1;
  60696. }
  60697. };
  60698. /**
  60699. * Called by the particle System when the direction is computed for the created particle.
  60700. * @param worldMatrix is the world matrix of the particle system
  60701. * @param directionToUpdate is the direction vector to update with the result
  60702. * @param particle is the particle we are computed the direction for
  60703. */
  60704. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60705. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60706. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60707. }
  60708. else {
  60709. // measure the direction Vector from the emitter to the particle.
  60710. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60711. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60712. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60713. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60714. direction.x += randX;
  60715. direction.y += randY;
  60716. direction.z += randZ;
  60717. direction.normalize();
  60718. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60719. }
  60720. };
  60721. /**
  60722. * Called by the particle System when the position is computed for the created particle.
  60723. * @param worldMatrix is the world matrix of the particle system
  60724. * @param positionToUpdate is the position vector to update with the result
  60725. * @param particle is the particle we are computed the position for
  60726. */
  60727. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60728. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60729. var h;
  60730. if (!this.emitFromSpawnPointOnly) {
  60731. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60732. // Better distribution in a cone at normal angles.
  60733. h = 1 - h * h;
  60734. }
  60735. else {
  60736. h = 0.0001;
  60737. }
  60738. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60739. radius = radius * h;
  60740. var randX = radius * Math.sin(s);
  60741. var randZ = radius * Math.cos(s);
  60742. var randY = h * this._height;
  60743. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60744. };
  60745. /**
  60746. * Clones the current emitter and returns a copy of it
  60747. * @returns the new emitter
  60748. */
  60749. ConeParticleEmitter.prototype.clone = function () {
  60750. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60751. BABYLON.Tools.DeepCopy(this, newOne);
  60752. return newOne;
  60753. };
  60754. /**
  60755. * Called by the GPUParticleSystem to setup the update shader
  60756. * @param effect defines the update shader
  60757. */
  60758. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60759. effect.setFloat2("radius", this._radius, this.radiusRange);
  60760. effect.setFloat("coneAngle", this._angle);
  60761. effect.setFloat2("height", this._height, this.heightRange);
  60762. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60763. };
  60764. /**
  60765. * Returns a string to use to update the GPU particles update shader
  60766. * @returns a string containng the defines string
  60767. */
  60768. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60769. var defines = "#define CONEEMITTER";
  60770. if (this.emitFromSpawnPointOnly) {
  60771. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60772. }
  60773. return defines;
  60774. };
  60775. /**
  60776. * Returns the string "ConeParticleEmitter"
  60777. * @returns a string containing the class name
  60778. */
  60779. ConeParticleEmitter.prototype.getClassName = function () {
  60780. return "ConeParticleEmitter";
  60781. };
  60782. /**
  60783. * Serializes the particle system to a JSON object.
  60784. * @returns the JSON object
  60785. */
  60786. ConeParticleEmitter.prototype.serialize = function () {
  60787. var serializationObject = {};
  60788. serializationObject.type = this.getClassName();
  60789. serializationObject.radius = this._radius;
  60790. serializationObject.angle = this._angle;
  60791. serializationObject.directionRandomizer = this.directionRandomizer;
  60792. return serializationObject;
  60793. };
  60794. /**
  60795. * Parse properties from a JSON object
  60796. * @param serializationObject defines the JSON object
  60797. */
  60798. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60799. this.radius = serializationObject.radius;
  60800. this.angle = serializationObject.angle;
  60801. this.directionRandomizer = serializationObject.directionRandomizer;
  60802. };
  60803. return ConeParticleEmitter;
  60804. }());
  60805. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60806. })(BABYLON || (BABYLON = {}));
  60807. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60808. var BABYLON;
  60809. (function (BABYLON) {
  60810. /**
  60811. * Particle emitter emitting particles from the inside of a sphere.
  60812. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60813. */
  60814. var SphereParticleEmitter = /** @class */ (function () {
  60815. /**
  60816. * Creates a new instance SphereParticleEmitter
  60817. * @param radius the radius of the emission sphere (1 by default)
  60818. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60819. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60820. */
  60821. function SphereParticleEmitter(
  60822. /**
  60823. * The radius of the emission sphere.
  60824. */
  60825. radius,
  60826. /**
  60827. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60828. */
  60829. radiusRange,
  60830. /**
  60831. * How much to randomize the particle direction [0-1].
  60832. */
  60833. directionRandomizer) {
  60834. if (radius === void 0) { radius = 1; }
  60835. if (radiusRange === void 0) { radiusRange = 1; }
  60836. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60837. this.radius = radius;
  60838. this.radiusRange = radiusRange;
  60839. this.directionRandomizer = directionRandomizer;
  60840. }
  60841. /**
  60842. * Called by the particle System when the direction is computed for the created particle.
  60843. * @param worldMatrix is the world matrix of the particle system
  60844. * @param directionToUpdate is the direction vector to update with the result
  60845. * @param particle is the particle we are computed the direction for
  60846. */
  60847. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60848. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60849. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60850. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60851. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60852. direction.x += randX;
  60853. direction.y += randY;
  60854. direction.z += randZ;
  60855. direction.normalize();
  60856. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60857. };
  60858. /**
  60859. * Called by the particle System when the position is computed for the created particle.
  60860. * @param worldMatrix is the world matrix of the particle system
  60861. * @param positionToUpdate is the position vector to update with the result
  60862. * @param particle is the particle we are computed the position for
  60863. */
  60864. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60865. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60866. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60867. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60868. var theta = Math.acos(2 * v - 1);
  60869. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60870. var randY = randRadius * Math.cos(theta);
  60871. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60872. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60873. };
  60874. /**
  60875. * Clones the current emitter and returns a copy of it
  60876. * @returns the new emitter
  60877. */
  60878. SphereParticleEmitter.prototype.clone = function () {
  60879. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60880. BABYLON.Tools.DeepCopy(this, newOne);
  60881. return newOne;
  60882. };
  60883. /**
  60884. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60885. * @param effect defines the update shader
  60886. */
  60887. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60888. effect.setFloat("radius", this.radius);
  60889. effect.setFloat("radiusRange", this.radiusRange);
  60890. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60891. };
  60892. /**
  60893. * Returns a string to use to update the GPU particles update shader
  60894. * @returns a string containng the defines string
  60895. */
  60896. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60897. return "#define SPHEREEMITTER";
  60898. };
  60899. /**
  60900. * Returns the string "SphereParticleEmitter"
  60901. * @returns a string containing the class name
  60902. */
  60903. SphereParticleEmitter.prototype.getClassName = function () {
  60904. return "SphereParticleEmitter";
  60905. };
  60906. /**
  60907. * Serializes the particle system to a JSON object.
  60908. * @returns the JSON object
  60909. */
  60910. SphereParticleEmitter.prototype.serialize = function () {
  60911. var serializationObject = {};
  60912. serializationObject.type = this.getClassName();
  60913. serializationObject.radius = this.radius;
  60914. serializationObject.radiusRange = this.radiusRange;
  60915. serializationObject.directionRandomizer = this.directionRandomizer;
  60916. return serializationObject;
  60917. };
  60918. /**
  60919. * Parse properties from a JSON object
  60920. * @param serializationObject defines the JSON object
  60921. */
  60922. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60923. this.radius = serializationObject.radius;
  60924. this.radiusRange = serializationObject.radiusRange;
  60925. this.directionRandomizer = serializationObject.directionRandomizer;
  60926. };
  60927. return SphereParticleEmitter;
  60928. }());
  60929. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60930. /**
  60931. * Particle emitter emitting particles from the inside of a sphere.
  60932. * It emits the particles randomly between two vectors.
  60933. */
  60934. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60935. __extends(SphereDirectedParticleEmitter, _super);
  60936. /**
  60937. * Creates a new instance SphereDirectedParticleEmitter
  60938. * @param radius the radius of the emission sphere (1 by default)
  60939. * @param direction1 the min limit of the emission direction (up vector by default)
  60940. * @param direction2 the max limit of the emission direction (up vector by default)
  60941. */
  60942. function SphereDirectedParticleEmitter(radius,
  60943. /**
  60944. * The min limit of the emission direction.
  60945. */
  60946. direction1,
  60947. /**
  60948. * The max limit of the emission direction.
  60949. */
  60950. direction2) {
  60951. if (radius === void 0) { radius = 1; }
  60952. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60953. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60954. var _this = _super.call(this, radius) || this;
  60955. _this.direction1 = direction1;
  60956. _this.direction2 = direction2;
  60957. return _this;
  60958. }
  60959. /**
  60960. * Called by the particle System when the direction is computed for the created particle.
  60961. * @param worldMatrix is the world matrix of the particle system
  60962. * @param directionToUpdate is the direction vector to update with the result
  60963. * @param particle is the particle we are computed the direction for
  60964. */
  60965. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60966. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60967. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60968. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60969. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60970. };
  60971. /**
  60972. * Clones the current emitter and returns a copy of it
  60973. * @returns the new emitter
  60974. */
  60975. SphereDirectedParticleEmitter.prototype.clone = function () {
  60976. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60977. BABYLON.Tools.DeepCopy(this, newOne);
  60978. return newOne;
  60979. };
  60980. /**
  60981. * Called by the GPUParticleSystem to setup the update shader
  60982. * @param effect defines the update shader
  60983. */
  60984. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60985. effect.setFloat("radius", this.radius);
  60986. effect.setFloat("radiusRange", this.radiusRange);
  60987. effect.setVector3("direction1", this.direction1);
  60988. effect.setVector3("direction2", this.direction2);
  60989. };
  60990. /**
  60991. * Returns a string to use to update the GPU particles update shader
  60992. * @returns a string containng the defines string
  60993. */
  60994. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60995. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60996. };
  60997. /**
  60998. * Returns the string "SphereDirectedParticleEmitter"
  60999. * @returns a string containing the class name
  61000. */
  61001. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61002. return "SphereDirectedParticleEmitter";
  61003. };
  61004. /**
  61005. * Serializes the particle system to a JSON object.
  61006. * @returns the JSON object
  61007. */
  61008. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61009. var serializationObject = _super.prototype.serialize.call(this);
  61010. serializationObject.direction1 = this.direction1.asArray();
  61011. serializationObject.direction2 = this.direction2.asArray();
  61012. return serializationObject;
  61013. };
  61014. /**
  61015. * Parse properties from a JSON object
  61016. * @param serializationObject defines the JSON object
  61017. */
  61018. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61019. _super.prototype.parse.call(this, serializationObject);
  61020. this.direction1.copyFrom(serializationObject.direction1);
  61021. this.direction2.copyFrom(serializationObject.direction2);
  61022. };
  61023. return SphereDirectedParticleEmitter;
  61024. }(SphereParticleEmitter));
  61025. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61026. })(BABYLON || (BABYLON = {}));
  61027. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61028. var BABYLON;
  61029. (function (BABYLON) {
  61030. /**
  61031. * Particle emitter emitting particles from the inside of a hemisphere.
  61032. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61033. */
  61034. var HemisphericParticleEmitter = /** @class */ (function () {
  61035. /**
  61036. * Creates a new instance HemisphericParticleEmitter
  61037. * @param radius the radius of the emission hemisphere (1 by default)
  61038. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61039. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61040. */
  61041. function HemisphericParticleEmitter(
  61042. /**
  61043. * The radius of the emission hemisphere.
  61044. */
  61045. radius,
  61046. /**
  61047. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61048. */
  61049. radiusRange,
  61050. /**
  61051. * How much to randomize the particle direction [0-1].
  61052. */
  61053. directionRandomizer) {
  61054. if (radius === void 0) { radius = 1; }
  61055. if (radiusRange === void 0) { radiusRange = 1; }
  61056. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61057. this.radius = radius;
  61058. this.radiusRange = radiusRange;
  61059. this.directionRandomizer = directionRandomizer;
  61060. }
  61061. /**
  61062. * Called by the particle System when the direction is computed for the created particle.
  61063. * @param worldMatrix is the world matrix of the particle system
  61064. * @param directionToUpdate is the direction vector to update with the result
  61065. * @param particle is the particle we are computed the direction for
  61066. */
  61067. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61068. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61069. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61070. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61071. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61072. direction.x += randX;
  61073. direction.y += randY;
  61074. direction.z += randZ;
  61075. direction.normalize();
  61076. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61077. };
  61078. /**
  61079. * Called by the particle System when the position is computed for the created particle.
  61080. * @param worldMatrix is the world matrix of the particle system
  61081. * @param positionToUpdate is the position vector to update with the result
  61082. * @param particle is the particle we are computed the position for
  61083. */
  61084. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61085. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61086. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61087. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61088. var theta = Math.acos(2 * v - 1);
  61089. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61090. var randY = randRadius * Math.cos(theta);
  61091. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61092. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61093. };
  61094. /**
  61095. * Clones the current emitter and returns a copy of it
  61096. * @returns the new emitter
  61097. */
  61098. HemisphericParticleEmitter.prototype.clone = function () {
  61099. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61100. BABYLON.Tools.DeepCopy(this, newOne);
  61101. return newOne;
  61102. };
  61103. /**
  61104. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61105. * @param effect defines the update shader
  61106. */
  61107. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61108. effect.setFloat("radius", this.radius);
  61109. effect.setFloat("radiusRange", this.radiusRange);
  61110. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61111. };
  61112. /**
  61113. * Returns a string to use to update the GPU particles update shader
  61114. * @returns a string containng the defines string
  61115. */
  61116. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61117. return "#define HEMISPHERICEMITTER";
  61118. };
  61119. /**
  61120. * Returns the string "HemisphericParticleEmitter"
  61121. * @returns a string containing the class name
  61122. */
  61123. HemisphericParticleEmitter.prototype.getClassName = function () {
  61124. return "HemisphericParticleEmitter";
  61125. };
  61126. /**
  61127. * Serializes the particle system to a JSON object.
  61128. * @returns the JSON object
  61129. */
  61130. HemisphericParticleEmitter.prototype.serialize = function () {
  61131. var serializationObject = {};
  61132. serializationObject.type = this.getClassName();
  61133. serializationObject.radius = this.radius;
  61134. serializationObject.radiusRange = this.radiusRange;
  61135. serializationObject.directionRandomizer = this.directionRandomizer;
  61136. return serializationObject;
  61137. };
  61138. /**
  61139. * Parse properties from a JSON object
  61140. * @param serializationObject defines the JSON object
  61141. */
  61142. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61143. this.radius = serializationObject.radius;
  61144. this.radiusRange = serializationObject.radiusRange;
  61145. this.directionRandomizer = serializationObject.directionRandomizer;
  61146. };
  61147. return HemisphericParticleEmitter;
  61148. }());
  61149. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61150. })(BABYLON || (BABYLON = {}));
  61151. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61152. var BABYLON;
  61153. (function (BABYLON) {
  61154. /**
  61155. * Particle emitter emitting particles from a point.
  61156. * It emits the particles randomly between 2 given directions.
  61157. */
  61158. var PointParticleEmitter = /** @class */ (function () {
  61159. /**
  61160. * Creates a new instance PointParticleEmitter
  61161. */
  61162. function PointParticleEmitter() {
  61163. /**
  61164. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61165. */
  61166. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61167. /**
  61168. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61169. */
  61170. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61171. }
  61172. /**
  61173. * Called by the particle System when the direction is computed for the created particle.
  61174. * @param worldMatrix is the world matrix of the particle system
  61175. * @param directionToUpdate is the direction vector to update with the result
  61176. * @param particle is the particle we are computed the direction for
  61177. */
  61178. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61179. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61180. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61181. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61182. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61183. };
  61184. /**
  61185. * Called by the particle System when the position is computed for the created particle.
  61186. * @param worldMatrix is the world matrix of the particle system
  61187. * @param positionToUpdate is the position vector to update with the result
  61188. * @param particle is the particle we are computed the position for
  61189. */
  61190. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61192. };
  61193. /**
  61194. * Clones the current emitter and returns a copy of it
  61195. * @returns the new emitter
  61196. */
  61197. PointParticleEmitter.prototype.clone = function () {
  61198. var newOne = new PointParticleEmitter();
  61199. BABYLON.Tools.DeepCopy(this, newOne);
  61200. return newOne;
  61201. };
  61202. /**
  61203. * Called by the GPUParticleSystem to setup the update shader
  61204. * @param effect defines the update shader
  61205. */
  61206. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61207. effect.setVector3("direction1", this.direction1);
  61208. effect.setVector3("direction2", this.direction2);
  61209. };
  61210. /**
  61211. * Returns a string to use to update the GPU particles update shader
  61212. * @returns a string containng the defines string
  61213. */
  61214. PointParticleEmitter.prototype.getEffectDefines = function () {
  61215. return "#define POINTEMITTER";
  61216. };
  61217. /**
  61218. * Returns the string "PointParticleEmitter"
  61219. * @returns a string containing the class name
  61220. */
  61221. PointParticleEmitter.prototype.getClassName = function () {
  61222. return "PointParticleEmitter";
  61223. };
  61224. /**
  61225. * Serializes the particle system to a JSON object.
  61226. * @returns the JSON object
  61227. */
  61228. PointParticleEmitter.prototype.serialize = function () {
  61229. var serializationObject = {};
  61230. serializationObject.type = this.getClassName();
  61231. serializationObject.direction1 = this.direction1.asArray();
  61232. serializationObject.direction2 = this.direction2.asArray();
  61233. return serializationObject;
  61234. };
  61235. /**
  61236. * Parse properties from a JSON object
  61237. * @param serializationObject defines the JSON object
  61238. */
  61239. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61240. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61241. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61242. };
  61243. return PointParticleEmitter;
  61244. }());
  61245. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61246. })(BABYLON || (BABYLON = {}));
  61247. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61248. var BABYLON;
  61249. (function (BABYLON) {
  61250. // Adds the parsers to the scene parsers.
  61251. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61252. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61253. if (!individualParser) {
  61254. return;
  61255. }
  61256. // Particles Systems
  61257. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61258. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61259. var parsedParticleSystem = parsedData.particleSystems[index];
  61260. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61261. }
  61262. }
  61263. });
  61264. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61265. if (parsedParticleSystem.activeParticleCount) {
  61266. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61267. return ps;
  61268. }
  61269. else {
  61270. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61271. return ps;
  61272. }
  61273. });
  61274. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61275. if (uniformsNames === void 0) { uniformsNames = []; }
  61276. if (samplers === void 0) { samplers = []; }
  61277. if (defines === void 0) { defines = ""; }
  61278. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61279. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61280. if (defines.indexOf(" BILLBOARD") === -1) {
  61281. defines += "\n#define BILLBOARD\n";
  61282. }
  61283. if (samplers.indexOf("diffuseSampler") === -1) {
  61284. samplers.push("diffuseSampler");
  61285. }
  61286. return this.createEffect({
  61287. vertex: "particles",
  61288. fragmentElement: fragmentName
  61289. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61290. };
  61291. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61292. var results = new Array();
  61293. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61294. var particleSystem = this.getScene().particleSystems[index];
  61295. if (particleSystem.emitter === this) {
  61296. results.push(particleSystem);
  61297. }
  61298. }
  61299. return results;
  61300. };
  61301. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61302. var results = new Array();
  61303. var descendants = this.getDescendants();
  61304. descendants.push(this);
  61305. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61306. var particleSystem = this.getScene().particleSystems[index];
  61307. var emitter = particleSystem.emitter;
  61308. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61309. results.push(particleSystem);
  61310. }
  61311. }
  61312. return results;
  61313. };
  61314. })(BABYLON || (BABYLON = {}));
  61315. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61316. var BABYLON;
  61317. (function (BABYLON) {
  61318. /**
  61319. * Type of sub emitter
  61320. */
  61321. var SubEmitterType;
  61322. (function (SubEmitterType) {
  61323. /**
  61324. * Attached to the particle over it's lifetime
  61325. */
  61326. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61327. /**
  61328. * Created when the particle dies
  61329. */
  61330. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61331. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61332. /**
  61333. * Sub emitter class used to emit particles from an existing particle
  61334. */
  61335. var SubEmitter = /** @class */ (function () {
  61336. /**
  61337. * Creates a sub emitter
  61338. * @param particleSystem the particle system to be used by the sub emitter
  61339. */
  61340. function SubEmitter(
  61341. /**
  61342. * the particle system to be used by the sub emitter
  61343. */
  61344. particleSystem) {
  61345. this.particleSystem = particleSystem;
  61346. /**
  61347. * Type of the submitter (Default: END)
  61348. */
  61349. this.type = SubEmitterType.END;
  61350. /**
  61351. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  61352. * Note: This only is supported when using an emitter of type Mesh
  61353. */
  61354. this.inheritDirection = false;
  61355. /**
  61356. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61357. */
  61358. this.inheritedVelocityAmount = 0;
  61359. }
  61360. /**
  61361. * Clones the sub emitter
  61362. * @returns the cloned sub emitter
  61363. */
  61364. SubEmitter.prototype.clone = function () {
  61365. // Clone particle system
  61366. var emitter = this.particleSystem.emitter;
  61367. if (!emitter) {
  61368. emitter = new BABYLON.Vector3();
  61369. }
  61370. else if (emitter instanceof BABYLON.Vector3) {
  61371. emitter = emitter.clone();
  61372. }
  61373. else if (emitter instanceof BABYLON.AbstractMesh) {
  61374. emitter = new BABYLON.Mesh("", emitter.getScene());
  61375. emitter.isVisible = false;
  61376. }
  61377. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61378. // Clone properties
  61379. clone.type = this.type;
  61380. clone.inheritDirection = this.inheritDirection;
  61381. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61382. clone.particleSystem._disposeEmitterOnDispose = true;
  61383. clone.particleSystem.disposeOnStop = true;
  61384. return clone;
  61385. };
  61386. /**
  61387. * Serialize current object to a JSON object
  61388. * @returns the serialized object
  61389. */
  61390. SubEmitter.prototype.serialize = function () {
  61391. var serializationObject = {};
  61392. serializationObject.type = this.type;
  61393. serializationObject.inheritDirection = this.inheritDirection;
  61394. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61395. serializationObject.particleSystem = this.particleSystem.serialize();
  61396. return serializationObject;
  61397. };
  61398. /**
  61399. * Creates a new SubEmitter from a serialized JSON version
  61400. * @param serializationObject defines the JSON object to read from
  61401. * @param scene defines the hosting scene
  61402. * @param rootUrl defines the rootUrl for data loading
  61403. * @returns a new SubEmitter
  61404. */
  61405. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61406. var system = serializationObject.particleSystem;
  61407. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61408. subEmitter.type = serializationObject.type;
  61409. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61410. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61411. subEmitter.particleSystem._isSubEmitter = true;
  61412. return subEmitter;
  61413. };
  61414. /** Release associated resources */
  61415. SubEmitter.prototype.dispose = function () {
  61416. this.particleSystem.dispose();
  61417. };
  61418. return SubEmitter;
  61419. }());
  61420. BABYLON.SubEmitter = SubEmitter;
  61421. })(BABYLON || (BABYLON = {}));
  61422. //# sourceMappingURL=babylon.subEmitter.js.map
  61423. var BABYLON;
  61424. (function (BABYLON) {
  61425. /**
  61426. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61427. *
  61428. * This returned material effects how the mesh will look based on the code in the shaders.
  61429. *
  61430. * @see http://doc.babylonjs.com/how_to/shader_material
  61431. */
  61432. var ShaderMaterial = /** @class */ (function (_super) {
  61433. __extends(ShaderMaterial, _super);
  61434. /**
  61435. * Instantiate a new shader material.
  61436. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61437. * This returned material effects how the mesh will look based on the code in the shaders.
  61438. * @see http://doc.babylonjs.com/how_to/shader_material
  61439. * @param name Define the name of the material in the scene
  61440. * @param scene Define the scene the material belongs to
  61441. * @param shaderPath Defines the route to the shader code in one of three ways:
  61442. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61443. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61444. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61445. * @param options Define the options used to create the shader
  61446. */
  61447. function ShaderMaterial(name, scene, shaderPath, options) {
  61448. if (options === void 0) { options = {}; }
  61449. var _this = _super.call(this, name, scene) || this;
  61450. _this._textures = {};
  61451. _this._textureArrays = {};
  61452. _this._floats = {};
  61453. _this._ints = {};
  61454. _this._floatsArrays = {};
  61455. _this._colors3 = {};
  61456. _this._colors3Arrays = {};
  61457. _this._colors4 = {};
  61458. _this._vectors2 = {};
  61459. _this._vectors3 = {};
  61460. _this._vectors4 = {};
  61461. _this._matrices = {};
  61462. _this._matrices3x3 = {};
  61463. _this._matrices2x2 = {};
  61464. _this._vectors2Arrays = {};
  61465. _this._vectors3Arrays = {};
  61466. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61467. _this._shaderPath = shaderPath;
  61468. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61469. return _this;
  61470. }
  61471. /**
  61472. * Gets the current class name of the material e.g. "ShaderMaterial"
  61473. * Mainly use in serialization.
  61474. * @returns the class name
  61475. */
  61476. ShaderMaterial.prototype.getClassName = function () {
  61477. return "ShaderMaterial";
  61478. };
  61479. /**
  61480. * Specifies if the material will require alpha blending
  61481. * @returns a boolean specifying if alpha blending is needed
  61482. */
  61483. ShaderMaterial.prototype.needAlphaBlending = function () {
  61484. return (this.alpha < 1.0);
  61485. };
  61486. /**
  61487. * Specifies if this material should be rendered in alpha test mode
  61488. * @returns a boolean specifying if an alpha test is needed.
  61489. */
  61490. ShaderMaterial.prototype.needAlphaTesting = function () {
  61491. return this._options.needAlphaTesting;
  61492. };
  61493. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61494. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61495. this._options.uniforms.push(uniformName);
  61496. }
  61497. };
  61498. /**
  61499. * Set a texture in the shader.
  61500. * @param name Define the name of the uniform samplers as defined in the shader
  61501. * @param texture Define the texture to bind to this sampler
  61502. * @return the material itself allowing "fluent" like uniform updates
  61503. */
  61504. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61505. if (this._options.samplers.indexOf(name) === -1) {
  61506. this._options.samplers.push(name);
  61507. }
  61508. this._textures[name] = texture;
  61509. return this;
  61510. };
  61511. /**
  61512. * Set a texture array in the shader.
  61513. * @param name Define the name of the uniform sampler array as defined in the shader
  61514. * @param textures Define the list of textures to bind to this sampler
  61515. * @return the material itself allowing "fluent" like uniform updates
  61516. */
  61517. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61518. if (this._options.samplers.indexOf(name) === -1) {
  61519. this._options.samplers.push(name);
  61520. }
  61521. this._checkUniform(name);
  61522. this._textureArrays[name] = textures;
  61523. return this;
  61524. };
  61525. /**
  61526. * Set a float in the shader.
  61527. * @param name Define the name of the uniform as defined in the shader
  61528. * @param value Define the value to give to the uniform
  61529. * @return the material itself allowing "fluent" like uniform updates
  61530. */
  61531. ShaderMaterial.prototype.setFloat = function (name, value) {
  61532. this._checkUniform(name);
  61533. this._floats[name] = value;
  61534. return this;
  61535. };
  61536. /**
  61537. * Set a int in the shader.
  61538. * @param name Define the name of the uniform as defined in the shader
  61539. * @param value Define the value to give to the uniform
  61540. * @return the material itself allowing "fluent" like uniform updates
  61541. */
  61542. ShaderMaterial.prototype.setInt = function (name, value) {
  61543. this._checkUniform(name);
  61544. this._ints[name] = value;
  61545. return this;
  61546. };
  61547. /**
  61548. * Set an array of floats in the shader.
  61549. * @param name Define the name of the uniform as defined in the shader
  61550. * @param value Define the value to give to the uniform
  61551. * @return the material itself allowing "fluent" like uniform updates
  61552. */
  61553. ShaderMaterial.prototype.setFloats = function (name, value) {
  61554. this._checkUniform(name);
  61555. this._floatsArrays[name] = value;
  61556. return this;
  61557. };
  61558. /**
  61559. * Set a vec3 in the shader from a Color3.
  61560. * @param name Define the name of the uniform as defined in the shader
  61561. * @param value Define the value to give to the uniform
  61562. * @return the material itself allowing "fluent" like uniform updates
  61563. */
  61564. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61565. this._checkUniform(name);
  61566. this._colors3[name] = value;
  61567. return this;
  61568. };
  61569. /**
  61570. * Set a vec3 array in the shader from a Color3 array.
  61571. * @param name Define the name of the uniform as defined in the shader
  61572. * @param value Define the value to give to the uniform
  61573. * @return the material itself allowing "fluent" like uniform updates
  61574. */
  61575. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61576. this._checkUniform(name);
  61577. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61578. color.toArray(arr, arr.length);
  61579. return arr;
  61580. }, []);
  61581. return this;
  61582. };
  61583. /**
  61584. * Set a vec4 in the shader from a Color4.
  61585. * @param name Define the name of the uniform as defined in the shader
  61586. * @param value Define the value to give to the uniform
  61587. * @return the material itself allowing "fluent" like uniform updates
  61588. */
  61589. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61590. this._checkUniform(name);
  61591. this._colors4[name] = value;
  61592. return this;
  61593. };
  61594. /**
  61595. * Set a vec2 in the shader from a Vector2.
  61596. * @param name Define the name of the uniform as defined in the shader
  61597. * @param value Define the value to give to the uniform
  61598. * @return the material itself allowing "fluent" like uniform updates
  61599. */
  61600. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61601. this._checkUniform(name);
  61602. this._vectors2[name] = value;
  61603. return this;
  61604. };
  61605. /**
  61606. * Set a vec3 in the shader from a Vector3.
  61607. * @param name Define the name of the uniform as defined in the shader
  61608. * @param value Define the value to give to the uniform
  61609. * @return the material itself allowing "fluent" like uniform updates
  61610. */
  61611. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61612. this._checkUniform(name);
  61613. this._vectors3[name] = value;
  61614. return this;
  61615. };
  61616. /**
  61617. * Set a vec4 in the shader from a Vector4.
  61618. * @param name Define the name of the uniform as defined in the shader
  61619. * @param value Define the value to give to the uniform
  61620. * @return the material itself allowing "fluent" like uniform updates
  61621. */
  61622. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61623. this._checkUniform(name);
  61624. this._vectors4[name] = value;
  61625. return this;
  61626. };
  61627. /**
  61628. * Set a mat4 in the shader from a Matrix.
  61629. * @param name Define the name of the uniform as defined in the shader
  61630. * @param value Define the value to give to the uniform
  61631. * @return the material itself allowing "fluent" like uniform updates
  61632. */
  61633. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61634. this._checkUniform(name);
  61635. this._matrices[name] = value;
  61636. return this;
  61637. };
  61638. /**
  61639. * Set a mat3 in the shader from a Float32Array.
  61640. * @param name Define the name of the uniform as defined in the shader
  61641. * @param value Define the value to give to the uniform
  61642. * @return the material itself allowing "fluent" like uniform updates
  61643. */
  61644. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61645. this._checkUniform(name);
  61646. this._matrices3x3[name] = value;
  61647. return this;
  61648. };
  61649. /**
  61650. * Set a mat2 in the shader from a Float32Array.
  61651. * @param name Define the name of the uniform as defined in the shader
  61652. * @param value Define the value to give to the uniform
  61653. * @return the material itself allowing "fluent" like uniform updates
  61654. */
  61655. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61656. this._checkUniform(name);
  61657. this._matrices2x2[name] = value;
  61658. return this;
  61659. };
  61660. /**
  61661. * Set a vec2 array in the shader from a number array.
  61662. * @param name Define the name of the uniform as defined in the shader
  61663. * @param value Define the value to give to the uniform
  61664. * @return the material itself allowing "fluent" like uniform updates
  61665. */
  61666. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61667. this._checkUniform(name);
  61668. this._vectors2Arrays[name] = value;
  61669. return this;
  61670. };
  61671. /**
  61672. * Set a vec3 array in the shader from a number array.
  61673. * @param name Define the name of the uniform as defined in the shader
  61674. * @param value Define the value to give to the uniform
  61675. * @return the material itself allowing "fluent" like uniform updates
  61676. */
  61677. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61678. this._checkUniform(name);
  61679. this._vectors3Arrays[name] = value;
  61680. return this;
  61681. };
  61682. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61683. if (!mesh) {
  61684. return true;
  61685. }
  61686. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61687. return false;
  61688. }
  61689. return false;
  61690. };
  61691. /**
  61692. * Checks if the material is ready to render the requested mesh
  61693. * @param mesh Define the mesh to render
  61694. * @param useInstances Define whether or not the material is used with instances
  61695. * @returns true if ready, otherwise false
  61696. */
  61697. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61698. var scene = this.getScene();
  61699. var engine = scene.getEngine();
  61700. if (!this.checkReadyOnEveryCall) {
  61701. if (this._renderId === scene.getRenderId()) {
  61702. if (this._checkCache(scene, mesh, useInstances)) {
  61703. return true;
  61704. }
  61705. }
  61706. }
  61707. // Instances
  61708. var defines = [];
  61709. var attribs = [];
  61710. var fallbacks = new BABYLON.EffectFallbacks();
  61711. for (var index = 0; index < this._options.defines.length; index++) {
  61712. defines.push(this._options.defines[index]);
  61713. }
  61714. for (var index = 0; index < this._options.attributes.length; index++) {
  61715. attribs.push(this._options.attributes[index]);
  61716. }
  61717. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61718. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61719. defines.push("#define VERTEXCOLOR");
  61720. }
  61721. if (useInstances) {
  61722. defines.push("#define INSTANCES");
  61723. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61724. }
  61725. // Bones
  61726. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61729. if (mesh.numBoneInfluencers > 4) {
  61730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61732. }
  61733. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61734. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61735. fallbacks.addCPUSkinningFallback(0, mesh);
  61736. if (this._options.uniforms.indexOf("mBones") === -1) {
  61737. this._options.uniforms.push("mBones");
  61738. }
  61739. }
  61740. else {
  61741. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61742. }
  61743. // Textures
  61744. for (var name in this._textures) {
  61745. if (!this._textures[name].isReady()) {
  61746. return false;
  61747. }
  61748. }
  61749. // Alpha test
  61750. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61751. defines.push("#define ALPHATEST");
  61752. }
  61753. var previousEffect = this._effect;
  61754. var join = defines.join("\n");
  61755. this._effect = engine.createEffect(this._shaderPath, {
  61756. attributes: attribs,
  61757. uniformsNames: this._options.uniforms,
  61758. uniformBuffersNames: this._options.uniformBuffers,
  61759. samplers: this._options.samplers,
  61760. defines: join,
  61761. fallbacks: fallbacks,
  61762. onCompiled: this.onCompiled,
  61763. onError: this.onError
  61764. }, engine);
  61765. if (!this._effect.isReady()) {
  61766. return false;
  61767. }
  61768. if (previousEffect !== this._effect) {
  61769. scene.resetCachedMaterial();
  61770. }
  61771. this._renderId = scene.getRenderId();
  61772. return true;
  61773. };
  61774. /**
  61775. * Binds the world matrix to the material
  61776. * @param world defines the world transformation matrix
  61777. */
  61778. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61779. var scene = this.getScene();
  61780. if (!this._effect) {
  61781. return;
  61782. }
  61783. if (this._options.uniforms.indexOf("world") !== -1) {
  61784. this._effect.setMatrix("world", world);
  61785. }
  61786. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61787. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61788. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61789. }
  61790. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61791. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  61792. }
  61793. };
  61794. /**
  61795. * Binds the material to the mesh
  61796. * @param world defines the world transformation matrix
  61797. * @param mesh defines the mesh to bind the material to
  61798. */
  61799. ShaderMaterial.prototype.bind = function (world, mesh) {
  61800. // Std values
  61801. this.bindOnlyWorldMatrix(world);
  61802. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  61803. if (this._options.uniforms.indexOf("view") !== -1) {
  61804. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  61805. }
  61806. if (this._options.uniforms.indexOf("projection") !== -1) {
  61807. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  61808. }
  61809. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  61810. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  61811. }
  61812. // Bones
  61813. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61814. var name;
  61815. // Texture
  61816. for (name in this._textures) {
  61817. this._effect.setTexture(name, this._textures[name]);
  61818. }
  61819. // Texture arrays
  61820. for (name in this._textureArrays) {
  61821. this._effect.setTextureArray(name, this._textureArrays[name]);
  61822. }
  61823. // Int
  61824. for (name in this._ints) {
  61825. this._effect.setInt(name, this._ints[name]);
  61826. }
  61827. // Float
  61828. for (name in this._floats) {
  61829. this._effect.setFloat(name, this._floats[name]);
  61830. }
  61831. // Floats
  61832. for (name in this._floatsArrays) {
  61833. this._effect.setArray(name, this._floatsArrays[name]);
  61834. }
  61835. // Color3
  61836. for (name in this._colors3) {
  61837. this._effect.setColor3(name, this._colors3[name]);
  61838. }
  61839. for (name in this._colors3Arrays) {
  61840. this._effect.setArray3(name, this._colors3Arrays[name]);
  61841. }
  61842. // Color4
  61843. for (name in this._colors4) {
  61844. var color = this._colors4[name];
  61845. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61846. }
  61847. // Vector2
  61848. for (name in this._vectors2) {
  61849. this._effect.setVector2(name, this._vectors2[name]);
  61850. }
  61851. // Vector3
  61852. for (name in this._vectors3) {
  61853. this._effect.setVector3(name, this._vectors3[name]);
  61854. }
  61855. // Vector4
  61856. for (name in this._vectors4) {
  61857. this._effect.setVector4(name, this._vectors4[name]);
  61858. }
  61859. // Matrix
  61860. for (name in this._matrices) {
  61861. this._effect.setMatrix(name, this._matrices[name]);
  61862. }
  61863. // Matrix 3x3
  61864. for (name in this._matrices3x3) {
  61865. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  61866. }
  61867. // Matrix 2x2
  61868. for (name in this._matrices2x2) {
  61869. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  61870. }
  61871. // Vector2Array
  61872. for (name in this._vectors2Arrays) {
  61873. this._effect.setArray2(name, this._vectors2Arrays[name]);
  61874. }
  61875. // Vector3Array
  61876. for (name in this._vectors3Arrays) {
  61877. this._effect.setArray3(name, this._vectors3Arrays[name]);
  61878. }
  61879. }
  61880. this._afterBind(mesh);
  61881. };
  61882. /**
  61883. * Gets the active textures from the material
  61884. * @returns an array of textures
  61885. */
  61886. ShaderMaterial.prototype.getActiveTextures = function () {
  61887. var activeTextures = _super.prototype.getActiveTextures.call(this);
  61888. for (var name in this._textures) {
  61889. activeTextures.push(this._textures[name]);
  61890. }
  61891. for (var name in this._textureArrays) {
  61892. var array = this._textureArrays[name];
  61893. for (var index = 0; index < array.length; index++) {
  61894. activeTextures.push(array[index]);
  61895. }
  61896. }
  61897. return activeTextures;
  61898. };
  61899. /**
  61900. * Specifies if the material uses a texture
  61901. * @param texture defines the texture to check against the material
  61902. * @returns a boolean specifying if the material uses the texture
  61903. */
  61904. ShaderMaterial.prototype.hasTexture = function (texture) {
  61905. if (_super.prototype.hasTexture.call(this, texture)) {
  61906. return true;
  61907. }
  61908. for (var name in this._textures) {
  61909. if (this._textures[name] === texture) {
  61910. return true;
  61911. }
  61912. }
  61913. for (var name in this._textureArrays) {
  61914. var array = this._textureArrays[name];
  61915. for (var index = 0; index < array.length; index++) {
  61916. if (array[index] === texture) {
  61917. return true;
  61918. }
  61919. }
  61920. }
  61921. return false;
  61922. };
  61923. /**
  61924. * Makes a duplicate of the material, and gives it a new name
  61925. * @param name defines the new name for the duplicated material
  61926. * @returns the cloned material
  61927. */
  61928. ShaderMaterial.prototype.clone = function (name) {
  61929. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61930. return newShaderMaterial;
  61931. };
  61932. /**
  61933. * Disposes the material
  61934. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  61935. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  61936. */
  61937. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61938. if (forceDisposeTextures) {
  61939. var name;
  61940. for (name in this._textures) {
  61941. this._textures[name].dispose();
  61942. }
  61943. for (name in this._textureArrays) {
  61944. var array = this._textureArrays[name];
  61945. for (var index = 0; index < array.length; index++) {
  61946. array[index].dispose();
  61947. }
  61948. }
  61949. }
  61950. this._textures = {};
  61951. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61952. };
  61953. /**
  61954. * Serializes this material in a JSON representation
  61955. * @returns the serialized material object
  61956. */
  61957. ShaderMaterial.prototype.serialize = function () {
  61958. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61959. serializationObject.customType = "BABYLON.ShaderMaterial";
  61960. serializationObject.options = this._options;
  61961. serializationObject.shaderPath = this._shaderPath;
  61962. var name;
  61963. // Texture
  61964. serializationObject.textures = {};
  61965. for (name in this._textures) {
  61966. serializationObject.textures[name] = this._textures[name].serialize();
  61967. }
  61968. // Texture arrays
  61969. serializationObject.textureArrays = {};
  61970. for (name in this._textureArrays) {
  61971. serializationObject.textureArrays[name] = [];
  61972. var array = this._textureArrays[name];
  61973. for (var index = 0; index < array.length; index++) {
  61974. serializationObject.textureArrays[name].push(array[index].serialize());
  61975. }
  61976. }
  61977. // Float
  61978. serializationObject.floats = {};
  61979. for (name in this._floats) {
  61980. serializationObject.floats[name] = this._floats[name];
  61981. }
  61982. // Float s
  61983. serializationObject.FloatArrays = {};
  61984. for (name in this._floatsArrays) {
  61985. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61986. }
  61987. // Color3
  61988. serializationObject.colors3 = {};
  61989. for (name in this._colors3) {
  61990. serializationObject.colors3[name] = this._colors3[name].asArray();
  61991. }
  61992. // Color3 array
  61993. serializationObject.colors3Arrays = {};
  61994. for (name in this._colors3Arrays) {
  61995. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61996. }
  61997. // Color4
  61998. serializationObject.colors4 = {};
  61999. for (name in this._colors4) {
  62000. serializationObject.colors4[name] = this._colors4[name].asArray();
  62001. }
  62002. // Vector2
  62003. serializationObject.vectors2 = {};
  62004. for (name in this._vectors2) {
  62005. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62006. }
  62007. // Vector3
  62008. serializationObject.vectors3 = {};
  62009. for (name in this._vectors3) {
  62010. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62011. }
  62012. // Vector4
  62013. serializationObject.vectors4 = {};
  62014. for (name in this._vectors4) {
  62015. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62016. }
  62017. // Matrix
  62018. serializationObject.matrices = {};
  62019. for (name in this._matrices) {
  62020. serializationObject.matrices[name] = this._matrices[name].asArray();
  62021. }
  62022. // Matrix 3x3
  62023. serializationObject.matrices3x3 = {};
  62024. for (name in this._matrices3x3) {
  62025. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62026. }
  62027. // Matrix 2x2
  62028. serializationObject.matrices2x2 = {};
  62029. for (name in this._matrices2x2) {
  62030. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62031. }
  62032. // Vector2Array
  62033. serializationObject.vectors2Arrays = {};
  62034. for (name in this._vectors2Arrays) {
  62035. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62036. }
  62037. // Vector3Array
  62038. serializationObject.vectors3Arrays = {};
  62039. for (name in this._vectors3Arrays) {
  62040. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62041. }
  62042. return serializationObject;
  62043. };
  62044. /**
  62045. * Creates a shader material from parsed shader material data
  62046. * @param source defines the JSON represnetation of the material
  62047. * @param scene defines the hosting scene
  62048. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62049. * @returns a new material
  62050. */
  62051. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62052. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62053. var name;
  62054. // Texture
  62055. for (name in source.textures) {
  62056. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62057. }
  62058. // Texture arrays
  62059. for (name in source.textureArrays) {
  62060. var array = source.textureArrays[name];
  62061. var textureArray = new Array();
  62062. for (var index = 0; index < array.length; index++) {
  62063. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62064. }
  62065. material.setTextureArray(name, textureArray);
  62066. }
  62067. // Float
  62068. for (name in source.floats) {
  62069. material.setFloat(name, source.floats[name]);
  62070. }
  62071. // Float s
  62072. for (name in source.floatsArrays) {
  62073. material.setFloats(name, source.floatsArrays[name]);
  62074. }
  62075. // Color3
  62076. for (name in source.colors3) {
  62077. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62078. }
  62079. // Color3 arrays
  62080. for (name in source.colors3Arrays) {
  62081. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62082. if (i % 3 === 0) {
  62083. arr.push([num]);
  62084. }
  62085. else {
  62086. arr[arr.length - 1].push(num);
  62087. }
  62088. return arr;
  62089. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62090. material.setColor3Array(name, colors);
  62091. }
  62092. // Color4
  62093. for (name in source.colors4) {
  62094. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62095. }
  62096. // Vector2
  62097. for (name in source.vectors2) {
  62098. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62099. }
  62100. // Vector3
  62101. for (name in source.vectors3) {
  62102. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62103. }
  62104. // Vector4
  62105. for (name in source.vectors4) {
  62106. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62107. }
  62108. // Matrix
  62109. for (name in source.matrices) {
  62110. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62111. }
  62112. // Matrix 3x3
  62113. for (name in source.matrices3x3) {
  62114. material.setMatrix3x3(name, source.matrices3x3[name]);
  62115. }
  62116. // Matrix 2x2
  62117. for (name in source.matrices2x2) {
  62118. material.setMatrix2x2(name, source.matrices2x2[name]);
  62119. }
  62120. // Vector2Array
  62121. for (name in source.vectors2Arrays) {
  62122. material.setArray2(name, source.vectors2Arrays[name]);
  62123. }
  62124. // Vector3Array
  62125. for (name in source.vectors3Arrays) {
  62126. material.setArray3(name, source.vectors3Arrays[name]);
  62127. }
  62128. return material;
  62129. };
  62130. return ShaderMaterial;
  62131. }(BABYLON.Material));
  62132. BABYLON.ShaderMaterial = ShaderMaterial;
  62133. })(BABYLON || (BABYLON = {}));
  62134. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62135. var BABYLON;
  62136. (function (BABYLON) {
  62137. var GroundMesh = /** @class */ (function (_super) {
  62138. __extends(GroundMesh, _super);
  62139. function GroundMesh(name, scene) {
  62140. var _this = _super.call(this, name, scene) || this;
  62141. _this.generateOctree = false;
  62142. return _this;
  62143. }
  62144. GroundMesh.prototype.getClassName = function () {
  62145. return "GroundMesh";
  62146. };
  62147. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62148. get: function () {
  62149. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62150. },
  62151. enumerable: true,
  62152. configurable: true
  62153. });
  62154. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62155. get: function () {
  62156. return this._subdivisionsX;
  62157. },
  62158. enumerable: true,
  62159. configurable: true
  62160. });
  62161. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62162. get: function () {
  62163. return this._subdivisionsY;
  62164. },
  62165. enumerable: true,
  62166. configurable: true
  62167. });
  62168. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62169. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62170. this._subdivisionsX = chunksCount;
  62171. this._subdivisionsY = chunksCount;
  62172. this.subdivide(chunksCount);
  62173. // Call the octree system optimization if it is defined.
  62174. var thisAsAny = this;
  62175. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62176. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62177. }
  62178. };
  62179. /**
  62180. * Returns a height (y) value in the Worl system :
  62181. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62182. * Returns the ground y position if (x, z) are outside the ground surface.
  62183. */
  62184. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62185. var world = this.getWorldMatrix();
  62186. var invMat = BABYLON.Tmp.Matrix[5];
  62187. world.invertToRef(invMat);
  62188. var tmpVect = BABYLON.Tmp.Vector3[8];
  62189. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62190. x = tmpVect.x;
  62191. z = tmpVect.z;
  62192. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62193. return this.position.y;
  62194. }
  62195. if (!this._heightQuads || this._heightQuads.length == 0) {
  62196. this._initHeightQuads();
  62197. this._computeHeightQuads();
  62198. }
  62199. var facet = this._getFacetAt(x, z);
  62200. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62201. // return y in the World system
  62202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62203. return tmpVect.y;
  62204. };
  62205. /**
  62206. * Returns a normalized vector (Vector3) orthogonal to the ground
  62207. * at the ground coordinates (x, z) expressed in the World system.
  62208. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62209. */
  62210. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62211. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62212. this.getNormalAtCoordinatesToRef(x, z, normal);
  62213. return normal;
  62214. };
  62215. /**
  62216. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62217. * at the ground coordinates (x, z) expressed in the World system.
  62218. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62219. * Returns the GroundMesh.
  62220. */
  62221. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62222. var world = this.getWorldMatrix();
  62223. var tmpMat = BABYLON.Tmp.Matrix[5];
  62224. world.invertToRef(tmpMat);
  62225. var tmpVect = BABYLON.Tmp.Vector3[8];
  62226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62227. x = tmpVect.x;
  62228. z = tmpVect.z;
  62229. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62230. return this;
  62231. }
  62232. if (!this._heightQuads || this._heightQuads.length == 0) {
  62233. this._initHeightQuads();
  62234. this._computeHeightQuads();
  62235. }
  62236. var facet = this._getFacetAt(x, z);
  62237. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62238. return this;
  62239. };
  62240. /**
  62241. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62242. * if the ground has been updated.
  62243. * This can be used in the render loop.
  62244. * Returns the GroundMesh.
  62245. */
  62246. GroundMesh.prototype.updateCoordinateHeights = function () {
  62247. if (!this._heightQuads || this._heightQuads.length == 0) {
  62248. this._initHeightQuads();
  62249. }
  62250. this._computeHeightQuads();
  62251. return this;
  62252. };
  62253. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62254. GroundMesh.prototype._getFacetAt = function (x, z) {
  62255. // retrieve col and row from x, z coordinates in the ground local system
  62256. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62257. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62258. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62259. var facet;
  62260. if (z < quad.slope.x * x + quad.slope.y) {
  62261. facet = quad.facet1;
  62262. }
  62263. else {
  62264. facet = quad.facet2;
  62265. }
  62266. return facet;
  62267. };
  62268. // Creates and populates the heightMap array with "facet" elements :
  62269. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62270. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62271. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62272. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62273. // Returns the GroundMesh.
  62274. GroundMesh.prototype._initHeightQuads = function () {
  62275. var subdivisionsX = this._subdivisionsX;
  62276. var subdivisionsY = this._subdivisionsY;
  62277. this._heightQuads = new Array();
  62278. for (var row = 0; row < subdivisionsY; row++) {
  62279. for (var col = 0; col < subdivisionsX; col++) {
  62280. 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) };
  62281. this._heightQuads[row * subdivisionsX + col] = quad;
  62282. }
  62283. }
  62284. return this;
  62285. };
  62286. // Compute each quad element values and update the the heightMap array :
  62287. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62288. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62289. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62290. // Returns the GroundMesh.
  62291. GroundMesh.prototype._computeHeightQuads = function () {
  62292. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62293. if (!positions) {
  62294. return this;
  62295. }
  62296. var v1 = BABYLON.Tmp.Vector3[3];
  62297. var v2 = BABYLON.Tmp.Vector3[2];
  62298. var v3 = BABYLON.Tmp.Vector3[1];
  62299. var v4 = BABYLON.Tmp.Vector3[0];
  62300. var v1v2 = BABYLON.Tmp.Vector3[4];
  62301. var v1v3 = BABYLON.Tmp.Vector3[5];
  62302. var v1v4 = BABYLON.Tmp.Vector3[6];
  62303. var norm1 = BABYLON.Tmp.Vector3[7];
  62304. var norm2 = BABYLON.Tmp.Vector3[8];
  62305. var i = 0;
  62306. var j = 0;
  62307. var k = 0;
  62308. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62309. var h = 0;
  62310. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62311. var d2 = 0;
  62312. var subdivisionsX = this._subdivisionsX;
  62313. var subdivisionsY = this._subdivisionsY;
  62314. for (var row = 0; row < subdivisionsY; row++) {
  62315. for (var col = 0; col < subdivisionsX; col++) {
  62316. i = col * 3;
  62317. j = row * (subdivisionsX + 1) * 3;
  62318. k = (row + 1) * (subdivisionsX + 1) * 3;
  62319. v1.x = positions[j + i];
  62320. v1.y = positions[j + i + 1];
  62321. v1.z = positions[j + i + 2];
  62322. v2.x = positions[j + i + 3];
  62323. v2.y = positions[j + i + 4];
  62324. v2.z = positions[j + i + 5];
  62325. v3.x = positions[k + i];
  62326. v3.y = positions[k + i + 1];
  62327. v3.z = positions[k + i + 2];
  62328. v4.x = positions[k + i + 3];
  62329. v4.y = positions[k + i + 4];
  62330. v4.z = positions[k + i + 5];
  62331. // 2D slope V1V4
  62332. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62333. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62334. // facet equations :
  62335. // we compute each facet normal vector
  62336. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62337. // we compute the value d by applying the equation to v1 which belongs to the plane
  62338. // then we store the facet equation in a Vector4
  62339. v2.subtractToRef(v1, v1v2);
  62340. v3.subtractToRef(v1, v1v3);
  62341. v4.subtractToRef(v1, v1v4);
  62342. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62343. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62344. norm1.normalize();
  62345. norm2.normalize();
  62346. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62347. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62348. var quad = this._heightQuads[row * subdivisionsX + col];
  62349. quad.slope.copyFromFloats(cd, h);
  62350. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62351. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62352. }
  62353. }
  62354. return this;
  62355. };
  62356. GroundMesh.prototype.serialize = function (serializationObject) {
  62357. _super.prototype.serialize.call(this, serializationObject);
  62358. serializationObject.subdivisionsX = this._subdivisionsX;
  62359. serializationObject.subdivisionsY = this._subdivisionsY;
  62360. serializationObject.minX = this._minX;
  62361. serializationObject.maxX = this._maxX;
  62362. serializationObject.minZ = this._minZ;
  62363. serializationObject.maxZ = this._maxZ;
  62364. serializationObject.width = this._width;
  62365. serializationObject.height = this._height;
  62366. };
  62367. GroundMesh.Parse = function (parsedMesh, scene) {
  62368. var result = new GroundMesh(parsedMesh.name, scene);
  62369. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62370. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62371. result._minX = parsedMesh.minX;
  62372. result._maxX = parsedMesh.maxX;
  62373. result._minZ = parsedMesh.minZ;
  62374. result._maxZ = parsedMesh.maxZ;
  62375. result._width = parsedMesh.width;
  62376. result._height = parsedMesh.height;
  62377. return result;
  62378. };
  62379. return GroundMesh;
  62380. }(BABYLON.Mesh));
  62381. BABYLON.GroundMesh = GroundMesh;
  62382. })(BABYLON || (BABYLON = {}));
  62383. //# sourceMappingURL=babylon.groundMesh.js.map
  62384. var BABYLON;
  62385. (function (BABYLON) {
  62386. /**
  62387. * Creates an instance based on a source mesh.
  62388. */
  62389. var InstancedMesh = /** @class */ (function (_super) {
  62390. __extends(InstancedMesh, _super);
  62391. function InstancedMesh(name, source) {
  62392. var _this = _super.call(this, name, source.getScene()) || this;
  62393. source.instances.push(_this);
  62394. _this._sourceMesh = source;
  62395. _this.position.copyFrom(source.position);
  62396. _this.rotation.copyFrom(source.rotation);
  62397. _this.scaling.copyFrom(source.scaling);
  62398. if (source.rotationQuaternion) {
  62399. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62400. }
  62401. _this.infiniteDistance = source.infiniteDistance;
  62402. _this.setPivotMatrix(source.getPivotMatrix());
  62403. _this.refreshBoundingInfo();
  62404. _this._syncSubMeshes();
  62405. return _this;
  62406. }
  62407. /**
  62408. * Returns the string "InstancedMesh".
  62409. */
  62410. InstancedMesh.prototype.getClassName = function () {
  62411. return "InstancedMesh";
  62412. };
  62413. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62414. // Methods
  62415. get: function () {
  62416. return this._sourceMesh.receiveShadows;
  62417. },
  62418. enumerable: true,
  62419. configurable: true
  62420. });
  62421. Object.defineProperty(InstancedMesh.prototype, "material", {
  62422. get: function () {
  62423. return this._sourceMesh.material;
  62424. },
  62425. enumerable: true,
  62426. configurable: true
  62427. });
  62428. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62429. get: function () {
  62430. return this._sourceMesh.visibility;
  62431. },
  62432. enumerable: true,
  62433. configurable: true
  62434. });
  62435. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62436. get: function () {
  62437. return this._sourceMesh.skeleton;
  62438. },
  62439. enumerable: true,
  62440. configurable: true
  62441. });
  62442. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62443. get: function () {
  62444. return this._sourceMesh.renderingGroupId;
  62445. },
  62446. set: function (value) {
  62447. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62448. return;
  62449. }
  62450. //no-op with warning
  62451. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62452. },
  62453. enumerable: true,
  62454. configurable: true
  62455. });
  62456. /**
  62457. * Returns the total number of vertices (integer).
  62458. */
  62459. InstancedMesh.prototype.getTotalVertices = function () {
  62460. return this._sourceMesh.getTotalVertices();
  62461. };
  62462. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62463. get: function () {
  62464. return this._sourceMesh;
  62465. },
  62466. enumerable: true,
  62467. configurable: true
  62468. });
  62469. /**
  62470. * Is this node ready to be used/rendered
  62471. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62472. * @return {boolean} is it ready
  62473. */
  62474. InstancedMesh.prototype.isReady = function (completeCheck) {
  62475. if (completeCheck === void 0) { completeCheck = false; }
  62476. return this._sourceMesh.isReady(completeCheck, true);
  62477. };
  62478. /**
  62479. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62480. */
  62481. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62482. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62483. };
  62484. /**
  62485. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62486. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62487. * The `data` are either a numeric array either a Float32Array.
  62488. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62489. * 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).
  62490. * Note that a new underlying VertexBuffer object is created each call.
  62491. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62492. *
  62493. * Possible `kind` values :
  62494. * - BABYLON.VertexBuffer.PositionKind
  62495. * - BABYLON.VertexBuffer.UVKind
  62496. * - BABYLON.VertexBuffer.UV2Kind
  62497. * - BABYLON.VertexBuffer.UV3Kind
  62498. * - BABYLON.VertexBuffer.UV4Kind
  62499. * - BABYLON.VertexBuffer.UV5Kind
  62500. * - BABYLON.VertexBuffer.UV6Kind
  62501. * - BABYLON.VertexBuffer.ColorKind
  62502. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62503. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62504. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62505. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62506. *
  62507. * Returns the Mesh.
  62508. */
  62509. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62510. if (this.sourceMesh) {
  62511. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62512. }
  62513. return this.sourceMesh;
  62514. };
  62515. /**
  62516. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62517. * If the mesh has no geometry, it is simply returned as it is.
  62518. * The `data` are either a numeric array either a Float32Array.
  62519. * No new underlying VertexBuffer object is created.
  62520. * 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.
  62521. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62522. *
  62523. * Possible `kind` values :
  62524. * - BABYLON.VertexBuffer.PositionKind
  62525. * - BABYLON.VertexBuffer.UVKind
  62526. * - BABYLON.VertexBuffer.UV2Kind
  62527. * - BABYLON.VertexBuffer.UV3Kind
  62528. * - BABYLON.VertexBuffer.UV4Kind
  62529. * - BABYLON.VertexBuffer.UV5Kind
  62530. * - BABYLON.VertexBuffer.UV6Kind
  62531. * - BABYLON.VertexBuffer.ColorKind
  62532. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62533. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62534. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62535. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62536. *
  62537. * Returns the Mesh.
  62538. */
  62539. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62540. if (this.sourceMesh) {
  62541. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62542. }
  62543. return this.sourceMesh;
  62544. };
  62545. /**
  62546. * Sets the mesh indices.
  62547. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62548. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62549. * This method creates a new index buffer each call.
  62550. * Returns the Mesh.
  62551. */
  62552. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62553. if (totalVertices === void 0) { totalVertices = null; }
  62554. if (this.sourceMesh) {
  62555. this.sourceMesh.setIndices(indices, totalVertices);
  62556. }
  62557. return this.sourceMesh;
  62558. };
  62559. /**
  62560. * Boolean : True if the mesh owns the requested kind of data.
  62561. */
  62562. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62563. return this._sourceMesh.isVerticesDataPresent(kind);
  62564. };
  62565. /**
  62566. * Returns an array of indices (IndicesArray).
  62567. */
  62568. InstancedMesh.prototype.getIndices = function () {
  62569. return this._sourceMesh.getIndices();
  62570. };
  62571. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62572. get: function () {
  62573. return this._sourceMesh._positions;
  62574. },
  62575. enumerable: true,
  62576. configurable: true
  62577. });
  62578. /**
  62579. * Sets a new updated BoundingInfo to the mesh.
  62580. * Returns the mesh.
  62581. */
  62582. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62583. var meshBB = this._sourceMesh.getBoundingInfo();
  62584. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62585. this._updateBoundingInfo();
  62586. return this;
  62587. };
  62588. /** @hidden */
  62589. InstancedMesh.prototype._preActivate = function () {
  62590. if (this._currentLOD) {
  62591. this._currentLOD._preActivate();
  62592. }
  62593. return this;
  62594. };
  62595. /** @hidden */
  62596. InstancedMesh.prototype._activate = function (renderId) {
  62597. if (this._currentLOD) {
  62598. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62599. }
  62600. return this;
  62601. };
  62602. /**
  62603. * Returns the current associated LOD AbstractMesh.
  62604. */
  62605. InstancedMesh.prototype.getLOD = function (camera) {
  62606. if (!camera) {
  62607. return this;
  62608. }
  62609. var boundingInfo = this.getBoundingInfo();
  62610. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62611. if (this._currentLOD === this.sourceMesh) {
  62612. return this;
  62613. }
  62614. return this._currentLOD;
  62615. };
  62616. /** @hidden */
  62617. InstancedMesh.prototype._syncSubMeshes = function () {
  62618. this.releaseSubMeshes();
  62619. if (this._sourceMesh.subMeshes) {
  62620. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62621. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62622. }
  62623. }
  62624. return this;
  62625. };
  62626. /** @hidden */
  62627. InstancedMesh.prototype._generatePointsArray = function () {
  62628. return this._sourceMesh._generatePointsArray();
  62629. };
  62630. /**
  62631. * Creates a new InstancedMesh from the current mesh.
  62632. * - name (string) : the cloned mesh name
  62633. * - newParent (optional Node) : the optional Node to parent the clone to.
  62634. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62635. *
  62636. * Returns the clone.
  62637. */
  62638. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62639. var result = this._sourceMesh.createInstance(name);
  62640. // Deep copy
  62641. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62642. // Bounding info
  62643. this.refreshBoundingInfo();
  62644. // Parent
  62645. if (newParent) {
  62646. result.parent = newParent;
  62647. }
  62648. if (!doNotCloneChildren) {
  62649. // Children
  62650. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62651. var mesh = this.getScene().meshes[index];
  62652. if (mesh.parent === this) {
  62653. mesh.clone(mesh.name, result);
  62654. }
  62655. }
  62656. }
  62657. result.computeWorldMatrix(true);
  62658. return result;
  62659. };
  62660. /**
  62661. * Disposes the InstancedMesh.
  62662. * Returns nothing.
  62663. */
  62664. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62665. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62666. // Remove from mesh
  62667. var index = this._sourceMesh.instances.indexOf(this);
  62668. this._sourceMesh.instances.splice(index, 1);
  62669. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62670. };
  62671. return InstancedMesh;
  62672. }(BABYLON.AbstractMesh));
  62673. BABYLON.InstancedMesh = InstancedMesh;
  62674. })(BABYLON || (BABYLON = {}));
  62675. //# sourceMappingURL=babylon.instancedMesh.js.map
  62676. var BABYLON;
  62677. (function (BABYLON) {
  62678. var LinesMesh = /** @class */ (function (_super) {
  62679. __extends(LinesMesh, _super);
  62680. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62681. if (scene === void 0) { scene = null; }
  62682. if (parent === void 0) { parent = null; }
  62683. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62684. _this.useVertexColor = useVertexColor;
  62685. _this.useVertexAlpha = useVertexAlpha;
  62686. _this.color = new BABYLON.Color3(1, 1, 1);
  62687. _this.alpha = 1;
  62688. if (source) {
  62689. _this.color = source.color.clone();
  62690. _this.alpha = source.alpha;
  62691. _this.useVertexColor = source.useVertexColor;
  62692. _this.useVertexAlpha = source.useVertexAlpha;
  62693. }
  62694. _this._intersectionThreshold = 0.1;
  62695. var defines = [];
  62696. var options = {
  62697. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62698. uniforms: ["world", "viewProjection"],
  62699. needAlphaBlending: true,
  62700. defines: defines
  62701. };
  62702. if (useVertexAlpha === false) {
  62703. options.needAlphaBlending = false;
  62704. }
  62705. if (!useVertexColor) {
  62706. options.uniforms.push("color");
  62707. }
  62708. else {
  62709. options.defines.push("#define VERTEXCOLOR");
  62710. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62711. }
  62712. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62713. return _this;
  62714. }
  62715. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62716. /**
  62717. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62718. * This margin is expressed in world space coordinates, so its value may vary.
  62719. * Default value is 0.1
  62720. * @returns the intersection Threshold value.
  62721. */
  62722. get: function () {
  62723. return this._intersectionThreshold;
  62724. },
  62725. /**
  62726. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62727. * This margin is expressed in world space coordinates, so its value may vary.
  62728. * @param value the new threshold to apply
  62729. */
  62730. set: function (value) {
  62731. if (this._intersectionThreshold === value) {
  62732. return;
  62733. }
  62734. this._intersectionThreshold = value;
  62735. if (this.geometry) {
  62736. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62737. }
  62738. },
  62739. enumerable: true,
  62740. configurable: true
  62741. });
  62742. /**
  62743. * Returns the string "LineMesh"
  62744. */
  62745. LinesMesh.prototype.getClassName = function () {
  62746. return "LinesMesh";
  62747. };
  62748. Object.defineProperty(LinesMesh.prototype, "material", {
  62749. /**
  62750. * @hidden
  62751. */
  62752. get: function () {
  62753. return this._colorShader;
  62754. },
  62755. /**
  62756. * @hidden
  62757. */
  62758. set: function (value) {
  62759. // Do nothing
  62760. },
  62761. enumerable: true,
  62762. configurable: true
  62763. });
  62764. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62765. /**
  62766. * @hidden
  62767. */
  62768. get: function () {
  62769. return false;
  62770. },
  62771. enumerable: true,
  62772. configurable: true
  62773. });
  62774. /** @hidden */
  62775. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62776. if (!this._geometry) {
  62777. return this;
  62778. }
  62779. // VBOs
  62780. this._geometry._bind(this._colorShader.getEffect());
  62781. // Color
  62782. if (!this.useVertexColor) {
  62783. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62784. }
  62785. return this;
  62786. };
  62787. /** @hidden */
  62788. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62789. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62790. return this;
  62791. }
  62792. var engine = this.getScene().getEngine();
  62793. // Draw order
  62794. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  62795. return this;
  62796. };
  62797. LinesMesh.prototype.dispose = function (doNotRecurse) {
  62798. this._colorShader.dispose();
  62799. _super.prototype.dispose.call(this, doNotRecurse);
  62800. };
  62801. /**
  62802. * Returns a new LineMesh object cloned from the current one.
  62803. */
  62804. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62805. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  62806. };
  62807. return LinesMesh;
  62808. }(BABYLON.Mesh));
  62809. BABYLON.LinesMesh = LinesMesh;
  62810. })(BABYLON || (BABYLON = {}));
  62811. //# sourceMappingURL=babylon.linesMesh.js.map
  62812. var BABYLON;
  62813. (function (BABYLON) {
  62814. /**
  62815. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62816. * The underlying implementation relies on an associative array to ensure the best performances.
  62817. * The value can be anything including 'null' but except 'undefined'
  62818. */
  62819. var StringDictionary = /** @class */ (function () {
  62820. function StringDictionary() {
  62821. this._count = 0;
  62822. this._data = {};
  62823. }
  62824. /**
  62825. * This will clear this dictionary and copy the content from the 'source' one.
  62826. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62827. * @param source the dictionary to take the content from and copy to this dictionary
  62828. */
  62829. StringDictionary.prototype.copyFrom = function (source) {
  62830. var _this = this;
  62831. this.clear();
  62832. source.forEach(function (t, v) { return _this.add(t, v); });
  62833. };
  62834. /**
  62835. * Get a value based from its key
  62836. * @param key the given key to get the matching value from
  62837. * @return the value if found, otherwise undefined is returned
  62838. */
  62839. StringDictionary.prototype.get = function (key) {
  62840. var val = this._data[key];
  62841. if (val !== undefined) {
  62842. return val;
  62843. }
  62844. return undefined;
  62845. };
  62846. /**
  62847. * Get a value from its key or add it if it doesn't exist.
  62848. * This method will ensure you that a given key/data will be present in the dictionary.
  62849. * @param key the given key to get the matching value from
  62850. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62851. * The factory will only be invoked if there's no data for the given key.
  62852. * @return the value corresponding to the key.
  62853. */
  62854. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62855. var val = this.get(key);
  62856. if (val !== undefined) {
  62857. return val;
  62858. }
  62859. val = factory(key);
  62860. if (val) {
  62861. this.add(key, val);
  62862. }
  62863. return val;
  62864. };
  62865. /**
  62866. * Get a value from its key if present in the dictionary otherwise add it
  62867. * @param key the key to get the value from
  62868. * @param val if there's no such key/value pair in the dictionary add it with this value
  62869. * @return the value corresponding to the key
  62870. */
  62871. StringDictionary.prototype.getOrAdd = function (key, val) {
  62872. var curVal = this.get(key);
  62873. if (curVal !== undefined) {
  62874. return curVal;
  62875. }
  62876. this.add(key, val);
  62877. return val;
  62878. };
  62879. /**
  62880. * Check if there's a given key in the dictionary
  62881. * @param key the key to check for
  62882. * @return true if the key is present, false otherwise
  62883. */
  62884. StringDictionary.prototype.contains = function (key) {
  62885. return this._data[key] !== undefined;
  62886. };
  62887. /**
  62888. * Add a new key and its corresponding value
  62889. * @param key the key to add
  62890. * @param value the value corresponding to the key
  62891. * @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
  62892. */
  62893. StringDictionary.prototype.add = function (key, value) {
  62894. if (this._data[key] !== undefined) {
  62895. return false;
  62896. }
  62897. this._data[key] = value;
  62898. ++this._count;
  62899. return true;
  62900. };
  62901. StringDictionary.prototype.set = function (key, value) {
  62902. if (this._data[key] === undefined) {
  62903. return false;
  62904. }
  62905. this._data[key] = value;
  62906. return true;
  62907. };
  62908. /**
  62909. * Get the element of the given key and remove it from the dictionary
  62910. * @param key
  62911. */
  62912. StringDictionary.prototype.getAndRemove = function (key) {
  62913. var val = this.get(key);
  62914. if (val !== undefined) {
  62915. delete this._data[key];
  62916. --this._count;
  62917. return val;
  62918. }
  62919. return null;
  62920. };
  62921. /**
  62922. * Remove a key/value from the dictionary.
  62923. * @param key the key to remove
  62924. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62925. */
  62926. StringDictionary.prototype.remove = function (key) {
  62927. if (this.contains(key)) {
  62928. delete this._data[key];
  62929. --this._count;
  62930. return true;
  62931. }
  62932. return false;
  62933. };
  62934. /**
  62935. * Clear the whole content of the dictionary
  62936. */
  62937. StringDictionary.prototype.clear = function () {
  62938. this._data = {};
  62939. this._count = 0;
  62940. };
  62941. Object.defineProperty(StringDictionary.prototype, "count", {
  62942. get: function () {
  62943. return this._count;
  62944. },
  62945. enumerable: true,
  62946. configurable: true
  62947. });
  62948. /**
  62949. * Execute a callback on each key/val of the dictionary.
  62950. * Note that you can remove any element in this dictionary in the callback implementation
  62951. * @param callback the callback to execute on a given key/value pair
  62952. */
  62953. StringDictionary.prototype.forEach = function (callback) {
  62954. for (var cur in this._data) {
  62955. var val = this._data[cur];
  62956. callback(cur, val);
  62957. }
  62958. };
  62959. /**
  62960. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62961. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62962. * Note that you can remove any element in this dictionary in the callback implementation
  62963. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62964. */
  62965. StringDictionary.prototype.first = function (callback) {
  62966. for (var cur in this._data) {
  62967. var val = this._data[cur];
  62968. var res = callback(cur, val);
  62969. if (res) {
  62970. return res;
  62971. }
  62972. }
  62973. return null;
  62974. };
  62975. return StringDictionary;
  62976. }());
  62977. BABYLON.StringDictionary = StringDictionary;
  62978. })(BABYLON || (BABYLON = {}));
  62979. //# sourceMappingURL=babylon.stringDictionary.js.map
  62980. var BABYLON;
  62981. (function (BABYLON) {
  62982. var Debug;
  62983. (function (Debug) {
  62984. /**
  62985. * Class used to render a debug view of a given skeleton
  62986. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62987. */
  62988. var SkeletonViewer = /** @class */ (function () {
  62989. /**
  62990. * Creates a new SkeletonViewer
  62991. * @param skeleton defines the skeleton to render
  62992. * @param mesh defines the mesh attached to the skeleton
  62993. * @param scene defines the hosting scene
  62994. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62995. * @param renderingGroupId defines the rendering group id to use with the viewer
  62996. */
  62997. function SkeletonViewer(
  62998. /** defines the skeleton to render */
  62999. skeleton,
  63000. /** defines the mesh attached to the skeleton */
  63001. mesh, scene,
  63002. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63003. autoUpdateBonesMatrices,
  63004. /** defines the rendering group id to use with the viewer */
  63005. renderingGroupId) {
  63006. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63007. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63008. this.skeleton = skeleton;
  63009. this.mesh = mesh;
  63010. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63011. this.renderingGroupId = renderingGroupId;
  63012. /** Gets or sets the color used to render the skeleton */
  63013. this.color = BABYLON.Color3.White();
  63014. this._debugLines = new Array();
  63015. this._isEnabled = false;
  63016. this._scene = scene;
  63017. this.update();
  63018. this._renderFunction = this.update.bind(this);
  63019. }
  63020. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63021. get: function () {
  63022. return this._isEnabled;
  63023. },
  63024. /** Gets or sets a boolean indicating if the viewer is enabled */
  63025. set: function (value) {
  63026. if (this._isEnabled === value) {
  63027. return;
  63028. }
  63029. this._isEnabled = value;
  63030. if (value) {
  63031. this._scene.registerBeforeRender(this._renderFunction);
  63032. }
  63033. else {
  63034. this._scene.unregisterBeforeRender(this._renderFunction);
  63035. }
  63036. },
  63037. enumerable: true,
  63038. configurable: true
  63039. });
  63040. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63041. if (x === void 0) { x = 0; }
  63042. if (y === void 0) { y = 0; }
  63043. if (z === void 0) { z = 0; }
  63044. var tmat = BABYLON.Tmp.Matrix[0];
  63045. var parentBone = bone.getParent();
  63046. tmat.copyFrom(bone.getLocalMatrix());
  63047. if (x !== 0 || y !== 0 || z !== 0) {
  63048. var tmat2 = BABYLON.Tmp.Matrix[1];
  63049. BABYLON.Matrix.IdentityToRef(tmat2);
  63050. tmat2.m[12] = x;
  63051. tmat2.m[13] = y;
  63052. tmat2.m[14] = z;
  63053. tmat2.multiplyToRef(tmat, tmat);
  63054. }
  63055. if (parentBone) {
  63056. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63057. }
  63058. tmat.multiplyToRef(meshMat, tmat);
  63059. position.x = tmat.m[12];
  63060. position.y = tmat.m[13];
  63061. position.z = tmat.m[14];
  63062. };
  63063. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63064. var len = bones.length;
  63065. var meshPos = this.mesh.position;
  63066. for (var i = 0; i < len; i++) {
  63067. var bone = bones[i];
  63068. var points = this._debugLines[i];
  63069. if (!points) {
  63070. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63071. this._debugLines[i] = points;
  63072. }
  63073. this._getBonePosition(points[0], bone, meshMat);
  63074. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63075. points[0].subtractInPlace(meshPos);
  63076. points[1].subtractInPlace(meshPos);
  63077. }
  63078. };
  63079. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63080. var len = bones.length;
  63081. var boneNum = 0;
  63082. var meshPos = this.mesh.position;
  63083. for (var i = len - 1; i >= 0; i--) {
  63084. var childBone = bones[i];
  63085. var parentBone = childBone.getParent();
  63086. if (!parentBone) {
  63087. continue;
  63088. }
  63089. var points = this._debugLines[boneNum];
  63090. if (!points) {
  63091. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63092. this._debugLines[boneNum] = points;
  63093. }
  63094. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63095. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63096. points[0].subtractInPlace(meshPos);
  63097. points[1].subtractInPlace(meshPos);
  63098. boneNum++;
  63099. }
  63100. };
  63101. /** Update the viewer to sync with current skeleton state */
  63102. SkeletonViewer.prototype.update = function () {
  63103. if (this.autoUpdateBonesMatrices) {
  63104. this.skeleton.computeAbsoluteTransforms();
  63105. }
  63106. if (this.skeleton.bones[0].length === undefined) {
  63107. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63108. }
  63109. else {
  63110. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63111. }
  63112. if (!this._debugMesh) {
  63113. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63114. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63115. }
  63116. else {
  63117. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63118. }
  63119. this._debugMesh.position.copyFrom(this.mesh.position);
  63120. this._debugMesh.color = this.color;
  63121. };
  63122. /** Release associated resources */
  63123. SkeletonViewer.prototype.dispose = function () {
  63124. if (this._debugMesh) {
  63125. this.isEnabled = false;
  63126. this._debugMesh.dispose();
  63127. this._debugMesh = null;
  63128. }
  63129. };
  63130. return SkeletonViewer;
  63131. }());
  63132. Debug.SkeletonViewer = SkeletonViewer;
  63133. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63134. })(BABYLON || (BABYLON = {}));
  63135. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63136. /**
  63137. * Module Debug contains the (visual) components to debug a scene correctly
  63138. */
  63139. var BABYLON;
  63140. (function (BABYLON) {
  63141. var Debug;
  63142. (function (Debug) {
  63143. /**
  63144. * The Axes viewer will show 3 axes in a specific point in space
  63145. */
  63146. var AxesViewer = /** @class */ (function () {
  63147. /**
  63148. * Creates a new AxesViewer
  63149. * @param scene defines the hosting scene
  63150. * @param scaleLines defines a number used to scale line length (1 by default)
  63151. */
  63152. function AxesViewer(scene, scaleLines) {
  63153. if (scaleLines === void 0) { scaleLines = 1; }
  63154. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63155. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63156. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63157. /**
  63158. * Gets or sets a number used to scale line length
  63159. */
  63160. this.scaleLines = 1;
  63161. this.scaleLines = scaleLines;
  63162. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63163. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63164. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63165. this._xmesh.renderingGroupId = 2;
  63166. this._ymesh.renderingGroupId = 2;
  63167. this._zmesh.renderingGroupId = 2;
  63168. this._xmesh.material.checkReadyOnlyOnce = true;
  63169. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63170. this._ymesh.material.checkReadyOnlyOnce = true;
  63171. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63172. this._zmesh.material.checkReadyOnlyOnce = true;
  63173. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63174. this.scene = scene;
  63175. }
  63176. /**
  63177. * Force the viewer to update
  63178. * @param position defines the position of the viewer
  63179. * @param xaxis defines the x axis of the viewer
  63180. * @param yaxis defines the y axis of the viewer
  63181. * @param zaxis defines the z axis of the viewer
  63182. */
  63183. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63184. var scaleLines = this.scaleLines;
  63185. if (this._xmesh) {
  63186. this._xmesh.position.copyFrom(position);
  63187. }
  63188. if (this._ymesh) {
  63189. this._ymesh.position.copyFrom(position);
  63190. }
  63191. if (this._zmesh) {
  63192. this._zmesh.position.copyFrom(position);
  63193. }
  63194. var point2 = this._xline[1];
  63195. point2.x = xaxis.x * scaleLines;
  63196. point2.y = xaxis.y * scaleLines;
  63197. point2.z = xaxis.z * scaleLines;
  63198. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63199. point2 = this._yline[1];
  63200. point2.x = yaxis.x * scaleLines;
  63201. point2.y = yaxis.y * scaleLines;
  63202. point2.z = yaxis.z * scaleLines;
  63203. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63204. point2 = this._zline[1];
  63205. point2.x = zaxis.x * scaleLines;
  63206. point2.y = zaxis.y * scaleLines;
  63207. point2.z = zaxis.z * scaleLines;
  63208. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63209. };
  63210. /** Releases resources */
  63211. AxesViewer.prototype.dispose = function () {
  63212. if (this._xmesh) {
  63213. this._xmesh.dispose();
  63214. }
  63215. if (this._ymesh) {
  63216. this._ymesh.dispose();
  63217. }
  63218. if (this._zmesh) {
  63219. this._zmesh.dispose();
  63220. }
  63221. this._xmesh = null;
  63222. this._ymesh = null;
  63223. this._zmesh = null;
  63224. this.scene = null;
  63225. };
  63226. return AxesViewer;
  63227. }());
  63228. Debug.AxesViewer = AxesViewer;
  63229. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63230. })(BABYLON || (BABYLON = {}));
  63231. //# sourceMappingURL=babylon.axesViewer.js.map
  63232. var BABYLON;
  63233. (function (BABYLON) {
  63234. var Debug;
  63235. (function (Debug) {
  63236. /**
  63237. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63238. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63239. */
  63240. var BoneAxesViewer = /** @class */ (function (_super) {
  63241. __extends(BoneAxesViewer, _super);
  63242. /**
  63243. * Creates a new BoneAxesViewer
  63244. * @param scene defines the hosting scene
  63245. * @param bone defines the target bone
  63246. * @param mesh defines the target mesh
  63247. * @param scaleLines defines a scaling factor for line length (1 by default)
  63248. */
  63249. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63250. if (scaleLines === void 0) { scaleLines = 1; }
  63251. var _this = _super.call(this, scene, scaleLines) || this;
  63252. /** Gets current position */
  63253. _this.pos = BABYLON.Vector3.Zero();
  63254. /** Gets direction of X axis */
  63255. _this.xaxis = BABYLON.Vector3.Zero();
  63256. /** Gets direction of Y axis */
  63257. _this.yaxis = BABYLON.Vector3.Zero();
  63258. /** Gets direction of Z axis */
  63259. _this.zaxis = BABYLON.Vector3.Zero();
  63260. _this.mesh = mesh;
  63261. _this.bone = bone;
  63262. return _this;
  63263. }
  63264. /**
  63265. * Force the viewer to update
  63266. */
  63267. BoneAxesViewer.prototype.update = function () {
  63268. if (!this.mesh || !this.bone) {
  63269. return;
  63270. }
  63271. var bone = this.bone;
  63272. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63273. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63274. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63275. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63276. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63277. };
  63278. /** Releases resources */
  63279. BoneAxesViewer.prototype.dispose = function () {
  63280. if (this.mesh) {
  63281. this.mesh = null;
  63282. this.bone = null;
  63283. _super.prototype.dispose.call(this);
  63284. }
  63285. };
  63286. return BoneAxesViewer;
  63287. }(Debug.AxesViewer));
  63288. Debug.BoneAxesViewer = BoneAxesViewer;
  63289. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63290. })(BABYLON || (BABYLON = {}));
  63291. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63292. var BABYLON;
  63293. (function (BABYLON) {
  63294. /**
  63295. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63296. * in order to better appreciate the issue one might have.
  63297. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63298. */
  63299. var RayHelper = /** @class */ (function () {
  63300. /**
  63301. * Instantiate a new ray helper.
  63302. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63303. * in order to better appreciate the issue one might have.
  63304. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63305. * @param ray Defines the ray we are currently tryin to visualize
  63306. */
  63307. function RayHelper(ray) {
  63308. this.ray = ray;
  63309. }
  63310. /**
  63311. * Helper function to create a colored helper in a scene in one line.
  63312. * @param ray Defines the ray we are currently tryin to visualize
  63313. * @param scene Defines the scene the ray is used in
  63314. * @param color Defines the color we want to see the ray in
  63315. * @returns The newly created ray helper.
  63316. */
  63317. RayHelper.CreateAndShow = function (ray, scene, color) {
  63318. var helper = new RayHelper(ray);
  63319. helper.show(scene, color);
  63320. return helper;
  63321. };
  63322. /**
  63323. * Shows the ray we are willing to debug.
  63324. * @param scene Defines the scene the ray needs to be rendered in
  63325. * @param color Defines the color the ray needs to be rendered in
  63326. */
  63327. RayHelper.prototype.show = function (scene, color) {
  63328. if (!this._renderFunction && this.ray) {
  63329. var ray = this.ray;
  63330. this._renderFunction = this._render.bind(this);
  63331. this._scene = scene;
  63332. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63333. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63334. if (this._renderFunction) {
  63335. this._scene.registerBeforeRender(this._renderFunction);
  63336. }
  63337. }
  63338. if (color && this._renderLine) {
  63339. this._renderLine.color.copyFrom(color);
  63340. }
  63341. };
  63342. /**
  63343. * Hides the ray we are debugging.
  63344. */
  63345. RayHelper.prototype.hide = function () {
  63346. if (this._renderFunction && this._scene) {
  63347. this._scene.unregisterBeforeRender(this._renderFunction);
  63348. this._scene = null;
  63349. this._renderFunction = null;
  63350. if (this._renderLine) {
  63351. this._renderLine.dispose();
  63352. this._renderLine = null;
  63353. }
  63354. this._renderPoints = [];
  63355. }
  63356. };
  63357. RayHelper.prototype._render = function () {
  63358. var ray = this.ray;
  63359. if (!ray) {
  63360. return;
  63361. }
  63362. var point = this._renderPoints[1];
  63363. var len = Math.min(ray.length, 1000000);
  63364. point.copyFrom(ray.direction);
  63365. point.scaleInPlace(len);
  63366. point.addInPlace(ray.origin);
  63367. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63368. };
  63369. /**
  63370. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63371. * @param mesh Defines the mesh we want the helper attached to
  63372. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63373. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63374. * @param length Defines the length of the ray
  63375. */
  63376. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63377. this._attachedToMesh = mesh;
  63378. var ray = this.ray;
  63379. if (!ray) {
  63380. return;
  63381. }
  63382. if (!ray.direction) {
  63383. ray.direction = BABYLON.Vector3.Zero();
  63384. }
  63385. if (!ray.origin) {
  63386. ray.origin = BABYLON.Vector3.Zero();
  63387. }
  63388. if (length) {
  63389. ray.length = length;
  63390. }
  63391. if (!meshSpaceOrigin) {
  63392. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63393. }
  63394. if (!meshSpaceDirection) {
  63395. // -1 so that this will work with Mesh.lookAt
  63396. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63397. }
  63398. if (!this._meshSpaceDirection) {
  63399. this._meshSpaceDirection = meshSpaceDirection.clone();
  63400. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63401. }
  63402. else {
  63403. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63404. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63405. }
  63406. if (!this._updateToMeshFunction) {
  63407. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63408. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63409. }
  63410. this._updateToMesh();
  63411. };
  63412. /**
  63413. * Detach the ray helper from the mesh it has previously been attached to.
  63414. */
  63415. RayHelper.prototype.detachFromMesh = function () {
  63416. if (this._attachedToMesh) {
  63417. if (this._updateToMeshFunction) {
  63418. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63419. }
  63420. this._attachedToMesh = null;
  63421. this._updateToMeshFunction = null;
  63422. }
  63423. };
  63424. RayHelper.prototype._updateToMesh = function () {
  63425. var ray = this.ray;
  63426. if (!this._attachedToMesh || !ray) {
  63427. return;
  63428. }
  63429. if (this._attachedToMesh._isDisposed) {
  63430. this.detachFromMesh();
  63431. return;
  63432. }
  63433. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63434. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63435. };
  63436. /**
  63437. * Dispose the helper and release its associated resources.
  63438. */
  63439. RayHelper.prototype.dispose = function () {
  63440. this.hide();
  63441. this.detachFromMesh();
  63442. this.ray = null;
  63443. };
  63444. return RayHelper;
  63445. }());
  63446. BABYLON.RayHelper = RayHelper;
  63447. })(BABYLON || (BABYLON = {}));
  63448. //# sourceMappingURL=babylon.rayHelper.js.map
  63449. var BABYLON;
  63450. (function (BABYLON) {
  63451. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63452. get: function () {
  63453. if (!this._debugLayer) {
  63454. this._debugLayer = new DebugLayer(this);
  63455. }
  63456. return this._debugLayer;
  63457. },
  63458. enumerable: true,
  63459. configurable: true
  63460. });
  63461. /**
  63462. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63463. * what is happening in your scene
  63464. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63465. */
  63466. var DebugLayer = /** @class */ (function () {
  63467. /**
  63468. * Instantiates a new debug layer.
  63469. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63470. * what is happening in your scene
  63471. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63472. * @param scene Defines the scene to inspect
  63473. */
  63474. function DebugLayer(scene) {
  63475. var _this = this;
  63476. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63477. /**
  63478. * Observable triggered when a property is changed through the inspector.
  63479. */
  63480. this.onPropertyChangedObservable = new BABYLON.Observable();
  63481. this._scene = scene;
  63482. this._scene.onDisposeObservable.add(function () {
  63483. // Debug layer
  63484. if (_this._scene._debugLayer) {
  63485. _this._scene._debugLayer.hide();
  63486. }
  63487. });
  63488. }
  63489. /** Creates the inspector window. */
  63490. DebugLayer.prototype._createInspector = function (config) {
  63491. if (config === void 0) { config = {}; }
  63492. var popup = config.popup || false;
  63493. var initialTab = config.initialTab || 0;
  63494. var parentElement = config.parentElement || null;
  63495. if (!this._inspector) {
  63496. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63497. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63498. } // else nothing to do as instance is already created
  63499. };
  63500. /**
  63501. * Get if the inspector is visible or not.
  63502. * @returns true if visible otherwise, false
  63503. */
  63504. DebugLayer.prototype.isVisible = function () {
  63505. if (!this._inspector) {
  63506. return false;
  63507. }
  63508. return true;
  63509. };
  63510. /**
  63511. * Hide the inspector and close its window.
  63512. */
  63513. DebugLayer.prototype.hide = function () {
  63514. if (this._inspector) {
  63515. try {
  63516. this._inspector.dispose();
  63517. }
  63518. catch (e) {
  63519. // If the inspector has been removed directly from the inspector tool
  63520. }
  63521. this.onPropertyChangedObservable.clear();
  63522. this._inspector = null;
  63523. }
  63524. };
  63525. /**
  63526. *
  63527. * Launch the debugLayer.
  63528. *
  63529. * initialTab:
  63530. * | Value | Tab Name |
  63531. * | --- | --- |
  63532. * | 0 | Scene |
  63533. * | 1 | Console |
  63534. * | 2 | Stats |
  63535. * | 3 | Textures |
  63536. * | 4 | Mesh |
  63537. * | 5 | Light |
  63538. * | 6 | Material |
  63539. * | 7 | GLTF |
  63540. * | 8 | GUI |
  63541. * | 9 | Physics |
  63542. * | 10 | Camera |
  63543. * | 11 | Audio |
  63544. *
  63545. * @param config Define the configuration of the inspector
  63546. */
  63547. DebugLayer.prototype.show = function (config) {
  63548. if (config === void 0) { config = {}; }
  63549. if (typeof this.BJSINSPECTOR == 'undefined') {
  63550. // Load inspector and add it to the DOM
  63551. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63552. }
  63553. else {
  63554. // Otherwise creates the inspector
  63555. this._createInspector(config);
  63556. }
  63557. };
  63558. /**
  63559. * Gets the active tab
  63560. * @return the index of the active tab or -1 if the inspector is hidden
  63561. */
  63562. DebugLayer.prototype.getActiveTab = function () {
  63563. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63564. };
  63565. /**
  63566. * Define the url to get the inspector script from.
  63567. * By default it uses the babylonjs CDN.
  63568. * @ignoreNaming
  63569. */
  63570. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63571. return DebugLayer;
  63572. }());
  63573. BABYLON.DebugLayer = DebugLayer;
  63574. })(BABYLON || (BABYLON = {}));
  63575. //# sourceMappingURL=babylon.debugLayer.js.map
  63576. var BABYLON;
  63577. (function (BABYLON) {
  63578. var Debug;
  63579. (function (Debug) {
  63580. /**
  63581. * Used to show the physics impostor around the specific mesh
  63582. */
  63583. var PhysicsViewer = /** @class */ (function () {
  63584. /**
  63585. * Creates a new PhysicsViewer
  63586. * @param scene defines the hosting scene
  63587. */
  63588. function PhysicsViewer(scene) {
  63589. /** @hidden */
  63590. this._impostors = [];
  63591. /** @hidden */
  63592. this._meshes = [];
  63593. /** @hidden */
  63594. this._numMeshes = 0;
  63595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63596. var physicEngine = this._scene.getPhysicsEngine();
  63597. if (physicEngine) {
  63598. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63599. }
  63600. }
  63601. /** @hidden */
  63602. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63603. var plugin = this._physicsEnginePlugin;
  63604. for (var i = 0; i < this._numMeshes; i++) {
  63605. var impostor = this._impostors[i];
  63606. if (!impostor) {
  63607. continue;
  63608. }
  63609. if (impostor.isDisposed) {
  63610. this.hideImpostor(this._impostors[i--]);
  63611. }
  63612. else {
  63613. var mesh = this._meshes[i];
  63614. if (mesh && plugin) {
  63615. plugin.syncMeshWithImpostor(mesh, impostor);
  63616. }
  63617. }
  63618. }
  63619. };
  63620. /**
  63621. * Renders a specified physic impostor
  63622. * @param impostor defines the impostor to render
  63623. */
  63624. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63625. if (!this._scene) {
  63626. return;
  63627. }
  63628. for (var i = 0; i < this._numMeshes; i++) {
  63629. if (this._impostors[i] == impostor) {
  63630. return;
  63631. }
  63632. }
  63633. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63634. if (debugMesh) {
  63635. this._impostors[this._numMeshes] = impostor;
  63636. this._meshes[this._numMeshes] = debugMesh;
  63637. if (this._numMeshes === 0) {
  63638. this._renderFunction = this._updateDebugMeshes.bind(this);
  63639. this._scene.registerBeforeRender(this._renderFunction);
  63640. }
  63641. this._numMeshes++;
  63642. }
  63643. };
  63644. /**
  63645. * Hides a specified physic impostor
  63646. * @param impostor defines the impostor to hide
  63647. */
  63648. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63649. if (!impostor || !this._scene) {
  63650. return;
  63651. }
  63652. var removed = false;
  63653. for (var i = 0; i < this._numMeshes; i++) {
  63654. if (this._impostors[i] == impostor) {
  63655. var mesh = this._meshes[i];
  63656. if (!mesh) {
  63657. continue;
  63658. }
  63659. this._scene.removeMesh(mesh);
  63660. mesh.dispose();
  63661. this._numMeshes--;
  63662. if (this._numMeshes > 0) {
  63663. this._meshes[i] = this._meshes[this._numMeshes];
  63664. this._impostors[i] = this._impostors[this._numMeshes];
  63665. this._meshes[this._numMeshes] = null;
  63666. this._impostors[this._numMeshes] = null;
  63667. }
  63668. else {
  63669. this._meshes[0] = null;
  63670. this._impostors[0] = null;
  63671. }
  63672. removed = true;
  63673. break;
  63674. }
  63675. }
  63676. if (removed && this._numMeshes === 0) {
  63677. this._scene.unregisterBeforeRender(this._renderFunction);
  63678. }
  63679. };
  63680. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63681. if (!this._debugMaterial) {
  63682. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63683. this._debugMaterial.wireframe = true;
  63684. }
  63685. return this._debugMaterial;
  63686. };
  63687. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63688. if (!this._debugBoxMesh) {
  63689. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63690. this._debugBoxMesh.renderingGroupId = 1;
  63691. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63692. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63693. scene.removeMesh(this._debugBoxMesh);
  63694. }
  63695. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63696. };
  63697. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63698. if (!this._debugSphereMesh) {
  63699. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63700. this._debugSphereMesh.renderingGroupId = 1;
  63701. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63702. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63703. scene.removeMesh(this._debugSphereMesh);
  63704. }
  63705. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63706. };
  63707. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63708. var mesh = null;
  63709. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63710. mesh = this._getDebugBoxMesh(scene);
  63711. impostor.getBoxSizeToRef(mesh.scaling);
  63712. }
  63713. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63714. mesh = this._getDebugSphereMesh(scene);
  63715. var radius = impostor.getRadius();
  63716. mesh.scaling.x = radius * 2;
  63717. mesh.scaling.y = radius * 2;
  63718. mesh.scaling.z = radius * 2;
  63719. }
  63720. return mesh;
  63721. };
  63722. /** Releases all resources */
  63723. PhysicsViewer.prototype.dispose = function () {
  63724. for (var i = 0; i < this._numMeshes; i++) {
  63725. this.hideImpostor(this._impostors[i]);
  63726. }
  63727. if (this._debugBoxMesh) {
  63728. this._debugBoxMesh.dispose();
  63729. }
  63730. if (this._debugSphereMesh) {
  63731. this._debugSphereMesh.dispose();
  63732. }
  63733. if (this._debugMaterial) {
  63734. this._debugMaterial.dispose();
  63735. }
  63736. this._impostors.length = 0;
  63737. this._scene = null;
  63738. this._physicsEnginePlugin = null;
  63739. };
  63740. return PhysicsViewer;
  63741. }());
  63742. Debug.PhysicsViewer = PhysicsViewer;
  63743. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63744. })(BABYLON || (BABYLON = {}));
  63745. //# sourceMappingURL=babylon.physicsViewer.js.map
  63746. var BABYLON;
  63747. (function (BABYLON) {
  63748. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63749. get: function () {
  63750. return this._forceShowBoundingBoxes || false;
  63751. },
  63752. set: function (value) {
  63753. this._forceShowBoundingBoxes = value;
  63754. // Lazyly creates a BB renderer if needed.
  63755. if (value) {
  63756. this.getBoundingBoxRenderer();
  63757. }
  63758. },
  63759. enumerable: true,
  63760. configurable: true
  63761. });
  63762. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63763. if (!this._boundingBoxRenderer) {
  63764. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63765. }
  63766. return this._boundingBoxRenderer;
  63767. };
  63768. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63769. get: function () {
  63770. return this._showBoundingBox || false;
  63771. },
  63772. set: function (value) {
  63773. this._showBoundingBox = value;
  63774. // Lazyly creates a BB renderer if needed.
  63775. if (value) {
  63776. this.getScene().getBoundingBoxRenderer();
  63777. }
  63778. },
  63779. enumerable: true,
  63780. configurable: true
  63781. });
  63782. /**
  63783. * Component responsible of rendering the bounding box of the meshes in a scene.
  63784. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63785. */
  63786. var BoundingBoxRenderer = /** @class */ (function () {
  63787. /**
  63788. * Instantiates a new bounding box renderer in a scene.
  63789. * @param scene the scene the renderer renders in
  63790. */
  63791. function BoundingBoxRenderer(scene) {
  63792. /**
  63793. * The component name helpfull to identify the component in the list of scene components.
  63794. */
  63795. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  63796. /**
  63797. * Color of the bounding box lines placed in front of an object
  63798. */
  63799. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63800. /**
  63801. * Color of the bounding box lines placed behind an object
  63802. */
  63803. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63804. /**
  63805. * Defines if the renderer should show the back lines or not
  63806. */
  63807. this.showBackLines = true;
  63808. /**
  63809. * @hidden
  63810. */
  63811. this.renderList = new BABYLON.SmartArray(32);
  63812. this._vertexBuffers = {};
  63813. this.scene = scene;
  63814. scene._addComponent(this);
  63815. }
  63816. /**
  63817. * Registers the component in a given scene
  63818. */
  63819. BoundingBoxRenderer.prototype.register = function () {
  63820. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  63821. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  63822. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  63823. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  63824. };
  63825. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  63826. if (mesh.showSubMeshesBoundingBox) {
  63827. var boundingInfo = subMesh.getBoundingInfo();
  63828. if (boundingInfo !== null && boundingInfo !== undefined) {
  63829. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63830. this.renderList.push(boundingInfo.boundingBox);
  63831. }
  63832. }
  63833. };
  63834. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  63835. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  63836. var boundingInfo = sourceMesh.getBoundingInfo();
  63837. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63838. this.renderList.push(boundingInfo.boundingBox);
  63839. }
  63840. };
  63841. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63842. if (this._colorShader) {
  63843. return;
  63844. }
  63845. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  63846. attributes: [BABYLON.VertexBuffer.PositionKind],
  63847. uniforms: ["world", "viewProjection", "color"]
  63848. });
  63849. var engine = this.scene.getEngine();
  63850. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63851. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63852. this._createIndexBuffer();
  63853. };
  63854. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63855. var engine = this.scene.getEngine();
  63856. 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]);
  63857. };
  63858. /**
  63859. * Rebuilds the elements related to this component in case of
  63860. * context lost for instance.
  63861. */
  63862. BoundingBoxRenderer.prototype.rebuild = function () {
  63863. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63864. if (vb) {
  63865. vb._rebuild();
  63866. }
  63867. this._createIndexBuffer();
  63868. };
  63869. /**
  63870. * @hidden
  63871. */
  63872. BoundingBoxRenderer.prototype.reset = function () {
  63873. this.renderList.reset();
  63874. };
  63875. /**
  63876. * Render the bounding boxes of a specific rendering group
  63877. * @param renderingGroupId defines the rendering group to render
  63878. */
  63879. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  63880. if (this.renderList.length === 0) {
  63881. return;
  63882. }
  63883. this._prepareRessources();
  63884. if (!this._colorShader.isReady()) {
  63885. return;
  63886. }
  63887. var engine = this.scene.getEngine();
  63888. engine.setDepthWrite(false);
  63889. this._colorShader._preBind();
  63890. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63891. var boundingBox = this.renderList.data[boundingBoxIndex];
  63892. if (boundingBox._tag !== renderingGroupId) {
  63893. continue;
  63894. }
  63895. var min = boundingBox.minimum;
  63896. var max = boundingBox.maximum;
  63897. var diff = max.subtract(min);
  63898. var median = min.add(diff.scale(0.5));
  63899. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63900. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63901. .multiply(boundingBox.getWorldMatrix());
  63902. // VBOs
  63903. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63904. if (this.showBackLines) {
  63905. // Back
  63906. engine.setDepthFunctionToGreaterOrEqual();
  63907. this.scene.resetCachedMaterial();
  63908. this._colorShader.setColor4("color", this.backColor.toColor4());
  63909. this._colorShader.bind(worldMatrix);
  63910. // Draw order
  63911. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63912. }
  63913. // Front
  63914. engine.setDepthFunctionToLess();
  63915. this.scene.resetCachedMaterial();
  63916. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63917. this._colorShader.bind(worldMatrix);
  63918. // Draw order
  63919. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63920. }
  63921. this._colorShader.unbind();
  63922. engine.setDepthFunctionToLessOrEqual();
  63923. engine.setDepthWrite(true);
  63924. };
  63925. /**
  63926. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63927. * @param mesh Define the mesh to render the occlusion bounding box for
  63928. */
  63929. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63930. this._prepareRessources();
  63931. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63932. return;
  63933. }
  63934. var engine = this.scene.getEngine();
  63935. engine.setDepthWrite(false);
  63936. engine.setColorWrite(false);
  63937. this._colorShader._preBind();
  63938. var boundingBox = mesh._boundingInfo.boundingBox;
  63939. var min = boundingBox.minimum;
  63940. var max = boundingBox.maximum;
  63941. var diff = max.subtract(min);
  63942. var median = min.add(diff.scale(0.5));
  63943. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63944. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63945. .multiply(boundingBox.getWorldMatrix());
  63946. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63947. engine.setDepthFunctionToLess();
  63948. this.scene.resetCachedMaterial();
  63949. this._colorShader.bind(worldMatrix);
  63950. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63951. this._colorShader.unbind();
  63952. engine.setDepthFunctionToLessOrEqual();
  63953. engine.setDepthWrite(true);
  63954. engine.setColorWrite(true);
  63955. };
  63956. /**
  63957. * Dispose and release the resources attached to this renderer.
  63958. */
  63959. BoundingBoxRenderer.prototype.dispose = function () {
  63960. if (!this._colorShader) {
  63961. return;
  63962. }
  63963. this.renderList.dispose();
  63964. this._colorShader.dispose();
  63965. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63966. if (buffer) {
  63967. buffer.dispose();
  63968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63969. }
  63970. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63971. };
  63972. return BoundingBoxRenderer;
  63973. }());
  63974. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63975. })(BABYLON || (BABYLON = {}));
  63976. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63977. var BABYLON;
  63978. (function (BABYLON) {
  63979. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63980. return this._gl.createTransformFeedback();
  63981. };
  63982. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63983. this._gl.deleteTransformFeedback(value);
  63984. };
  63985. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63986. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63987. };
  63988. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63989. if (usePoints === void 0) { usePoints = true; }
  63990. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63991. };
  63992. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63993. this._gl.endTransformFeedback();
  63994. };
  63995. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63996. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63997. };
  63998. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63999. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64000. };
  64001. })(BABYLON || (BABYLON = {}));
  64002. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64003. var BABYLON;
  64004. (function (BABYLON) {
  64005. /**
  64006. * This represents a GPU particle system in Babylon
  64007. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64008. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64009. */
  64010. var GPUParticleSystem = /** @class */ (function (_super) {
  64011. __extends(GPUParticleSystem, _super);
  64012. /**
  64013. * Instantiates a GPU particle system.
  64014. * 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.
  64015. * @param name The name of the particle system
  64016. * @param options The options used to create the system
  64017. * @param scene The scene the particle system belongs to
  64018. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64019. */
  64020. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64021. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64022. var _this = _super.call(this, name) || this;
  64023. /**
  64024. * The layer mask we are rendering the particles through.
  64025. */
  64026. _this.layerMask = 0x0FFFFFFF;
  64027. _this._accumulatedCount = 0;
  64028. _this._targetIndex = 0;
  64029. _this._currentRenderId = -1;
  64030. _this._started = false;
  64031. _this._stopped = false;
  64032. _this._timeDelta = 0;
  64033. _this._attributesStrideSize = 21;
  64034. _this._actualFrame = 0;
  64035. _this._rawTextureWidth = 256;
  64036. /**
  64037. * An event triggered when the system is disposed.
  64038. */
  64039. _this.onDisposeObservable = new BABYLON.Observable();
  64040. /**
  64041. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64042. * to override the particles.
  64043. */
  64044. _this.forceDepthWrite = false;
  64045. _this._preWarmDone = false;
  64046. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64047. // Setup the default processing configuration to the scene.
  64048. _this._attachImageProcessingConfiguration(null);
  64049. _this._engine = _this._scene.getEngine();
  64050. if (!options.randomTextureSize) {
  64051. delete options.randomTextureSize;
  64052. }
  64053. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64054. var optionsAsNumber = options;
  64055. if (isFinite(optionsAsNumber)) {
  64056. fullOptions.capacity = optionsAsNumber;
  64057. }
  64058. _this._capacity = fullOptions.capacity;
  64059. _this._activeCount = fullOptions.capacity;
  64060. _this._currentActiveCount = 0;
  64061. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64062. _this._scene.particleSystems.push(_this);
  64063. _this._updateEffectOptions = {
  64064. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64065. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64066. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64067. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64068. uniformBuffersNames: [],
  64069. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64070. defines: "",
  64071. fallbacks: null,
  64072. onCompiled: null,
  64073. onError: null,
  64074. indexParameters: null,
  64075. maxSimultaneousLights: 0,
  64076. transformFeedbackVaryings: []
  64077. };
  64078. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64079. // Random data
  64080. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64081. var d = [];
  64082. for (var i = 0; i < maxTextureSize; ++i) {
  64083. d.push(Math.random());
  64084. d.push(Math.random());
  64085. d.push(Math.random());
  64086. d.push(Math.random());
  64087. }
  64088. _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);
  64089. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64090. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64091. d = [];
  64092. for (var i = 0; i < maxTextureSize; ++i) {
  64093. d.push(Math.random());
  64094. d.push(Math.random());
  64095. d.push(Math.random());
  64096. d.push(Math.random());
  64097. }
  64098. _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);
  64099. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64100. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64101. _this._randomTextureSize = maxTextureSize;
  64102. return _this;
  64103. }
  64104. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64105. /**
  64106. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64107. */
  64108. get: function () {
  64109. if (!BABYLON.Engine.LastCreatedEngine) {
  64110. return false;
  64111. }
  64112. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64113. },
  64114. enumerable: true,
  64115. configurable: true
  64116. });
  64117. /**
  64118. * Gets the maximum number of particles active at the same time.
  64119. * @returns The max number of active particles.
  64120. */
  64121. GPUParticleSystem.prototype.getCapacity = function () {
  64122. return this._capacity;
  64123. };
  64124. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64125. /**
  64126. * Gets or set the number of active particles
  64127. */
  64128. get: function () {
  64129. return this._activeCount;
  64130. },
  64131. set: function (value) {
  64132. this._activeCount = Math.min(value, this._capacity);
  64133. },
  64134. enumerable: true,
  64135. configurable: true
  64136. });
  64137. /**
  64138. * Is this system ready to be used/rendered
  64139. * @return true if the system is ready
  64140. */
  64141. GPUParticleSystem.prototype.isReady = function () {
  64142. if (!this._updateEffect) {
  64143. this._recreateUpdateEffect();
  64144. this._recreateRenderEffect();
  64145. return false;
  64146. }
  64147. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64148. return false;
  64149. }
  64150. return true;
  64151. };
  64152. /**
  64153. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64154. * @returns True if it has been started, otherwise false.
  64155. */
  64156. GPUParticleSystem.prototype.isStarted = function () {
  64157. return this._started;
  64158. };
  64159. /**
  64160. * Starts the particle system and begins to emit
  64161. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64162. */
  64163. GPUParticleSystem.prototype.start = function (delay) {
  64164. var _this = this;
  64165. if (delay === void 0) { delay = this.startDelay; }
  64166. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64167. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64168. }
  64169. if (delay) {
  64170. setTimeout(function () {
  64171. _this.start(0);
  64172. }, delay);
  64173. return;
  64174. }
  64175. this._started = true;
  64176. this._stopped = false;
  64177. this._preWarmDone = false;
  64178. // Animations
  64179. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64180. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64181. }
  64182. };
  64183. /**
  64184. * Stops the particle system.
  64185. */
  64186. GPUParticleSystem.prototype.stop = function () {
  64187. this._stopped = true;
  64188. };
  64189. /**
  64190. * Remove all active particles
  64191. */
  64192. GPUParticleSystem.prototype.reset = function () {
  64193. this._releaseBuffers();
  64194. this._releaseVAOs();
  64195. this._currentActiveCount = 0;
  64196. this._targetIndex = 0;
  64197. };
  64198. /**
  64199. * Returns the string "GPUParticleSystem"
  64200. * @returns a string containing the class name
  64201. */
  64202. GPUParticleSystem.prototype.getClassName = function () {
  64203. return "GPUParticleSystem";
  64204. };
  64205. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64206. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64207. this._releaseBuffers();
  64208. return this;
  64209. };
  64210. /**
  64211. * Adds a new color gradient
  64212. * @param gradient defines the gradient to use (between 0 and 1)
  64213. * @param color1 defines the color to affect to the specified gradient
  64214. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64215. * @returns the current particle system
  64216. */
  64217. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64218. if (!this._colorGradients) {
  64219. this._colorGradients = [];
  64220. }
  64221. var colorGradient = new BABYLON.ColorGradient();
  64222. colorGradient.gradient = gradient;
  64223. colorGradient.color1 = color1;
  64224. this._colorGradients.push(colorGradient);
  64225. this._colorGradients.sort(function (a, b) {
  64226. if (a.gradient < b.gradient) {
  64227. return -1;
  64228. }
  64229. else if (a.gradient > b.gradient) {
  64230. return 1;
  64231. }
  64232. return 0;
  64233. });
  64234. if (this._colorGradientsTexture) {
  64235. this._colorGradientsTexture.dispose();
  64236. this._colorGradientsTexture = null;
  64237. }
  64238. this._releaseBuffers();
  64239. return this;
  64240. };
  64241. /**
  64242. * Remove a specific color gradient
  64243. * @param gradient defines the gradient to remove
  64244. * @returns the current particle system
  64245. */
  64246. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64247. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64248. this._colorGradientsTexture = null;
  64249. return this;
  64250. };
  64251. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64252. var valueGradient = new BABYLON.FactorGradient();
  64253. valueGradient.gradient = gradient;
  64254. valueGradient.factor1 = factor;
  64255. factorGradients.push(valueGradient);
  64256. factorGradients.sort(function (a, b) {
  64257. if (a.gradient < b.gradient) {
  64258. return -1;
  64259. }
  64260. else if (a.gradient > b.gradient) {
  64261. return 1;
  64262. }
  64263. return 0;
  64264. });
  64265. this._releaseBuffers();
  64266. };
  64267. /**
  64268. * Adds a new size gradient
  64269. * @param gradient defines the gradient to use (between 0 and 1)
  64270. * @param factor defines the size factor to affect to the specified gradient
  64271. * @returns the current particle system
  64272. */
  64273. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64274. if (!this._sizeGradients) {
  64275. this._sizeGradients = [];
  64276. }
  64277. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64278. if (this._sizeGradientsTexture) {
  64279. this._sizeGradientsTexture.dispose();
  64280. this._sizeGradientsTexture = null;
  64281. }
  64282. this._releaseBuffers();
  64283. return this;
  64284. };
  64285. /**
  64286. * Remove a specific size gradient
  64287. * @param gradient defines the gradient to remove
  64288. * @returns the current particle system
  64289. */
  64290. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64291. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64292. this._sizeGradientsTexture = null;
  64293. return this;
  64294. };
  64295. /**
  64296. * Adds a new angular speed gradient
  64297. * @param gradient defines the gradient to use (between 0 and 1)
  64298. * @param factor defines the angular speed to affect to the specified gradient
  64299. * @returns the current particle system
  64300. */
  64301. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64302. if (!this._angularSpeedGradients) {
  64303. this._angularSpeedGradients = [];
  64304. }
  64305. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64306. if (this._angularSpeedGradientsTexture) {
  64307. this._angularSpeedGradientsTexture.dispose();
  64308. this._angularSpeedGradientsTexture = null;
  64309. }
  64310. this._releaseBuffers();
  64311. return this;
  64312. };
  64313. /**
  64314. * Remove a specific angular speed gradient
  64315. * @param gradient defines the gradient to remove
  64316. * @returns the current particle system
  64317. */
  64318. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64319. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64320. this._angularSpeedGradientsTexture = null;
  64321. return this;
  64322. };
  64323. /**
  64324. * Adds a new velocity gradient
  64325. * @param gradient defines the gradient to use (between 0 and 1)
  64326. * @param factor defines the velocity to affect to the specified gradient
  64327. * @returns the current particle system
  64328. */
  64329. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64330. if (!this._velocityGradients) {
  64331. this._velocityGradients = [];
  64332. }
  64333. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64334. if (this._velocityGradientsTexture) {
  64335. this._velocityGradientsTexture.dispose();
  64336. this._velocityGradientsTexture = null;
  64337. }
  64338. this._releaseBuffers();
  64339. return this;
  64340. };
  64341. /**
  64342. * Remove a specific velocity gradient
  64343. * @param gradient defines the gradient to remove
  64344. * @returns the current particle system
  64345. */
  64346. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64347. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64348. this._velocityGradientsTexture = null;
  64349. return this;
  64350. };
  64351. /**
  64352. * Adds a new limit velocity gradient
  64353. * @param gradient defines the gradient to use (between 0 and 1)
  64354. * @param factor defines the limit velocity value to affect to the specified gradient
  64355. * @returns the current particle system
  64356. */
  64357. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64358. if (!this._limitVelocityGradients) {
  64359. this._limitVelocityGradients = [];
  64360. }
  64361. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64362. if (this._limitVelocityGradientsTexture) {
  64363. this._limitVelocityGradientsTexture.dispose();
  64364. this._limitVelocityGradientsTexture = null;
  64365. }
  64366. this._releaseBuffers();
  64367. return this;
  64368. };
  64369. /**
  64370. * Remove a specific limit velocity gradient
  64371. * @param gradient defines the gradient to remove
  64372. * @returns the current particle system
  64373. */
  64374. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64375. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64376. this._limitVelocityGradientsTexture = null;
  64377. return this;
  64378. };
  64379. /**
  64380. * Adds a new drag gradient
  64381. * @param gradient defines the gradient to use (between 0 and 1)
  64382. * @param factor defines the drag value to affect to the specified gradient
  64383. * @returns the current particle system
  64384. */
  64385. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64386. if (!this._dragGradients) {
  64387. this._dragGradients = [];
  64388. }
  64389. this._addFactorGradient(this._dragGradients, gradient, factor);
  64390. if (this._dragGradientsTexture) {
  64391. this._dragGradientsTexture.dispose();
  64392. this._dragGradientsTexture = null;
  64393. }
  64394. this._releaseBuffers();
  64395. return this;
  64396. };
  64397. /**
  64398. * Remove a specific drag gradient
  64399. * @param gradient defines the gradient to remove
  64400. * @returns the current particle system
  64401. */
  64402. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64403. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64404. this._dragGradientsTexture = null;
  64405. return this;
  64406. };
  64407. /**
  64408. * Not supported by GPUParticleSystem
  64409. * @param gradient defines the gradient to use (between 0 and 1)
  64410. * @param factor defines the emit rate value to affect to the specified gradient
  64411. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64412. * @returns the current particle system
  64413. */
  64414. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64415. // Do nothing as emit rate is not supported by GPUParticleSystem
  64416. return this;
  64417. };
  64418. /**
  64419. * Not supported by GPUParticleSystem
  64420. * @param gradient defines the gradient to remove
  64421. * @returns the current particle system
  64422. */
  64423. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64424. // Do nothing as emit rate is not supported by GPUParticleSystem
  64425. return this;
  64426. };
  64427. /**
  64428. * Not supported by GPUParticleSystem
  64429. * @param gradient defines the gradient to use (between 0 and 1)
  64430. * @param factor defines the start size value to affect to the specified gradient
  64431. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64432. * @returns the current particle system
  64433. */
  64434. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64435. // Do nothing as start size is not supported by GPUParticleSystem
  64436. return this;
  64437. };
  64438. /**
  64439. * Not supported by GPUParticleSystem
  64440. * @param gradient defines the gradient to remove
  64441. * @returns the current particle system
  64442. */
  64443. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64444. // Do nothing as start size is not supported by GPUParticleSystem
  64445. return this;
  64446. };
  64447. /**
  64448. * Not supported by GPUParticleSystem
  64449. * @param gradient defines the gradient to use (between 0 and 1)
  64450. * @param min defines the color remap minimal range
  64451. * @param max defines the color remap maximal range
  64452. * @returns the current particle system
  64453. */
  64454. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64455. // Do nothing as start size is not supported by GPUParticleSystem
  64456. return this;
  64457. };
  64458. /**
  64459. * Not supported by GPUParticleSystem
  64460. * @param gradient defines the gradient to remove
  64461. * @returns the current particle system
  64462. */
  64463. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64464. // Do nothing as start size is not supported by GPUParticleSystem
  64465. return this;
  64466. };
  64467. /**
  64468. * Not supported by GPUParticleSystem
  64469. * @param gradient defines the gradient to use (between 0 and 1)
  64470. * @param min defines the alpha remap minimal range
  64471. * @param max defines the alpha remap maximal range
  64472. * @returns the current particle system
  64473. */
  64474. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64475. // Do nothing as start size is not supported by GPUParticleSystem
  64476. return this;
  64477. };
  64478. /**
  64479. * Not supported by GPUParticleSystem
  64480. * @param gradient defines the gradient to remove
  64481. * @returns the current particle system
  64482. */
  64483. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64484. // Do nothing as start size is not supported by GPUParticleSystem
  64485. return this;
  64486. };
  64487. /**
  64488. * Not supported by GPUParticleSystem
  64489. * @param gradient defines the gradient to use (between 0 and 1)
  64490. * @param color defines the color to affect to the specified gradient
  64491. * @returns the current particle system
  64492. */
  64493. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64494. //Not supported by GPUParticleSystem
  64495. return this;
  64496. };
  64497. /**
  64498. * Not supported by GPUParticleSystem
  64499. * @param gradient defines the gradient to remove
  64500. * @returns the current particle system
  64501. */
  64502. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64503. //Not supported by GPUParticleSystem
  64504. return this;
  64505. };
  64506. /**
  64507. * Not supported by GPUParticleSystem
  64508. * @returns the list of ramp gradients
  64509. */
  64510. GPUParticleSystem.prototype.getRampGradients = function () {
  64511. return null;
  64512. };
  64513. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64514. /**
  64515. * Not supported by GPUParticleSystem
  64516. * Gets or sets a boolean indicating that ramp gradients must be used
  64517. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64518. */
  64519. get: function () {
  64520. //Not supported by GPUParticleSystem
  64521. return false;
  64522. },
  64523. set: function (value) {
  64524. //Not supported by GPUParticleSystem
  64525. },
  64526. enumerable: true,
  64527. configurable: true
  64528. });
  64529. /**
  64530. * Not supported by GPUParticleSystem
  64531. * @param gradient defines the gradient to use (between 0 and 1)
  64532. * @param factor defines the life time factor to affect to the specified gradient
  64533. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64534. * @returns the current particle system
  64535. */
  64536. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64537. //Not supported by GPUParticleSystem
  64538. return this;
  64539. };
  64540. /**
  64541. * Not supported by GPUParticleSystem
  64542. * @param gradient defines the gradient to remove
  64543. * @returns the current particle system
  64544. */
  64545. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64546. //Not supported by GPUParticleSystem
  64547. return this;
  64548. };
  64549. GPUParticleSystem.prototype._reset = function () {
  64550. this._releaseBuffers();
  64551. };
  64552. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64553. var updateVertexBuffers = {};
  64554. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64555. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64556. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64557. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64558. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64559. var offset = 12;
  64560. if (!this._colorGradientsTexture) {
  64561. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64562. offset += 4;
  64563. }
  64564. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64565. offset += 3;
  64566. if (!this._isBillboardBased) {
  64567. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64568. offset += 3;
  64569. }
  64570. if (this._angularSpeedGradientsTexture) {
  64571. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64572. offset += 1;
  64573. }
  64574. else {
  64575. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64576. offset += 2;
  64577. }
  64578. if (this._isAnimationSheetEnabled) {
  64579. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64580. offset += 1;
  64581. if (this.spriteRandomStartCell) {
  64582. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64583. offset += 1;
  64584. }
  64585. }
  64586. if (this.noiseTexture) {
  64587. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64588. offset += 3;
  64589. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64590. offset += 3;
  64591. }
  64592. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64593. this._engine.bindArrayBuffer(null);
  64594. return vao;
  64595. };
  64596. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64597. var renderVertexBuffers = {};
  64598. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64599. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64600. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64601. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64602. var offset = 12;
  64603. if (!this._colorGradientsTexture) {
  64604. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64605. offset += 4;
  64606. }
  64607. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64608. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64609. }
  64610. offset += 3; // Direction
  64611. if (!this._isBillboardBased) {
  64612. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64613. offset += 3;
  64614. }
  64615. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64616. if (this._angularSpeedGradientsTexture) {
  64617. offset++;
  64618. }
  64619. else {
  64620. offset += 2;
  64621. }
  64622. if (this._isAnimationSheetEnabled) {
  64623. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64624. offset += 1;
  64625. if (this.spriteRandomStartCell) {
  64626. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64627. offset += 1;
  64628. }
  64629. }
  64630. if (this.noiseTexture) {
  64631. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64632. offset += 3;
  64633. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64634. offset += 3;
  64635. }
  64636. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64637. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64638. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64639. this._engine.bindArrayBuffer(null);
  64640. return vao;
  64641. };
  64642. GPUParticleSystem.prototype._initialize = function (force) {
  64643. if (force === void 0) { force = false; }
  64644. if (this._buffer0 && !force) {
  64645. return;
  64646. }
  64647. var engine = this._scene.getEngine();
  64648. var data = new Array();
  64649. if (!this.isBillboardBased) {
  64650. this._attributesStrideSize += 3;
  64651. }
  64652. if (this._colorGradientsTexture) {
  64653. this._attributesStrideSize -= 4;
  64654. }
  64655. if (this._angularSpeedGradientsTexture) {
  64656. this._attributesStrideSize -= 1;
  64657. }
  64658. if (this._isAnimationSheetEnabled) {
  64659. this._attributesStrideSize += 1;
  64660. if (this.spriteRandomStartCell) {
  64661. this._attributesStrideSize += 1;
  64662. }
  64663. }
  64664. if (this.noiseTexture) {
  64665. this._attributesStrideSize += 6;
  64666. }
  64667. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64668. // position
  64669. data.push(0.0);
  64670. data.push(0.0);
  64671. data.push(0.0);
  64672. // Age and life
  64673. data.push(0.0); // create the particle as a dead one to create a new one at start
  64674. data.push(0.0);
  64675. // Seed
  64676. data.push(Math.random());
  64677. data.push(Math.random());
  64678. data.push(Math.random());
  64679. data.push(Math.random());
  64680. // Size
  64681. data.push(0.0);
  64682. data.push(0.0);
  64683. data.push(0.0);
  64684. if (!this._colorGradientsTexture) {
  64685. // color
  64686. data.push(0.0);
  64687. data.push(0.0);
  64688. data.push(0.0);
  64689. data.push(0.0);
  64690. }
  64691. // direction
  64692. data.push(0.0);
  64693. data.push(0.0);
  64694. data.push(0.0);
  64695. if (!this.isBillboardBased) {
  64696. // initialDirection
  64697. data.push(0.0);
  64698. data.push(0.0);
  64699. data.push(0.0);
  64700. }
  64701. // angle
  64702. data.push(0.0);
  64703. if (!this._angularSpeedGradientsTexture) {
  64704. data.push(0.0);
  64705. }
  64706. if (this._isAnimationSheetEnabled) {
  64707. data.push(0.0);
  64708. if (this.spriteRandomStartCell) {
  64709. data.push(0.0);
  64710. }
  64711. }
  64712. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64713. data.push(Math.random());
  64714. data.push(Math.random());
  64715. data.push(Math.random());
  64716. data.push(Math.random());
  64717. data.push(Math.random());
  64718. data.push(Math.random());
  64719. }
  64720. }
  64721. // Sprite data
  64722. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64723. -0.5, 0.5, 0, 1,
  64724. -0.5, -0.5, 0, 0,
  64725. 0.5, -0.5, 1, 0]);
  64726. // Buffers
  64727. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64728. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64729. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64730. // Update VAO
  64731. this._updateVAO = [];
  64732. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64733. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64734. // Render VAO
  64735. this._renderVAO = [];
  64736. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64737. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64738. // Links
  64739. this._sourceBuffer = this._buffer0;
  64740. this._targetBuffer = this._buffer1;
  64741. };
  64742. /** @hidden */
  64743. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64744. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64745. if (this._isBillboardBased) {
  64746. defines += "\n#define BILLBOARD";
  64747. }
  64748. if (this._colorGradientsTexture) {
  64749. defines += "\n#define COLORGRADIENTS";
  64750. }
  64751. if (this._sizeGradientsTexture) {
  64752. defines += "\n#define SIZEGRADIENTS";
  64753. }
  64754. if (this._angularSpeedGradientsTexture) {
  64755. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64756. }
  64757. if (this._velocityGradientsTexture) {
  64758. defines += "\n#define VELOCITYGRADIENTS";
  64759. }
  64760. if (this._limitVelocityGradientsTexture) {
  64761. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64762. }
  64763. if (this._dragGradientsTexture) {
  64764. defines += "\n#define DRAGGRADIENTS";
  64765. }
  64766. if (this.isAnimationSheetEnabled) {
  64767. defines += "\n#define ANIMATESHEET";
  64768. if (this.spriteRandomStartCell) {
  64769. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64770. }
  64771. }
  64772. if (this.noiseTexture) {
  64773. defines += "\n#define NOISE";
  64774. }
  64775. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64776. return;
  64777. }
  64778. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64779. if (!this._colorGradientsTexture) {
  64780. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64781. }
  64782. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64783. if (!this._isBillboardBased) {
  64784. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64785. }
  64786. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64787. if (this.isAnimationSheetEnabled) {
  64788. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64789. if (this.spriteRandomStartCell) {
  64790. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64791. }
  64792. }
  64793. if (this.noiseTexture) {
  64794. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  64795. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  64796. }
  64797. this._updateEffectOptions.defines = defines;
  64798. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  64799. };
  64800. /** @hidden */
  64801. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  64802. var defines = "";
  64803. if (this._scene.clipPlane) {
  64804. defines = "\n#define CLIPPLANE";
  64805. }
  64806. if (this._scene.clipPlane2) {
  64807. defines = "\n#define CLIPPLANE2";
  64808. }
  64809. if (this._scene.clipPlane3) {
  64810. defines = "\n#define CLIPPLANE3";
  64811. }
  64812. if (this._scene.clipPlane4) {
  64813. defines = "\n#define CLIPPLANE4";
  64814. }
  64815. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  64816. defines = "\n#define BLENDMULTIPLYMODE";
  64817. }
  64818. if (this._isBillboardBased) {
  64819. defines += "\n#define BILLBOARD";
  64820. switch (this.billboardMode) {
  64821. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  64822. defines += "\n#define BILLBOARDY";
  64823. break;
  64824. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  64825. defines += "\n#define BILLBOARDSTRETCHED";
  64826. break;
  64827. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  64828. default:
  64829. break;
  64830. }
  64831. }
  64832. if (this._colorGradientsTexture) {
  64833. defines += "\n#define COLORGRADIENTS";
  64834. }
  64835. if (this.isAnimationSheetEnabled) {
  64836. defines += "\n#define ANIMATESHEET";
  64837. }
  64838. if (this._imageProcessingConfiguration) {
  64839. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  64840. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  64841. }
  64842. if (this._renderEffect && this._renderEffect.defines === defines) {
  64843. return;
  64844. }
  64845. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  64846. var samplers = ["textureSampler", "colorGradientSampler"];
  64847. if (BABYLON.ImageProcessingConfiguration) {
  64848. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  64849. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  64850. }
  64851. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  64852. };
  64853. /**
  64854. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  64855. * @param preWarm defines if we are in the pre-warmimg phase
  64856. */
  64857. GPUParticleSystem.prototype.animate = function (preWarm) {
  64858. if (preWarm === void 0) { preWarm = false; }
  64859. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  64860. this._actualFrame += this._timeDelta;
  64861. if (!this._stopped) {
  64862. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  64863. this.stop();
  64864. }
  64865. }
  64866. };
  64867. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  64868. var texture = this[textureName];
  64869. if (!factorGradients || !factorGradients.length || texture) {
  64870. return;
  64871. }
  64872. var data = new Float32Array(this._rawTextureWidth);
  64873. for (var x = 0; x < this._rawTextureWidth; x++) {
  64874. var ratio = x / this._rawTextureWidth;
  64875. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  64876. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  64877. });
  64878. }
  64879. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64880. };
  64881. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  64882. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  64883. };
  64884. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  64885. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  64886. };
  64887. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  64888. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  64889. };
  64890. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  64891. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  64892. };
  64893. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  64894. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  64895. };
  64896. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  64897. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  64898. return;
  64899. }
  64900. var data = new Uint8Array(this._rawTextureWidth * 4);
  64901. var tmpColor = BABYLON.Tmp.Color4[0];
  64902. for (var x = 0; x < this._rawTextureWidth; x++) {
  64903. var ratio = x / this._rawTextureWidth;
  64904. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  64905. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  64906. data[x * 4] = tmpColor.r * 255;
  64907. data[x * 4 + 1] = tmpColor.g * 255;
  64908. data[x * 4 + 2] = tmpColor.b * 255;
  64909. data[x * 4 + 3] = tmpColor.a * 255;
  64910. });
  64911. }
  64912. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64913. };
  64914. /**
  64915. * Renders the particle system in its current state
  64916. * @param preWarm defines if the system should only update the particles but not render them
  64917. * @returns the current number of particles
  64918. */
  64919. GPUParticleSystem.prototype.render = function (preWarm) {
  64920. if (preWarm === void 0) { preWarm = false; }
  64921. if (!this._started) {
  64922. return 0;
  64923. }
  64924. this._createColorGradientTexture();
  64925. this._createSizeGradientTexture();
  64926. this._createAngularSpeedGradientTexture();
  64927. this._createVelocityGradientTexture();
  64928. this._createLimitVelocityGradientTexture();
  64929. this._createDragGradientTexture();
  64930. this._recreateUpdateEffect();
  64931. this._recreateRenderEffect();
  64932. if (!this.isReady()) {
  64933. return 0;
  64934. }
  64935. if (!preWarm) {
  64936. if (!this._preWarmDone && this.preWarmCycles) {
  64937. for (var index = 0; index < this.preWarmCycles; index++) {
  64938. this.animate(true);
  64939. this.render(true);
  64940. }
  64941. this._preWarmDone = true;
  64942. }
  64943. if (this._currentRenderId === this._scene.getRenderId()) {
  64944. return 0;
  64945. }
  64946. this._currentRenderId = this._scene.getRenderId();
  64947. }
  64948. // Get everything ready to render
  64949. this._initialize();
  64950. this._accumulatedCount += this.emitRate * this._timeDelta;
  64951. if (this._accumulatedCount > 1) {
  64952. var intPart = this._accumulatedCount | 0;
  64953. this._accumulatedCount -= intPart;
  64954. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64955. }
  64956. if (!this._currentActiveCount) {
  64957. return 0;
  64958. }
  64959. // Enable update effect
  64960. this._engine.enableEffect(this._updateEffect);
  64961. this._engine.setState(false);
  64962. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64963. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64964. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64965. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64966. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64967. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64968. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64969. if (!this._colorGradientsTexture) {
  64970. this._updateEffect.setDirectColor4("color1", this.color1);
  64971. this._updateEffect.setDirectColor4("color2", this.color2);
  64972. }
  64973. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64974. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64975. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64976. this._updateEffect.setVector3("gravity", this.gravity);
  64977. if (this._sizeGradientsTexture) {
  64978. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64979. }
  64980. if (this._angularSpeedGradientsTexture) {
  64981. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64982. }
  64983. if (this._velocityGradientsTexture) {
  64984. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64985. }
  64986. if (this._limitVelocityGradientsTexture) {
  64987. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64988. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64989. }
  64990. if (this._dragGradientsTexture) {
  64991. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64992. }
  64993. if (this.particleEmitterType) {
  64994. this.particleEmitterType.applyToShader(this._updateEffect);
  64995. }
  64996. if (this._isAnimationSheetEnabled) {
  64997. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64998. }
  64999. if (this.noiseTexture) {
  65000. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65001. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65002. }
  65003. var emitterWM;
  65004. if (this.emitter.position) {
  65005. var emitterMesh = this.emitter;
  65006. emitterWM = emitterMesh.getWorldMatrix();
  65007. }
  65008. else {
  65009. var emitterPosition = this.emitter;
  65010. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65011. }
  65012. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65013. // Bind source VAO
  65014. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65015. // Update
  65016. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65017. this._engine.setRasterizerState(false);
  65018. this._engine.beginTransformFeedback(true);
  65019. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65020. this._engine.endTransformFeedback();
  65021. this._engine.setRasterizerState(true);
  65022. this._engine.bindTransformFeedbackBuffer(null);
  65023. if (!preWarm) {
  65024. // Enable render effect
  65025. this._engine.enableEffect(this._renderEffect);
  65026. var viewMatrix = this._scene.getViewMatrix();
  65027. this._renderEffect.setMatrix("view", viewMatrix);
  65028. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65029. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65030. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65031. if (this._colorGradientsTexture) {
  65032. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65033. }
  65034. else {
  65035. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65036. }
  65037. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65038. var baseSize = this.particleTexture.getBaseSize();
  65039. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65040. }
  65041. if (this._isBillboardBased) {
  65042. var camera = this._scene.activeCamera;
  65043. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65044. }
  65045. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65046. var invView = viewMatrix.clone();
  65047. invView.invert();
  65048. this._renderEffect.setMatrix("invView", invView);
  65049. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65050. }
  65051. // image processing
  65052. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65053. this._imageProcessingConfiguration.bind(this._renderEffect);
  65054. }
  65055. // Draw order
  65056. switch (this.blendMode) {
  65057. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65058. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65059. break;
  65060. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65061. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65062. break;
  65063. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65064. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65065. break;
  65066. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65067. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65068. break;
  65069. }
  65070. if (this.forceDepthWrite) {
  65071. this._engine.setDepthWrite(true);
  65072. }
  65073. // Bind source VAO
  65074. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65075. // Render
  65076. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65077. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65078. }
  65079. // Switch VAOs
  65080. this._targetIndex++;
  65081. if (this._targetIndex === 2) {
  65082. this._targetIndex = 0;
  65083. }
  65084. // Switch buffers
  65085. var tmpBuffer = this._sourceBuffer;
  65086. this._sourceBuffer = this._targetBuffer;
  65087. this._targetBuffer = tmpBuffer;
  65088. return this._currentActiveCount;
  65089. };
  65090. /**
  65091. * Rebuilds the particle system
  65092. */
  65093. GPUParticleSystem.prototype.rebuild = function () {
  65094. this._initialize(true);
  65095. };
  65096. GPUParticleSystem.prototype._releaseBuffers = function () {
  65097. if (this._buffer0) {
  65098. this._buffer0.dispose();
  65099. this._buffer0 = null;
  65100. }
  65101. if (this._buffer1) {
  65102. this._buffer1.dispose();
  65103. this._buffer1 = null;
  65104. }
  65105. if (this._spriteBuffer) {
  65106. this._spriteBuffer.dispose();
  65107. this._spriteBuffer = null;
  65108. }
  65109. };
  65110. GPUParticleSystem.prototype._releaseVAOs = function () {
  65111. if (!this._updateVAO) {
  65112. return;
  65113. }
  65114. for (var index = 0; index < this._updateVAO.length; index++) {
  65115. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65116. }
  65117. this._updateVAO = [];
  65118. for (var index = 0; index < this._renderVAO.length; index++) {
  65119. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65120. }
  65121. this._renderVAO = [];
  65122. };
  65123. /**
  65124. * Disposes the particle system and free the associated resources
  65125. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65126. */
  65127. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65128. if (disposeTexture === void 0) { disposeTexture = true; }
  65129. var index = this._scene.particleSystems.indexOf(this);
  65130. if (index > -1) {
  65131. this._scene.particleSystems.splice(index, 1);
  65132. }
  65133. this._releaseBuffers();
  65134. this._releaseVAOs();
  65135. if (this._colorGradientsTexture) {
  65136. this._colorGradientsTexture.dispose();
  65137. this._colorGradientsTexture = null;
  65138. }
  65139. if (this._sizeGradientsTexture) {
  65140. this._sizeGradientsTexture.dispose();
  65141. this._sizeGradientsTexture = null;
  65142. }
  65143. if (this._angularSpeedGradientsTexture) {
  65144. this._angularSpeedGradientsTexture.dispose();
  65145. this._angularSpeedGradientsTexture = null;
  65146. }
  65147. if (this._velocityGradientsTexture) {
  65148. this._velocityGradientsTexture.dispose();
  65149. this._velocityGradientsTexture = null;
  65150. }
  65151. if (this._limitVelocityGradientsTexture) {
  65152. this._limitVelocityGradientsTexture.dispose();
  65153. this._limitVelocityGradientsTexture = null;
  65154. }
  65155. if (this._dragGradientsTexture) {
  65156. this._dragGradientsTexture.dispose();
  65157. this._dragGradientsTexture = null;
  65158. }
  65159. if (this._randomTexture) {
  65160. this._randomTexture.dispose();
  65161. this._randomTexture = null;
  65162. }
  65163. if (this._randomTexture2) {
  65164. this._randomTexture2.dispose();
  65165. this._randomTexture2 = null;
  65166. }
  65167. if (disposeTexture && this.particleTexture) {
  65168. this.particleTexture.dispose();
  65169. this.particleTexture = null;
  65170. }
  65171. if (disposeTexture && this.noiseTexture) {
  65172. this.noiseTexture.dispose();
  65173. this.noiseTexture = null;
  65174. }
  65175. // Callback
  65176. this.onDisposeObservable.notifyObservers(this);
  65177. this.onDisposeObservable.clear();
  65178. };
  65179. /**
  65180. * Clones the particle system.
  65181. * @param name The name of the cloned object
  65182. * @param newEmitter The new emitter to use
  65183. * @returns the cloned particle system
  65184. */
  65185. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65186. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65187. BABYLON.Tools.DeepCopy(this, result);
  65188. if (newEmitter === undefined) {
  65189. newEmitter = this.emitter;
  65190. }
  65191. result.emitter = newEmitter;
  65192. if (this.particleTexture) {
  65193. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65194. }
  65195. return result;
  65196. };
  65197. /**
  65198. * Serializes the particle system to a JSON object.
  65199. * @returns the JSON object
  65200. */
  65201. GPUParticleSystem.prototype.serialize = function () {
  65202. var serializationObject = {};
  65203. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65204. serializationObject.activeParticleCount = this.activeParticleCount;
  65205. return serializationObject;
  65206. };
  65207. /**
  65208. * Parses a JSON object to create a GPU particle system.
  65209. * @param parsedParticleSystem The JSON object to parse
  65210. * @param scene The scene to create the particle system in
  65211. * @param rootUrl The root url to use to load external dependencies like texture
  65212. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65213. * @returns the parsed GPU particle system
  65214. */
  65215. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65216. if (doNotStart === void 0) { doNotStart = false; }
  65217. var name = parsedParticleSystem.name;
  65218. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65219. if (parsedParticleSystem.activeParticleCount) {
  65220. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65221. }
  65222. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65223. // Auto start
  65224. if (parsedParticleSystem.preventAutoStart) {
  65225. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65226. }
  65227. if (!doNotStart && !particleSystem.preventAutoStart) {
  65228. particleSystem.start();
  65229. }
  65230. return particleSystem;
  65231. };
  65232. return GPUParticleSystem;
  65233. }(BABYLON.BaseParticleSystem));
  65234. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65235. })(BABYLON || (BABYLON = {}));
  65236. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65237. var BABYLON;
  65238. (function (BABYLON) {
  65239. /**
  65240. * Represents one particle of a solid particle system.
  65241. */
  65242. var SolidParticle = /** @class */ (function () {
  65243. /**
  65244. * Creates a Solid Particle object.
  65245. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65246. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65247. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65248. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65249. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65250. * @param shapeId (integer) is the model shape identifier in the SPS.
  65251. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65252. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65253. */
  65254. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65255. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65256. /**
  65257. * particle global index
  65258. */
  65259. this.idx = 0;
  65260. /**
  65261. * The color of the particle
  65262. */
  65263. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65264. /**
  65265. * The world space position of the particle.
  65266. */
  65267. this.position = BABYLON.Vector3.Zero();
  65268. /**
  65269. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65270. */
  65271. this.rotation = BABYLON.Vector3.Zero();
  65272. /**
  65273. * The scaling of the particle.
  65274. */
  65275. this.scaling = BABYLON.Vector3.One();
  65276. /**
  65277. * The uvs of the particle.
  65278. */
  65279. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65280. /**
  65281. * The current speed of the particle.
  65282. */
  65283. this.velocity = BABYLON.Vector3.Zero();
  65284. /**
  65285. * The pivot point in the particle local space.
  65286. */
  65287. this.pivot = BABYLON.Vector3.Zero();
  65288. /**
  65289. * Must the particle be translated from its pivot point in its local space ?
  65290. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65291. * Default : false
  65292. */
  65293. this.translateFromPivot = false;
  65294. /**
  65295. * Is the particle active or not ?
  65296. */
  65297. this.alive = true;
  65298. /**
  65299. * Is the particle visible or not ?
  65300. */
  65301. this.isVisible = true;
  65302. /**
  65303. * Index of this particle in the global "positions" array (Internal use)
  65304. * @hidden
  65305. */
  65306. this._pos = 0;
  65307. /**
  65308. * @hidden Index of this particle in the global "indices" array (Internal use)
  65309. */
  65310. this._ind = 0;
  65311. /**
  65312. * ModelShape id of this particle
  65313. */
  65314. this.shapeId = 0;
  65315. /**
  65316. * Index of the particle in its shape id (Internal use)
  65317. */
  65318. this.idxInShape = 0;
  65319. /**
  65320. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65321. */
  65322. this._stillInvisible = false;
  65323. /**
  65324. * @hidden Last computed particle rotation matrix
  65325. */
  65326. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65327. /**
  65328. * Parent particle Id, if any.
  65329. * Default null.
  65330. */
  65331. this.parentId = null;
  65332. /**
  65333. * @hidden Internal global position in the SPS.
  65334. */
  65335. this._globalPosition = BABYLON.Vector3.Zero();
  65336. this.idx = particleIndex;
  65337. this._pos = positionIndex;
  65338. this._ind = indiceIndex;
  65339. this._model = model;
  65340. this.shapeId = shapeId;
  65341. this.idxInShape = idxInShape;
  65342. this._sps = sps;
  65343. if (modelBoundingInfo) {
  65344. this._modelBoundingInfo = modelBoundingInfo;
  65345. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65346. }
  65347. }
  65348. Object.defineProperty(SolidParticle.prototype, "scale", {
  65349. /**
  65350. * Legacy support, changed scale to scaling
  65351. */
  65352. get: function () {
  65353. return this.scaling;
  65354. },
  65355. /**
  65356. * Legacy support, changed scale to scaling
  65357. */
  65358. set: function (scale) {
  65359. this.scaling = scale;
  65360. },
  65361. enumerable: true,
  65362. configurable: true
  65363. });
  65364. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65365. /**
  65366. * Legacy support, changed quaternion to rotationQuaternion
  65367. */
  65368. get: function () {
  65369. return this.rotationQuaternion;
  65370. },
  65371. /**
  65372. * Legacy support, changed quaternion to rotationQuaternion
  65373. */
  65374. set: function (q) {
  65375. this.rotationQuaternion = q;
  65376. },
  65377. enumerable: true,
  65378. configurable: true
  65379. });
  65380. /**
  65381. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65382. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65383. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65384. * @returns true if it intersects
  65385. */
  65386. SolidParticle.prototype.intersectsMesh = function (target) {
  65387. if (!this._boundingInfo || !target._boundingInfo) {
  65388. return false;
  65389. }
  65390. if (this._sps._bSphereOnly) {
  65391. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65392. }
  65393. return this._boundingInfo.intersects(target._boundingInfo, false);
  65394. };
  65395. return SolidParticle;
  65396. }());
  65397. BABYLON.SolidParticle = SolidParticle;
  65398. /**
  65399. * Represents the shape of the model used by one particle of a solid particle system.
  65400. * SPS internal tool, don't use it manually.
  65401. */
  65402. var ModelShape = /** @class */ (function () {
  65403. /**
  65404. * 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.
  65405. * SPS internal tool, don't use it manually.
  65406. * @hidden
  65407. */
  65408. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65409. /**
  65410. * length of the shape in the model indices array (internal use)
  65411. * @hidden
  65412. */
  65413. this._indicesLength = 0;
  65414. this.shapeID = id;
  65415. this._shape = shape;
  65416. this._indicesLength = indicesLength;
  65417. this._shapeUV = shapeUV;
  65418. this._positionFunction = posFunction;
  65419. this._vertexFunction = vtxFunction;
  65420. }
  65421. return ModelShape;
  65422. }());
  65423. BABYLON.ModelShape = ModelShape;
  65424. /**
  65425. * Represents a Depth Sorted Particle in the solid particle system.
  65426. */
  65427. var DepthSortedParticle = /** @class */ (function () {
  65428. function DepthSortedParticle() {
  65429. /**
  65430. * Index of the particle in the "indices" array
  65431. */
  65432. this.ind = 0;
  65433. /**
  65434. * Length of the particle shape in the "indices" array
  65435. */
  65436. this.indicesLength = 0;
  65437. /**
  65438. * Squared distance from the particle to the camera
  65439. */
  65440. this.sqDistance = 0.0;
  65441. }
  65442. return DepthSortedParticle;
  65443. }());
  65444. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65445. })(BABYLON || (BABYLON = {}));
  65446. //# sourceMappingURL=babylon.solidParticle.js.map
  65447. var BABYLON;
  65448. (function (BABYLON) {
  65449. /**
  65450. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65451. *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.
  65452. * The SPS is also a particle system. It provides some methods to manage the particles.
  65453. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65454. *
  65455. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65456. */
  65457. var SolidParticleSystem = /** @class */ (function () {
  65458. /**
  65459. * Creates a SPS (Solid Particle System) object.
  65460. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65461. * @param scene (Scene) is the scene in which the SPS is added.
  65462. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65463. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65464. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65465. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65466. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65467. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65468. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65469. */
  65470. function SolidParticleSystem(name, scene, options) {
  65471. /**
  65472. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65473. * Example : var p = SPS.particles[i];
  65474. */
  65475. this.particles = new Array();
  65476. /**
  65477. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65478. */
  65479. this.nbParticles = 0;
  65480. /**
  65481. * If the particles must ever face the camera (default false). Useful for planar particles.
  65482. */
  65483. this.billboard = false;
  65484. /**
  65485. * Recompute normals when adding a shape
  65486. */
  65487. this.recomputeNormals = true;
  65488. /**
  65489. * This a counter ofr your own usage. It's not set by any SPS functions.
  65490. */
  65491. this.counter = 0;
  65492. /**
  65493. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65494. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65495. */
  65496. this.vars = {};
  65497. /**
  65498. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65499. * @hidden
  65500. */
  65501. this._bSphereOnly = false;
  65502. /**
  65503. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65504. * @hidden
  65505. */
  65506. this._bSphereRadiusFactor = 1.0;
  65507. this._positions = new Array();
  65508. this._indices = new Array();
  65509. this._normals = new Array();
  65510. this._colors = new Array();
  65511. this._uvs = new Array();
  65512. this._index = 0; // indices index
  65513. this._updatable = true;
  65514. this._pickable = false;
  65515. this._isVisibilityBoxLocked = false;
  65516. this._alwaysVisible = false;
  65517. this._depthSort = false;
  65518. this._shapeCounter = 0;
  65519. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65520. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65521. this._computeParticleColor = true;
  65522. this._computeParticleTexture = true;
  65523. this._computeParticleRotation = true;
  65524. this._computeParticleVertex = false;
  65525. this._computeBoundingBox = false;
  65526. this._depthSortParticles = true;
  65527. this._cam_axisZ = BABYLON.Vector3.Zero();
  65528. this._cam_axisY = BABYLON.Vector3.Zero();
  65529. this._cam_axisX = BABYLON.Vector3.Zero();
  65530. this._axisZ = BABYLON.Axis.Z;
  65531. this._camDir = BABYLON.Vector3.Zero();
  65532. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65533. this._rotMatrix = new BABYLON.Matrix();
  65534. this._invertMatrix = new BABYLON.Matrix();
  65535. this._rotated = BABYLON.Vector3.Zero();
  65536. this._quaternion = new BABYLON.Quaternion();
  65537. this._vertex = BABYLON.Vector3.Zero();
  65538. this._normal = BABYLON.Vector3.Zero();
  65539. this._yaw = 0.0;
  65540. this._pitch = 0.0;
  65541. this._roll = 0.0;
  65542. this._halfroll = 0.0;
  65543. this._halfpitch = 0.0;
  65544. this._halfyaw = 0.0;
  65545. this._sinRoll = 0.0;
  65546. this._cosRoll = 0.0;
  65547. this._sinPitch = 0.0;
  65548. this._cosPitch = 0.0;
  65549. this._sinYaw = 0.0;
  65550. this._cosYaw = 0.0;
  65551. this._mustUnrotateFixedNormals = false;
  65552. this._minimum = BABYLON.Vector3.Zero();
  65553. this._maximum = BABYLON.Vector3.Zero();
  65554. this._minBbox = BABYLON.Vector3.Zero();
  65555. this._maxBbox = BABYLON.Vector3.Zero();
  65556. this._particlesIntersect = false;
  65557. this._depthSortFunction = function (p1, p2) {
  65558. return (p2.sqDistance - p1.sqDistance);
  65559. };
  65560. this._needs32Bits = false;
  65561. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65562. this._scaledPivot = BABYLON.Vector3.Zero();
  65563. this._particleHasParent = false;
  65564. this.name = name;
  65565. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65566. this._camera = scene.activeCamera;
  65567. this._pickable = options ? options.isPickable : false;
  65568. this._depthSort = options ? options.enableDepthSort : false;
  65569. this._particlesIntersect = options ? options.particleIntersection : false;
  65570. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65571. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65572. if (options && options.updatable !== undefined) {
  65573. this._updatable = options.updatable;
  65574. }
  65575. else {
  65576. this._updatable = true;
  65577. }
  65578. if (this._pickable) {
  65579. this.pickedParticles = [];
  65580. }
  65581. if (this._depthSort) {
  65582. this.depthSortedParticles = [];
  65583. }
  65584. }
  65585. /**
  65586. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65587. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65588. * @returns the created mesh
  65589. */
  65590. SolidParticleSystem.prototype.buildMesh = function () {
  65591. if (this.nbParticles === 0) {
  65592. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65593. this.addShape(triangle, 1);
  65594. triangle.dispose();
  65595. }
  65596. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65597. this._positions32 = new Float32Array(this._positions);
  65598. this._uvs32 = new Float32Array(this._uvs);
  65599. this._colors32 = new Float32Array(this._colors);
  65600. if (this.recomputeNormals) {
  65601. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65602. }
  65603. this._normals32 = new Float32Array(this._normals);
  65604. this._fixedNormal32 = new Float32Array(this._normals);
  65605. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65606. this._unrotateFixedNormals();
  65607. }
  65608. var vertexData = new BABYLON.VertexData();
  65609. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65610. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65611. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65612. if (this._uvs32.length > 0) {
  65613. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65614. }
  65615. if (this._colors32.length > 0) {
  65616. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65617. }
  65618. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65619. vertexData.applyToMesh(mesh, this._updatable);
  65620. this.mesh = mesh;
  65621. this.mesh.isPickable = this._pickable;
  65622. // free memory
  65623. if (!this._depthSort) {
  65624. this._indices = null;
  65625. }
  65626. this._positions = null;
  65627. this._normals = null;
  65628. this._uvs = null;
  65629. this._colors = null;
  65630. if (!this._updatable) {
  65631. this.particles.length = 0;
  65632. }
  65633. return mesh;
  65634. };
  65635. /**
  65636. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65637. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65638. * Thus the particles generated from `digest()` have their property `position` set yet.
  65639. * @param mesh ( Mesh ) is the mesh to be digested
  65640. * @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
  65641. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65642. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65643. * @returns the current SPS
  65644. */
  65645. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65646. var size = (options && options.facetNb) || 1;
  65647. var number = (options && options.number) || 0;
  65648. var delta = (options && options.delta) || 0;
  65649. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65650. var meshInd = mesh.getIndices();
  65651. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65652. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65653. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65654. var f = 0; // facet counter
  65655. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65656. // compute size from number
  65657. if (number) {
  65658. number = (number > totalFacets) ? totalFacets : number;
  65659. size = Math.round(totalFacets / number);
  65660. delta = 0;
  65661. }
  65662. else {
  65663. size = (size > totalFacets) ? totalFacets : size;
  65664. }
  65665. var facetPos = []; // submesh positions
  65666. var facetInd = []; // submesh indices
  65667. var facetUV = []; // submesh UV
  65668. var facetCol = []; // submesh colors
  65669. var barycenter = BABYLON.Vector3.Zero();
  65670. var sizeO = size;
  65671. while (f < totalFacets) {
  65672. size = sizeO + Math.floor((1 + delta) * Math.random());
  65673. if (f > totalFacets - size) {
  65674. size = totalFacets - f;
  65675. }
  65676. // reset temp arrays
  65677. facetPos.length = 0;
  65678. facetInd.length = 0;
  65679. facetUV.length = 0;
  65680. facetCol.length = 0;
  65681. // iterate over "size" facets
  65682. var fi = 0;
  65683. for (var j = f * 3; j < (f + size) * 3; j++) {
  65684. facetInd.push(fi);
  65685. var i = meshInd[j];
  65686. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65687. if (meshUV) {
  65688. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65689. }
  65690. if (meshCol) {
  65691. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65692. }
  65693. fi++;
  65694. }
  65695. // create a model shape for each single particle
  65696. var idx = this.nbParticles;
  65697. var shape = this._posToShape(facetPos);
  65698. var shapeUV = this._uvsToShapeUV(facetUV);
  65699. // compute the barycenter of the shape
  65700. var v;
  65701. for (v = 0; v < shape.length; v++) {
  65702. barycenter.addInPlace(shape[v]);
  65703. }
  65704. barycenter.scaleInPlace(1 / shape.length);
  65705. // shift the shape from its barycenter to the origin
  65706. for (v = 0; v < shape.length; v++) {
  65707. shape[v].subtractInPlace(barycenter);
  65708. }
  65709. var bInfo;
  65710. if (this._particlesIntersect) {
  65711. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65712. }
  65713. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65714. // add the particle in the SPS
  65715. var currentPos = this._positions.length;
  65716. var currentInd = this._indices.length;
  65717. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65718. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65719. // initialize the particle position
  65720. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65721. this._index += shape.length;
  65722. idx++;
  65723. this.nbParticles++;
  65724. this._shapeCounter++;
  65725. f += size;
  65726. }
  65727. return this;
  65728. };
  65729. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65730. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65731. var index = 0;
  65732. var idx = 0;
  65733. for (var p = 0; p < this.particles.length; p++) {
  65734. this._particle = this.particles[p];
  65735. this._shape = this._particle._model._shape;
  65736. if (this._particle.rotationQuaternion) {
  65737. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65738. }
  65739. else {
  65740. this._yaw = this._particle.rotation.y;
  65741. this._pitch = this._particle.rotation.x;
  65742. this._roll = this._particle.rotation.z;
  65743. this._quaternionRotationYPR();
  65744. }
  65745. this._quaternionToRotationMatrix();
  65746. this._rotMatrix.invertToRef(this._invertMatrix);
  65747. for (var pt = 0; pt < this._shape.length; pt++) {
  65748. idx = index + pt * 3;
  65749. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65750. this._fixedNormal32[idx] = this._normal.x;
  65751. this._fixedNormal32[idx + 1] = this._normal.y;
  65752. this._fixedNormal32[idx + 2] = this._normal.z;
  65753. }
  65754. index = idx + 3;
  65755. }
  65756. };
  65757. //reset copy
  65758. SolidParticleSystem.prototype._resetCopy = function () {
  65759. this._copy.position.x = 0;
  65760. this._copy.position.y = 0;
  65761. this._copy.position.z = 0;
  65762. this._copy.rotation.x = 0;
  65763. this._copy.rotation.y = 0;
  65764. this._copy.rotation.z = 0;
  65765. this._copy.rotationQuaternion = null;
  65766. this._copy.scaling.x = 1.0;
  65767. this._copy.scaling.y = 1.0;
  65768. this._copy.scaling.z = 1.0;
  65769. this._copy.uvs.x = 0;
  65770. this._copy.uvs.y = 0;
  65771. this._copy.uvs.z = 1.0;
  65772. this._copy.uvs.w = 1.0;
  65773. this._copy.color = null;
  65774. this._copy.translateFromPivot = false;
  65775. };
  65776. // _meshBuilder : inserts the shape model in the global SPS mesh
  65777. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65778. var i;
  65779. var u = 0;
  65780. var c = 0;
  65781. var n = 0;
  65782. this._resetCopy();
  65783. if (options && options.positionFunction) { // call to custom positionFunction
  65784. options.positionFunction(this._copy, idx, idxInShape);
  65785. this._mustUnrotateFixedNormals = true;
  65786. }
  65787. if (this._copy.rotationQuaternion) {
  65788. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65789. }
  65790. else {
  65791. this._yaw = this._copy.rotation.y;
  65792. this._pitch = this._copy.rotation.x;
  65793. this._roll = this._copy.rotation.z;
  65794. this._quaternionRotationYPR();
  65795. }
  65796. this._quaternionToRotationMatrix();
  65797. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  65798. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  65799. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  65800. if (this._copy.translateFromPivot) {
  65801. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65802. }
  65803. else {
  65804. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65805. }
  65806. for (i = 0; i < shape.length; i++) {
  65807. this._vertex.x = shape[i].x;
  65808. this._vertex.y = shape[i].y;
  65809. this._vertex.z = shape[i].z;
  65810. if (options && options.vertexFunction) {
  65811. options.vertexFunction(this._copy, this._vertex, i);
  65812. }
  65813. this._vertex.x *= this._copy.scaling.x;
  65814. this._vertex.y *= this._copy.scaling.y;
  65815. this._vertex.z *= this._copy.scaling.z;
  65816. this._vertex.x -= this._scaledPivot.x;
  65817. this._vertex.y -= this._scaledPivot.y;
  65818. this._vertex.z -= this._scaledPivot.z;
  65819. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65820. this._rotated.addInPlace(this._pivotBackTranslation);
  65821. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  65822. if (meshUV) {
  65823. 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);
  65824. u += 2;
  65825. }
  65826. if (this._copy.color) {
  65827. this._color = this._copy.color;
  65828. }
  65829. else if (meshCol && meshCol[c] !== undefined) {
  65830. this._color.r = meshCol[c];
  65831. this._color.g = meshCol[c + 1];
  65832. this._color.b = meshCol[c + 2];
  65833. this._color.a = meshCol[c + 3];
  65834. }
  65835. else {
  65836. this._color.r = 1.0;
  65837. this._color.g = 1.0;
  65838. this._color.b = 1.0;
  65839. this._color.a = 1.0;
  65840. }
  65841. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  65842. c += 4;
  65843. if (!this.recomputeNormals && meshNor) {
  65844. this._normal.x = meshNor[n];
  65845. this._normal.y = meshNor[n + 1];
  65846. this._normal.z = meshNor[n + 2];
  65847. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  65848. normals.push(this._normal.x, this._normal.y, this._normal.z);
  65849. n += 3;
  65850. }
  65851. }
  65852. for (i = 0; i < meshInd.length; i++) {
  65853. var current_ind = p + meshInd[i];
  65854. indices.push(current_ind);
  65855. if (current_ind > 65535) {
  65856. this._needs32Bits = true;
  65857. }
  65858. }
  65859. if (this._pickable) {
  65860. var nbfaces = meshInd.length / 3;
  65861. for (i = 0; i < nbfaces; i++) {
  65862. this.pickedParticles.push({ idx: idx, faceId: i });
  65863. }
  65864. }
  65865. if (this._depthSort) {
  65866. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  65867. }
  65868. return this._copy;
  65869. };
  65870. // returns a shape array from positions array
  65871. SolidParticleSystem.prototype._posToShape = function (positions) {
  65872. var shape = [];
  65873. for (var i = 0; i < positions.length; i += 3) {
  65874. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  65875. }
  65876. return shape;
  65877. };
  65878. // returns a shapeUV array from a Vector4 uvs
  65879. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  65880. var shapeUV = [];
  65881. if (uvs) {
  65882. for (var i = 0; i < uvs.length; i++)
  65883. shapeUV.push(uvs[i]);
  65884. }
  65885. return shapeUV;
  65886. };
  65887. // adds a new particle object in the particles array
  65888. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  65889. if (bInfo === void 0) { bInfo = null; }
  65890. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  65891. this.particles.push(sp);
  65892. return sp;
  65893. };
  65894. /**
  65895. * Adds some particles to the SPS from the model shape. Returns the shape id.
  65896. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  65897. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  65898. * @param nb (positive integer) the number of particles to be created from this model
  65899. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  65900. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  65901. * @returns the number of shapes in the system
  65902. */
  65903. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  65904. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65905. var meshInd = mesh.getIndices();
  65906. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65907. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65908. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65909. var bbInfo;
  65910. if (this._particlesIntersect) {
  65911. bbInfo = mesh.getBoundingInfo();
  65912. }
  65913. var shape = this._posToShape(meshPos);
  65914. var shapeUV = this._uvsToShapeUV(meshUV);
  65915. var posfunc = options ? options.positionFunction : null;
  65916. var vtxfunc = options ? options.vertexFunction : null;
  65917. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65918. // particles
  65919. var sp;
  65920. var currentCopy;
  65921. var idx = this.nbParticles;
  65922. for (var i = 0; i < nb; i++) {
  65923. var currentPos = this._positions.length;
  65924. var currentInd = this._indices.length;
  65925. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65926. if (this._updatable) {
  65927. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65928. sp.position.copyFrom(currentCopy.position);
  65929. sp.rotation.copyFrom(currentCopy.rotation);
  65930. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65931. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65932. }
  65933. if (currentCopy.color && sp.color) {
  65934. sp.color.copyFrom(currentCopy.color);
  65935. }
  65936. sp.scaling.copyFrom(currentCopy.scaling);
  65937. sp.uvs.copyFrom(currentCopy.uvs);
  65938. }
  65939. this._index += shape.length;
  65940. idx++;
  65941. }
  65942. this.nbParticles += nb;
  65943. this._shapeCounter++;
  65944. return this._shapeCounter - 1;
  65945. };
  65946. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65947. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65948. this._resetCopy();
  65949. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65950. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65951. }
  65952. if (this._copy.rotationQuaternion) {
  65953. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65954. }
  65955. else {
  65956. this._yaw = this._copy.rotation.y;
  65957. this._pitch = this._copy.rotation.x;
  65958. this._roll = this._copy.rotation.z;
  65959. this._quaternionRotationYPR();
  65960. }
  65961. this._quaternionToRotationMatrix();
  65962. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65963. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65964. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65965. if (this._copy.translateFromPivot) {
  65966. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65967. }
  65968. else {
  65969. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65970. }
  65971. this._shape = particle._model._shape;
  65972. for (var pt = 0; pt < this._shape.length; pt++) {
  65973. this._vertex.x = this._shape[pt].x;
  65974. this._vertex.y = this._shape[pt].y;
  65975. this._vertex.z = this._shape[pt].z;
  65976. if (particle._model._vertexFunction) {
  65977. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65978. }
  65979. this._vertex.x *= this._copy.scaling.x;
  65980. this._vertex.y *= this._copy.scaling.y;
  65981. this._vertex.z *= this._copy.scaling.z;
  65982. this._vertex.x -= this._scaledPivot.x;
  65983. this._vertex.y -= this._scaledPivot.y;
  65984. this._vertex.z -= this._scaledPivot.z;
  65985. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65986. this._rotated.addInPlace(this._pivotBackTranslation);
  65987. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65988. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65989. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65990. }
  65991. particle.position.x = 0.0;
  65992. particle.position.y = 0.0;
  65993. particle.position.z = 0.0;
  65994. particle.rotation.x = 0.0;
  65995. particle.rotation.y = 0.0;
  65996. particle.rotation.z = 0.0;
  65997. particle.rotationQuaternion = null;
  65998. particle.scaling.x = 1.0;
  65999. particle.scaling.y = 1.0;
  66000. particle.scaling.z = 1.0;
  66001. particle.uvs.x = 0.0;
  66002. particle.uvs.y = 0.0;
  66003. particle.uvs.z = 1.0;
  66004. particle.uvs.w = 1.0;
  66005. particle.pivot.x = 0.0;
  66006. particle.pivot.y = 0.0;
  66007. particle.pivot.z = 0.0;
  66008. particle.translateFromPivot = false;
  66009. particle.parentId = null;
  66010. };
  66011. /**
  66012. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66013. * @returns the SPS.
  66014. */
  66015. SolidParticleSystem.prototype.rebuildMesh = function () {
  66016. for (var p = 0; p < this.particles.length; p++) {
  66017. this._rebuildParticle(this.particles[p]);
  66018. }
  66019. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66020. return this;
  66021. };
  66022. /**
  66023. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66024. * This method calls `updateParticle()` for each particle of the SPS.
  66025. * For an animated SPS, it is usually called within the render loop.
  66026. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66027. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66028. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66029. * @returns the SPS.
  66030. */
  66031. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66032. if (start === void 0) { start = 0; }
  66033. if (end === void 0) { end = this.nbParticles - 1; }
  66034. if (update === void 0) { update = true; }
  66035. if (!this._updatable) {
  66036. return this;
  66037. }
  66038. // custom beforeUpdate
  66039. this.beforeUpdateParticles(start, end, update);
  66040. this._cam_axisX.x = 1.0;
  66041. this._cam_axisX.y = 0.0;
  66042. this._cam_axisX.z = 0.0;
  66043. this._cam_axisY.x = 0.0;
  66044. this._cam_axisY.y = 1.0;
  66045. this._cam_axisY.z = 0.0;
  66046. this._cam_axisZ.x = 0.0;
  66047. this._cam_axisZ.y = 0.0;
  66048. this._cam_axisZ.z = 1.0;
  66049. // cases when the World Matrix is to be computed first
  66050. if (this.billboard || this._depthSort) {
  66051. this.mesh.computeWorldMatrix(true);
  66052. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66053. }
  66054. // if the particles will always face the camera
  66055. if (this.billboard) {
  66056. // compute the camera position and un-rotate it by the current mesh rotation
  66057. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66058. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66059. this._cam_axisZ.normalize();
  66060. // same for camera up vector extracted from the cam view matrix
  66061. var view = this._camera.getViewMatrix(true);
  66062. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66063. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66064. this._cam_axisY.normalize();
  66065. this._cam_axisX.normalize();
  66066. }
  66067. // if depthSort, compute the camera global position in the mesh local system
  66068. if (this._depthSort) {
  66069. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66070. }
  66071. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66072. var idx = 0; // current position index in the global array positions32
  66073. var index = 0; // position start index in the global array positions32 of the current particle
  66074. var colidx = 0; // current color index in the global array colors32
  66075. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66076. var uvidx = 0; // current uv index in the global array uvs32
  66077. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66078. var pt = 0; // current index in the particle model shape
  66079. if (this.mesh.isFacetDataEnabled) {
  66080. this._computeBoundingBox = true;
  66081. }
  66082. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66083. if (this._computeBoundingBox) {
  66084. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66085. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66086. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66087. }
  66088. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66089. if (this.mesh._boundingInfo) {
  66090. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66091. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66092. }
  66093. }
  66094. }
  66095. // particle loop
  66096. index = this.particles[start]._pos;
  66097. var vpos = (index / 3) | 0;
  66098. colorIndex = vpos * 4;
  66099. uvIndex = vpos * 2;
  66100. for (var p = start; p <= end; p++) {
  66101. this._particle = this.particles[p];
  66102. this._shape = this._particle._model._shape;
  66103. this._shapeUV = this._particle._model._shapeUV;
  66104. // call to custom user function to update the particle properties
  66105. this.updateParticle(this._particle);
  66106. // camera-particle distance for depth sorting
  66107. if (this._depthSort && this._depthSortParticles) {
  66108. var dsp = this.depthSortedParticles[p];
  66109. dsp.ind = this._particle._ind;
  66110. dsp.indicesLength = this._particle._model._indicesLength;
  66111. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66112. }
  66113. // skip the computations for inactive or already invisible particles
  66114. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66115. // increment indexes for the next particle
  66116. pt = this._shape.length;
  66117. index += pt * 3;
  66118. colorIndex += pt * 4;
  66119. uvIndex += pt * 2;
  66120. continue;
  66121. }
  66122. if (this._particle.isVisible) {
  66123. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66124. this._particleHasParent = (this._particle.parentId !== null);
  66125. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66126. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66127. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66128. // particle rotation matrix
  66129. if (this.billboard) {
  66130. this._particle.rotation.x = 0.0;
  66131. this._particle.rotation.y = 0.0;
  66132. }
  66133. if (this._computeParticleRotation || this.billboard) {
  66134. if (this._particle.rotationQuaternion) {
  66135. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66136. }
  66137. else {
  66138. this._yaw = this._particle.rotation.y;
  66139. this._pitch = this._particle.rotation.x;
  66140. this._roll = this._particle.rotation.z;
  66141. this._quaternionRotationYPR();
  66142. }
  66143. this._quaternionToRotationMatrix();
  66144. }
  66145. if (this._particleHasParent) {
  66146. this._parent = this.particles[this._particle.parentId];
  66147. 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];
  66148. 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];
  66149. 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];
  66150. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66151. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66152. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66153. if (this._computeParticleRotation || this.billboard) {
  66154. 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];
  66155. 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];
  66156. 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];
  66157. 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];
  66158. 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];
  66159. 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];
  66160. 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];
  66161. 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];
  66162. 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];
  66163. }
  66164. }
  66165. else {
  66166. this._particle._globalPosition.x = this._particle.position.x;
  66167. this._particle._globalPosition.y = this._particle.position.y;
  66168. this._particle._globalPosition.z = this._particle.position.z;
  66169. if (this._computeParticleRotation || this.billboard) {
  66170. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66171. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66172. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66173. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66174. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66175. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66176. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66177. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66178. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66179. }
  66180. }
  66181. if (this._particle.translateFromPivot) {
  66182. this._pivotBackTranslation.x = 0.0;
  66183. this._pivotBackTranslation.y = 0.0;
  66184. this._pivotBackTranslation.z = 0.0;
  66185. }
  66186. else {
  66187. this._pivotBackTranslation.x = this._scaledPivot.x;
  66188. this._pivotBackTranslation.y = this._scaledPivot.y;
  66189. this._pivotBackTranslation.z = this._scaledPivot.z;
  66190. }
  66191. // particle vertex loop
  66192. for (pt = 0; pt < this._shape.length; pt++) {
  66193. idx = index + pt * 3;
  66194. colidx = colorIndex + pt * 4;
  66195. uvidx = uvIndex + pt * 2;
  66196. this._vertex.x = this._shape[pt].x;
  66197. this._vertex.y = this._shape[pt].y;
  66198. this._vertex.z = this._shape[pt].z;
  66199. if (this._computeParticleVertex) {
  66200. this.updateParticleVertex(this._particle, this._vertex, pt);
  66201. }
  66202. // positions
  66203. this._vertex.x *= this._particle.scaling.x;
  66204. this._vertex.y *= this._particle.scaling.y;
  66205. this._vertex.z *= this._particle.scaling.z;
  66206. this._vertex.x -= this._scaledPivot.x;
  66207. this._vertex.y -= this._scaledPivot.y;
  66208. this._vertex.z -= this._scaledPivot.z;
  66209. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66210. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66211. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66212. this._rotated.x += this._pivotBackTranslation.x;
  66213. this._rotated.y += this._pivotBackTranslation.y;
  66214. this._rotated.z += this._pivotBackTranslation.z;
  66215. 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;
  66216. 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;
  66217. 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;
  66218. if (this._computeBoundingBox) {
  66219. if (this._positions32[idx] < this._minimum.x) {
  66220. this._minimum.x = this._positions32[idx];
  66221. }
  66222. if (this._positions32[idx] > this._maximum.x) {
  66223. this._maximum.x = this._positions32[idx];
  66224. }
  66225. if (this._positions32[idx + 1] < this._minimum.y) {
  66226. this._minimum.y = this._positions32[idx + 1];
  66227. }
  66228. if (this._positions32[idx + 1] > this._maximum.y) {
  66229. this._maximum.y = this._positions32[idx + 1];
  66230. }
  66231. if (this._positions32[idx + 2] < this._minimum.z) {
  66232. this._minimum.z = this._positions32[idx + 2];
  66233. }
  66234. if (this._positions32[idx + 2] > this._maximum.z) {
  66235. this._maximum.z = this._positions32[idx + 2];
  66236. }
  66237. }
  66238. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66239. if (!this._computeParticleVertex) {
  66240. this._normal.x = this._fixedNormal32[idx];
  66241. this._normal.y = this._fixedNormal32[idx + 1];
  66242. this._normal.z = this._fixedNormal32[idx + 2];
  66243. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66244. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66245. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66246. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66247. 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;
  66248. 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;
  66249. }
  66250. if (this._computeParticleColor && this._particle.color) {
  66251. this._colors32[colidx] = this._particle.color.r;
  66252. this._colors32[colidx + 1] = this._particle.color.g;
  66253. this._colors32[colidx + 2] = this._particle.color.b;
  66254. this._colors32[colidx + 3] = this._particle.color.a;
  66255. }
  66256. if (this._computeParticleTexture) {
  66257. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66258. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66259. }
  66260. }
  66261. }
  66262. // particle just set invisible : scaled to zero and positioned at the origin
  66263. else {
  66264. this._particle._stillInvisible = true; // mark the particle as invisible
  66265. for (pt = 0; pt < this._shape.length; pt++) {
  66266. idx = index + pt * 3;
  66267. colidx = colorIndex + pt * 4;
  66268. uvidx = uvIndex + pt * 2;
  66269. this._positions32[idx] = 0.0;
  66270. this._positions32[idx + 1] = 0.0;
  66271. this._positions32[idx + 2] = 0.0;
  66272. this._normals32[idx] = 0.0;
  66273. this._normals32[idx + 1] = 0.0;
  66274. this._normals32[idx + 2] = 0.0;
  66275. if (this._computeParticleColor && this._particle.color) {
  66276. this._colors32[colidx] = this._particle.color.r;
  66277. this._colors32[colidx + 1] = this._particle.color.g;
  66278. this._colors32[colidx + 2] = this._particle.color.b;
  66279. this._colors32[colidx + 3] = this._particle.color.a;
  66280. }
  66281. if (this._computeParticleTexture) {
  66282. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66283. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66284. }
  66285. }
  66286. }
  66287. // if the particle intersections must be computed : update the bbInfo
  66288. if (this._particlesIntersect) {
  66289. var bInfo = this._particle._boundingInfo;
  66290. var bBox = bInfo.boundingBox;
  66291. var bSphere = bInfo.boundingSphere;
  66292. if (!this._bSphereOnly) {
  66293. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66294. for (var b = 0; b < bBox.vectors.length; b++) {
  66295. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66296. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66297. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66298. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66299. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66300. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66301. 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;
  66302. 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;
  66303. 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;
  66304. }
  66305. bBox._update(this.mesh._worldMatrix);
  66306. }
  66307. // place and scale the particle bouding sphere in the SPS local system, then update it
  66308. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66309. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66310. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66311. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66312. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66313. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66314. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66315. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66316. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66317. 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));
  66318. bSphere._update(this.mesh._worldMatrix);
  66319. }
  66320. // increment indexes for the next particle
  66321. index = idx + 3;
  66322. colorIndex = colidx + 4;
  66323. uvIndex = uvidx + 2;
  66324. }
  66325. // if the VBO must be updated
  66326. if (update) {
  66327. if (this._computeParticleColor) {
  66328. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66329. }
  66330. if (this._computeParticleTexture) {
  66331. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66332. }
  66333. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66334. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66335. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66336. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66337. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66338. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66339. for (var i = 0; i < this._normals32.length; i++) {
  66340. this._fixedNormal32[i] = this._normals32[i];
  66341. }
  66342. }
  66343. if (!this.mesh.areNormalsFrozen) {
  66344. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66345. }
  66346. }
  66347. if (this._depthSort && this._depthSortParticles) {
  66348. this.depthSortedParticles.sort(this._depthSortFunction);
  66349. var dspl = this.depthSortedParticles.length;
  66350. var sorted = 0;
  66351. var lind = 0;
  66352. var sind = 0;
  66353. var sid = 0;
  66354. for (sorted = 0; sorted < dspl; sorted++) {
  66355. lind = this.depthSortedParticles[sorted].indicesLength;
  66356. sind = this.depthSortedParticles[sorted].ind;
  66357. for (var i = 0; i < lind; i++) {
  66358. this._indices32[sid] = this._indices[sind + i];
  66359. sid++;
  66360. }
  66361. }
  66362. this.mesh.updateIndices(this._indices32);
  66363. }
  66364. }
  66365. if (this._computeBoundingBox) {
  66366. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66367. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66368. }
  66369. this.afterUpdateParticles(start, end, update);
  66370. return this;
  66371. };
  66372. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66373. this._halfroll = this._roll * 0.5;
  66374. this._halfpitch = this._pitch * 0.5;
  66375. this._halfyaw = this._yaw * 0.5;
  66376. this._sinRoll = Math.sin(this._halfroll);
  66377. this._cosRoll = Math.cos(this._halfroll);
  66378. this._sinPitch = Math.sin(this._halfpitch);
  66379. this._cosPitch = Math.cos(this._halfpitch);
  66380. this._sinYaw = Math.sin(this._halfyaw);
  66381. this._cosYaw = Math.cos(this._halfyaw);
  66382. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66383. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66384. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66385. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66386. };
  66387. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66388. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66389. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66390. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66391. this._rotMatrix.m[3] = 0;
  66392. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66393. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66394. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66395. this._rotMatrix.m[7] = 0;
  66396. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66397. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66398. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66399. this._rotMatrix.m[11] = 0;
  66400. this._rotMatrix.m[12] = 0;
  66401. this._rotMatrix.m[13] = 0;
  66402. this._rotMatrix.m[14] = 0;
  66403. this._rotMatrix.m[15] = 1.0;
  66404. };
  66405. /**
  66406. * Disposes the SPS.
  66407. */
  66408. SolidParticleSystem.prototype.dispose = function () {
  66409. this.mesh.dispose();
  66410. this.vars = null;
  66411. // drop references to internal big arrays for the GC
  66412. this._positions = null;
  66413. this._indices = null;
  66414. this._normals = null;
  66415. this._uvs = null;
  66416. this._colors = null;
  66417. this._indices32 = null;
  66418. this._positions32 = null;
  66419. this._normals32 = null;
  66420. this._fixedNormal32 = null;
  66421. this._uvs32 = null;
  66422. this._colors32 = null;
  66423. this.pickedParticles = null;
  66424. };
  66425. /**
  66426. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66427. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66428. * @returns the SPS.
  66429. */
  66430. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66431. if (!this._isVisibilityBoxLocked) {
  66432. this.mesh.refreshBoundingInfo();
  66433. }
  66434. return this;
  66435. };
  66436. /**
  66437. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66438. * @param size the size (float) of the visibility box
  66439. * note : this doesn't lock the SPS mesh bounding box.
  66440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66441. */
  66442. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66443. var vis = size / 2;
  66444. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66445. };
  66446. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66447. /**
  66448. * Gets whether the SPS as always visible or not
  66449. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66450. */
  66451. get: function () {
  66452. return this._alwaysVisible;
  66453. },
  66454. /**
  66455. * Sets the SPS as always visible or not
  66456. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66457. */
  66458. set: function (val) {
  66459. this._alwaysVisible = val;
  66460. this.mesh.alwaysSelectAsActiveMesh = val;
  66461. },
  66462. enumerable: true,
  66463. configurable: true
  66464. });
  66465. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66466. /**
  66467. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66468. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66469. */
  66470. get: function () {
  66471. return this._isVisibilityBoxLocked;
  66472. },
  66473. /**
  66474. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66475. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66476. */
  66477. set: function (val) {
  66478. this._isVisibilityBoxLocked = val;
  66479. var boundingInfo = this.mesh.getBoundingInfo();
  66480. boundingInfo.isLocked = val;
  66481. },
  66482. enumerable: true,
  66483. configurable: true
  66484. });
  66485. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66486. /**
  66487. * Gets if `setParticles()` computes the particle rotations or not.
  66488. * Default value : true. The SPS is faster when it's set to false.
  66489. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66490. */
  66491. get: function () {
  66492. return this._computeParticleRotation;
  66493. },
  66494. /**
  66495. * Tells to `setParticles()` to compute the particle rotations or not.
  66496. * Default value : true. The SPS is faster when it's set to false.
  66497. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66498. */
  66499. set: function (val) {
  66500. this._computeParticleRotation = val;
  66501. },
  66502. enumerable: true,
  66503. configurable: true
  66504. });
  66505. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66506. /**
  66507. * Gets if `setParticles()` computes the particle colors or not.
  66508. * Default value : true. The SPS is faster when it's set to false.
  66509. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66510. */
  66511. get: function () {
  66512. return this._computeParticleColor;
  66513. },
  66514. /**
  66515. * Tells to `setParticles()` to compute the particle colors or not.
  66516. * Default value : true. The SPS is faster when it's set to false.
  66517. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66518. */
  66519. set: function (val) {
  66520. this._computeParticleColor = val;
  66521. },
  66522. enumerable: true,
  66523. configurable: true
  66524. });
  66525. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66526. /**
  66527. * Gets if `setParticles()` computes the particle textures or not.
  66528. * Default value : true. The SPS is faster when it's set to false.
  66529. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66530. */
  66531. get: function () {
  66532. return this._computeParticleTexture;
  66533. },
  66534. set: function (val) {
  66535. this._computeParticleTexture = val;
  66536. },
  66537. enumerable: true,
  66538. configurable: true
  66539. });
  66540. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66541. /**
  66542. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66543. * Default value : false. The SPS is faster when it's set to false.
  66544. * Note : the particle custom vertex positions aren't stored values.
  66545. */
  66546. get: function () {
  66547. return this._computeParticleVertex;
  66548. },
  66549. /**
  66550. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66551. * Default value : false. The SPS is faster when it's set to false.
  66552. * Note : the particle custom vertex positions aren't stored values.
  66553. */
  66554. set: function (val) {
  66555. this._computeParticleVertex = val;
  66556. },
  66557. enumerable: true,
  66558. configurable: true
  66559. });
  66560. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66561. /**
  66562. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66563. */
  66564. get: function () {
  66565. return this._computeBoundingBox;
  66566. },
  66567. /**
  66568. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66569. */
  66570. set: function (val) {
  66571. this._computeBoundingBox = val;
  66572. },
  66573. enumerable: true,
  66574. configurable: true
  66575. });
  66576. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66577. /**
  66578. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66579. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66580. * Default : `true`
  66581. */
  66582. get: function () {
  66583. return this._depthSortParticles;
  66584. },
  66585. /**
  66586. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66587. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66588. * Default : `true`
  66589. */
  66590. set: function (val) {
  66591. this._depthSortParticles = val;
  66592. },
  66593. enumerable: true,
  66594. configurable: true
  66595. });
  66596. // =======================================================================
  66597. // Particle behavior logic
  66598. // these following methods may be overwritten by the user to fit his needs
  66599. /**
  66600. * This function does nothing. It may be overwritten to set all the particle first values.
  66601. * The SPS doesn't call this function, you may have to call it by your own.
  66602. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66603. */
  66604. SolidParticleSystem.prototype.initParticles = function () {
  66605. };
  66606. /**
  66607. * This function does nothing. It may be overwritten to recycle a particle.
  66608. * The SPS doesn't call this function, you may have to call it by your own.
  66609. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66610. * @param particle The particle to recycle
  66611. * @returns the recycled particle
  66612. */
  66613. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66614. return particle;
  66615. };
  66616. /**
  66617. * Updates a particle : this function should be overwritten by the user.
  66618. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66620. * @example : just set a particle position or velocity and recycle conditions
  66621. * @param particle The particle to update
  66622. * @returns the updated particle
  66623. */
  66624. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66625. return particle;
  66626. };
  66627. /**
  66628. * Updates a vertex of a particle : it can be overwritten by the user.
  66629. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66630. * @param particle the current particle
  66631. * @param vertex the current index of the current particle
  66632. * @param pt the index of the current vertex in the particle shape
  66633. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66634. * @example : just set a vertex particle position
  66635. * @returns the updated vertex
  66636. */
  66637. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66638. return vertex;
  66639. };
  66640. /**
  66641. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66642. * This does nothing and may be overwritten by the user.
  66643. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66644. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66645. * @param update the boolean update value actually passed to setParticles()
  66646. */
  66647. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66648. };
  66649. /**
  66650. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66651. * This will be passed three parameters.
  66652. * This does nothing and may be overwritten by the user.
  66653. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66654. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66655. * @param update the boolean update value actually passed to setParticles()
  66656. */
  66657. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66658. };
  66659. return SolidParticleSystem;
  66660. }());
  66661. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66662. })(BABYLON || (BABYLON = {}));
  66663. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66664. var BABYLON;
  66665. (function (BABYLON) {
  66666. /**
  66667. * Class containing static functions to help procedurally build meshes
  66668. */
  66669. var MeshBuilder = /** @class */ (function () {
  66670. function MeshBuilder() {
  66671. }
  66672. MeshBuilder.updateSideOrientation = function (orientation) {
  66673. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66674. return BABYLON.Mesh.DOUBLESIDE;
  66675. }
  66676. if (orientation === undefined || orientation === null) {
  66677. return BABYLON.Mesh.FRONTSIDE;
  66678. }
  66679. return orientation;
  66680. };
  66681. /**
  66682. * Creates a box mesh
  66683. * * The parameter `size` sets the size (float) of each box side (default 1)
  66684. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66685. * * 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)
  66686. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66687. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66688. * * 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
  66689. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66690. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66691. * @param name defines the name of the mesh
  66692. * @param options defines the options used to create the mesh
  66693. * @param scene defines the hosting scene
  66694. * @returns the box mesh
  66695. */
  66696. MeshBuilder.CreateBox = function (name, options, scene) {
  66697. if (scene === void 0) { scene = null; }
  66698. var box = new BABYLON.Mesh(name, scene);
  66699. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66700. box._originalBuilderSideOrientation = options.sideOrientation;
  66701. var vertexData = BABYLON.VertexData.CreateBox(options);
  66702. vertexData.applyToMesh(box, options.updatable);
  66703. return box;
  66704. };
  66705. /**
  66706. * Creates a sphere mesh
  66707. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66708. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
  66709. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66710. * * 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
  66711. * * 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)
  66712. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66713. * * 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
  66714. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66715. * @param name defines the name of the mesh
  66716. * @param options defines the options used to create the mesh
  66717. * @param scene defines the hosting scene
  66718. * @returns the sphere mesh
  66719. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66720. */
  66721. MeshBuilder.CreateSphere = function (name, options, scene) {
  66722. var sphere = new BABYLON.Mesh(name, scene);
  66723. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66724. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66725. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66726. vertexData.applyToMesh(sphere, options.updatable);
  66727. return sphere;
  66728. };
  66729. /**
  66730. * Creates a plane polygonal mesh. By default, this is a disc
  66731. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66732. * * 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
  66733. * * 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
  66734. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66735. * * 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
  66736. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66737. * @param name defines the name of the mesh
  66738. * @param options defines the options used to create the mesh
  66739. * @param scene defines the hosting scene
  66740. * @returns the plane polygonal mesh
  66741. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66742. */
  66743. MeshBuilder.CreateDisc = function (name, options, scene) {
  66744. if (scene === void 0) { scene = null; }
  66745. var disc = new BABYLON.Mesh(name, scene);
  66746. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66747. disc._originalBuilderSideOrientation = options.sideOrientation;
  66748. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66749. vertexData.applyToMesh(disc, options.updatable);
  66750. return disc;
  66751. };
  66752. /**
  66753. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66754. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66755. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
  66756. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66757. * * 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
  66758. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66759. * * 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
  66760. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66761. * @param name defines the name of the mesh
  66762. * @param options defines the options used to create the mesh
  66763. * @param scene defines the hosting scene
  66764. * @returns the icosahedron mesh
  66765. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66766. */
  66767. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66768. var sphere = new BABYLON.Mesh(name, scene);
  66769. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66770. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66771. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66772. vertexData.applyToMesh(sphere, options.updatable);
  66773. return sphere;
  66774. };
  66775. ;
  66776. /**
  66777. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66778. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66779. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66780. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66781. * * 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
  66782. * * 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
  66783. * * 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
  66784. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66785. * * 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
  66786. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66787. * * 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
  66788. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66789. * * 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
  66790. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66791. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66792. * @param name defines the name of the mesh
  66793. * @param options defines the options used to create the mesh
  66794. * @param scene defines the hosting scene
  66795. * @returns the ribbon mesh
  66796. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  66797. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66798. */
  66799. MeshBuilder.CreateRibbon = function (name, options, scene) {
  66800. if (scene === void 0) { scene = null; }
  66801. var pathArray = options.pathArray;
  66802. var closeArray = options.closeArray;
  66803. var closePath = options.closePath;
  66804. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66805. var instance = options.instance;
  66806. var updatable = options.updatable;
  66807. if (instance) { // existing ribbon instance update
  66808. // positionFunction : ribbon case
  66809. // only pathArray and sideOrientation parameters are taken into account for positions update
  66810. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  66811. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  66812. var positionFunction = function (positions) {
  66813. var minlg = pathArray[0].length;
  66814. var mesh = instance;
  66815. var i = 0;
  66816. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  66817. for (var si = 1; si <= ns; si++) {
  66818. for (var p = 0; p < pathArray.length; p++) {
  66819. var path = pathArray[p];
  66820. var l = path.length;
  66821. minlg = (minlg < l) ? minlg : l;
  66822. var j = 0;
  66823. while (j < minlg) {
  66824. positions[i] = path[j].x;
  66825. positions[i + 1] = path[j].y;
  66826. positions[i + 2] = path[j].z;
  66827. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  66828. BABYLON.Tmp.Vector3[0].x = path[j].x;
  66829. }
  66830. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  66831. BABYLON.Tmp.Vector3[1].x = path[j].x;
  66832. }
  66833. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  66834. BABYLON.Tmp.Vector3[0].y = path[j].y;
  66835. }
  66836. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  66837. BABYLON.Tmp.Vector3[1].y = path[j].y;
  66838. }
  66839. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  66840. BABYLON.Tmp.Vector3[0].z = path[j].z;
  66841. }
  66842. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  66843. BABYLON.Tmp.Vector3[1].z = path[j].z;
  66844. }
  66845. j++;
  66846. i += 3;
  66847. }
  66848. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  66849. positions[i] = path[0].x;
  66850. positions[i + 1] = path[0].y;
  66851. positions[i + 2] = path[0].z;
  66852. i += 3;
  66853. }
  66854. }
  66855. }
  66856. };
  66857. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66858. positionFunction(positions);
  66859. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  66860. instance._boundingInfo.update(instance._worldMatrix);
  66861. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66862. if (options.colors) {
  66863. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66864. for (var c = 0; c < options.colors.length; c++) {
  66865. colors[c * 4] = options.colors[c].r;
  66866. colors[c * 4 + 1] = options.colors[c].g;
  66867. colors[c * 4 + 2] = options.colors[c].b;
  66868. colors[c * 4 + 3] = options.colors[c].a;
  66869. }
  66870. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  66871. }
  66872. if (options.uvs) {
  66873. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66874. for (var i = 0; i < options.uvs.length; i++) {
  66875. uvs[i * 2] = options.uvs[i].x;
  66876. uvs[i * 2 + 1] = options.uvs[i].y;
  66877. }
  66878. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  66879. }
  66880. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  66881. var indices = instance.getIndices();
  66882. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66883. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  66884. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  66885. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  66886. var indexFirst = 0;
  66887. var indexLast = 0;
  66888. for (var p = 0; p < pathArray.length; p++) {
  66889. indexFirst = instance._creationDataStorage.idx[p] * 3;
  66890. if (p + 1 < pathArray.length) {
  66891. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  66892. }
  66893. else {
  66894. indexLast = normals.length - 3;
  66895. }
  66896. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  66897. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  66898. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  66899. normals[indexLast] = normals[indexFirst];
  66900. normals[indexLast + 1] = normals[indexFirst + 1];
  66901. normals[indexLast + 2] = normals[indexFirst + 2];
  66902. }
  66903. }
  66904. if (!(instance.areNormalsFrozen)) {
  66905. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  66906. }
  66907. }
  66908. return instance;
  66909. }
  66910. else { // new ribbon creation
  66911. var ribbon = new BABYLON.Mesh(name, scene);
  66912. ribbon._originalBuilderSideOrientation = sideOrientation;
  66913. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  66914. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  66915. if (closePath) {
  66916. ribbon._creationDataStorage.idx = vertexData._idx;
  66917. }
  66918. ribbon._creationDataStorage.closePath = closePath;
  66919. ribbon._closeArray = closeArray;
  66920. vertexData.applyToMesh(ribbon, updatable);
  66921. return ribbon;
  66922. }
  66923. };
  66924. /**
  66925. * Creates a cylinder or a cone mesh
  66926. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66927. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66928. * * 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.
  66929. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66930. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66931. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66932. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66933. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66934. * * 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).
  66935. * * 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
  66936. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66937. * * 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
  66938. * * 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.
  66939. * * If `enclose` is false, a ring surface is one element.
  66940. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66941. * * 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
  66942. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66943. * * 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
  66944. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66945. * @param name defines the name of the mesh
  66946. * @param options defines the options used to create the mesh
  66947. * @param scene defines the hosting scene
  66948. * @returns the cylinder mesh
  66949. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66950. */
  66951. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66952. var cylinder = new BABYLON.Mesh(name, scene);
  66953. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66954. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66955. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66956. vertexData.applyToMesh(cylinder, options.updatable);
  66957. return cylinder;
  66958. };
  66959. /**
  66960. * Creates a torus mesh
  66961. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66962. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66963. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66964. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66965. * * 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
  66966. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66967. * @param name defines the name of the mesh
  66968. * @param options defines the options used to create the mesh
  66969. * @param scene defines the hosting scene
  66970. * @returns the torus mesh
  66971. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66972. */
  66973. MeshBuilder.CreateTorus = function (name, options, scene) {
  66974. var torus = new BABYLON.Mesh(name, scene);
  66975. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66976. torus._originalBuilderSideOrientation = options.sideOrientation;
  66977. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66978. vertexData.applyToMesh(torus, options.updatable);
  66979. return torus;
  66980. };
  66981. /**
  66982. * Creates a torus knot mesh
  66983. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66984. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66985. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66986. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66987. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66988. * * 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
  66989. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66990. * @param name defines the name of the mesh
  66991. * @param options defines the options used to create the mesh
  66992. * @param scene defines the hosting scene
  66993. * @returns the torus knot mesh
  66994. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66995. */
  66996. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66997. var torusKnot = new BABYLON.Mesh(name, scene);
  66998. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66999. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67000. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67001. vertexData.applyToMesh(torusKnot, options.updatable);
  67002. return torusKnot;
  67003. };
  67004. /**
  67005. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67006. * * 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
  67007. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67008. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67009. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67010. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67011. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67012. * * 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
  67013. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67014. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67015. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67016. * @param name defines the name of the new line system
  67017. * @param options defines the options used to create the line system
  67018. * @param scene defines the hosting scene
  67019. * @returns a new line system mesh
  67020. */
  67021. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67022. var instance = options.instance;
  67023. var lines = options.lines;
  67024. var colors = options.colors;
  67025. if (instance) { // lines update
  67026. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67027. var vertexColor;
  67028. var lineColors;
  67029. if (colors) {
  67030. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67031. }
  67032. var i = 0;
  67033. var c = 0;
  67034. for (var l = 0; l < lines.length; l++) {
  67035. var points = lines[l];
  67036. for (var p = 0; p < points.length; p++) {
  67037. positions[i] = points[p].x;
  67038. positions[i + 1] = points[p].y;
  67039. positions[i + 2] = points[p].z;
  67040. if (colors && vertexColor) {
  67041. lineColors = colors[l];
  67042. vertexColor[c] = lineColors[p].r;
  67043. vertexColor[c + 1] = lineColors[p].g;
  67044. vertexColor[c + 2] = lineColors[p].b;
  67045. vertexColor[c + 3] = lineColors[p].a;
  67046. c += 4;
  67047. }
  67048. i += 3;
  67049. }
  67050. }
  67051. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67052. if (colors && vertexColor) {
  67053. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67054. }
  67055. return instance;
  67056. }
  67057. // line system creation
  67058. var useVertexColor = (colors) ? true : false;
  67059. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67060. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67061. vertexData.applyToMesh(lineSystem, options.updatable);
  67062. return lineSystem;
  67063. };
  67064. /**
  67065. * Creates a line mesh
  67066. * 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
  67067. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67068. * * The parameter `points` is an array successive Vector3
  67069. * * 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
  67070. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67071. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67072. * * When updating an instance, remember that only point positions can change, not the number of points
  67073. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67074. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67075. * @param name defines the name of the new line system
  67076. * @param options defines the options used to create the line system
  67077. * @param scene defines the hosting scene
  67078. * @returns a new line mesh
  67079. */
  67080. MeshBuilder.CreateLines = function (name, options, scene) {
  67081. if (scene === void 0) { scene = null; }
  67082. var colors = (options.colors) ? [options.colors] : null;
  67083. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67084. return lines;
  67085. };
  67086. /**
  67087. * Creates a dashed line mesh
  67088. * * 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
  67089. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67090. * * The parameter `points` is an array successive Vector3
  67091. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67092. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67093. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67094. * * 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
  67095. * * When updating an instance, remember that only point positions can change, not the number of points
  67096. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67097. * @param name defines the name of the mesh
  67098. * @param options defines the options used to create the mesh
  67099. * @param scene defines the hosting scene
  67100. * @returns the dashed line mesh
  67101. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67102. */
  67103. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67104. if (scene === void 0) { scene = null; }
  67105. var points = options.points;
  67106. var instance = options.instance;
  67107. var gapSize = options.gapSize || 1;
  67108. var dashSize = options.dashSize || 3;
  67109. if (instance) { // dashed lines update
  67110. var positionFunction = function (positions) {
  67111. var curvect = BABYLON.Vector3.Zero();
  67112. var nbSeg = positions.length / 6;
  67113. var lg = 0;
  67114. var nb = 0;
  67115. var shft = 0;
  67116. var dashshft = 0;
  67117. var curshft = 0;
  67118. var p = 0;
  67119. var i = 0;
  67120. var j = 0;
  67121. for (i = 0; i < points.length - 1; i++) {
  67122. points[i + 1].subtractToRef(points[i], curvect);
  67123. lg += curvect.length();
  67124. }
  67125. shft = lg / nbSeg;
  67126. var dashSize = instance._creationDataStorage.dashSize;
  67127. var gapSize = instance._creationDataStorage.gapSize;
  67128. dashshft = dashSize * shft / (dashSize + gapSize);
  67129. for (i = 0; i < points.length - 1; i++) {
  67130. points[i + 1].subtractToRef(points[i], curvect);
  67131. nb = Math.floor(curvect.length() / shft);
  67132. curvect.normalize();
  67133. j = 0;
  67134. while (j < nb && p < positions.length) {
  67135. curshft = shft * j;
  67136. positions[p] = points[i].x + curshft * curvect.x;
  67137. positions[p + 1] = points[i].y + curshft * curvect.y;
  67138. positions[p + 2] = points[i].z + curshft * curvect.z;
  67139. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67140. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67141. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67142. p += 6;
  67143. j++;
  67144. }
  67145. }
  67146. while (p < positions.length) {
  67147. positions[p] = points[i].x;
  67148. positions[p + 1] = points[i].y;
  67149. positions[p + 2] = points[i].z;
  67150. p += 3;
  67151. }
  67152. };
  67153. instance.updateMeshPositions(positionFunction, false);
  67154. return instance;
  67155. }
  67156. // dashed lines creation
  67157. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67158. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67159. vertexData.applyToMesh(dashedLines, options.updatable);
  67160. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67161. dashedLines._creationDataStorage.dashSize = dashSize;
  67162. dashedLines._creationDataStorage.gapSize = gapSize;
  67163. return dashedLines;
  67164. };
  67165. /**
  67166. * 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.
  67167. * * 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.
  67168. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67169. * * 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.
  67170. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67171. * * 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
  67172. * * 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
  67173. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67174. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67175. * * 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
  67176. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67177. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67178. * @param name defines the name of the mesh
  67179. * @param options defines the options used to create the mesh
  67180. * @param scene defines the hosting scene
  67181. * @returns the extruded shape mesh
  67182. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67183. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67184. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67185. */
  67186. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67187. if (scene === void 0) { scene = null; }
  67188. var path = options.path;
  67189. var shape = options.shape;
  67190. var scale = options.scale || 1;
  67191. var rotation = options.rotation || 0;
  67192. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67193. var updatable = options.updatable;
  67194. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67195. var instance = options.instance || null;
  67196. var invertUV = options.invertUV || false;
  67197. 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);
  67198. };
  67199. /**
  67200. * Creates an custom extruded shape mesh.
  67201. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67202. * * 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.
  67203. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67204. * * 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
  67205. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67206. * * 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
  67207. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67208. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67209. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67210. * * 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
  67211. * * 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
  67212. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67213. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67214. * * 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
  67215. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67216. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67217. * @param name defines the name of the mesh
  67218. * @param options defines the options used to create the mesh
  67219. * @param scene defines the hosting scene
  67220. * @returns the custom extruded shape mesh
  67221. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67222. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67223. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67224. */
  67225. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67226. var path = options.path;
  67227. var shape = options.shape;
  67228. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67229. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67230. var ribbonCloseArray = options.ribbonCloseArray || false;
  67231. var ribbonClosePath = options.ribbonClosePath || false;
  67232. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67233. var updatable = options.updatable;
  67234. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67235. var instance = options.instance;
  67236. var invertUV = options.invertUV || false;
  67237. 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);
  67238. };
  67239. /**
  67240. * Creates lathe mesh.
  67241. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67242. * * 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
  67243. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67244. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67245. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67246. * * 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
  67247. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67248. * * 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
  67249. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67250. * * 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
  67251. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67252. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67253. * @param name defines the name of the mesh
  67254. * @param options defines the options used to create the mesh
  67255. * @param scene defines the hosting scene
  67256. * @returns the lathe mesh
  67257. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67258. */
  67259. MeshBuilder.CreateLathe = function (name, options, scene) {
  67260. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67261. var closed = (options.closed === undefined) ? true : options.closed;
  67262. var shape = options.shape;
  67263. var radius = options.radius || 1;
  67264. var tessellation = options.tessellation || 64;
  67265. var clip = options.clip || 0;
  67266. var updatable = options.updatable;
  67267. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67268. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67269. var pi2 = Math.PI * 2;
  67270. var paths = new Array();
  67271. var invertUV = options.invertUV || false;
  67272. var i = 0;
  67273. var p = 0;
  67274. var step = pi2 / tessellation * arc;
  67275. var rotated;
  67276. var path = new Array();
  67277. for (i = 0; i <= tessellation - clip; i++) {
  67278. var path = [];
  67279. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67280. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67281. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67282. }
  67283. for (p = 0; p < shape.length; p++) {
  67284. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67285. path.push(rotated);
  67286. }
  67287. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67288. 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));
  67289. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67290. }
  67291. paths.push(path);
  67292. }
  67293. // lathe ribbon
  67294. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67295. return lathe;
  67296. };
  67297. /**
  67298. * Creates a plane mesh
  67299. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67300. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67301. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67302. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67303. * * 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
  67304. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67305. * @param name defines the name of the mesh
  67306. * @param options defines the options used to create the mesh
  67307. * @param scene defines the hosting scene
  67308. * @returns the plane mesh
  67309. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67310. */
  67311. MeshBuilder.CreatePlane = function (name, options, scene) {
  67312. var plane = new BABYLON.Mesh(name, scene);
  67313. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67314. plane._originalBuilderSideOrientation = options.sideOrientation;
  67315. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67316. vertexData.applyToMesh(plane, options.updatable);
  67317. if (options.sourcePlane) {
  67318. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67319. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67320. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67321. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67322. plane.rotate(vectorProduct, product);
  67323. }
  67324. }
  67325. return plane;
  67326. };
  67327. /**
  67328. * Creates a ground mesh
  67329. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67330. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67332. * @param name defines the name of the mesh
  67333. * @param options defines the options used to create the mesh
  67334. * @param scene defines the hosting scene
  67335. * @returns the ground mesh
  67336. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67337. */
  67338. MeshBuilder.CreateGround = function (name, options, scene) {
  67339. var ground = new BABYLON.GroundMesh(name, scene);
  67340. ground._setReady(false);
  67341. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67342. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67343. ground._width = options.width || 1;
  67344. ground._height = options.height || 1;
  67345. ground._maxX = ground._width / 2;
  67346. ground._maxZ = ground._height / 2;
  67347. ground._minX = -ground._maxX;
  67348. ground._minZ = -ground._maxZ;
  67349. var vertexData = BABYLON.VertexData.CreateGround(options);
  67350. vertexData.applyToMesh(ground, options.updatable);
  67351. ground._setReady(true);
  67352. return ground;
  67353. };
  67354. /**
  67355. * Creates a tiled ground mesh
  67356. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67357. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67358. * * 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
  67359. * * 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
  67360. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67361. * @param name defines the name of the mesh
  67362. * @param options defines the options used to create the mesh
  67363. * @param scene defines the hosting scene
  67364. * @returns the tiled ground mesh
  67365. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67366. */
  67367. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67368. var tiledGround = new BABYLON.Mesh(name, scene);
  67369. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67370. vertexData.applyToMesh(tiledGround, options.updatable);
  67371. return tiledGround;
  67372. };
  67373. /**
  67374. * Creates a ground mesh from a height map
  67375. * * The parameter `url` sets the URL of the height map image resource.
  67376. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67377. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67378. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67379. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67380. * * 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.
  67381. * * 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).
  67382. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67383. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67384. * @param name defines the name of the mesh
  67385. * @param url defines the url to the height map
  67386. * @param options defines the options used to create the mesh
  67387. * @param scene defines the hosting scene
  67388. * @returns the ground mesh
  67389. * @see http://doc.babylonjs.com/babylon101/height_map
  67390. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67391. */
  67392. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67393. var width = options.width || 10.0;
  67394. var height = options.height || 10.0;
  67395. var subdivisions = options.subdivisions || 1 | 0;
  67396. var minHeight = options.minHeight || 0.0;
  67397. var maxHeight = options.maxHeight || 1.0;
  67398. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67399. var alphaFilter = options.alphaFilter || 0.0;
  67400. var updatable = options.updatable;
  67401. var onReady = options.onReady;
  67402. var ground = new BABYLON.GroundMesh(name, scene);
  67403. ground._subdivisionsX = subdivisions;
  67404. ground._subdivisionsY = subdivisions;
  67405. ground._width = width;
  67406. ground._height = height;
  67407. ground._maxX = ground._width / 2.0;
  67408. ground._maxZ = ground._height / 2.0;
  67409. ground._minX = -ground._maxX;
  67410. ground._minZ = -ground._maxZ;
  67411. ground._setReady(false);
  67412. var onload = function (img) {
  67413. // Getting height map data
  67414. var canvas = document.createElement("canvas");
  67415. var context = canvas.getContext("2d");
  67416. if (!context) {
  67417. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67418. }
  67419. if (scene.isDisposed) {
  67420. return;
  67421. }
  67422. var bufferWidth = img.width;
  67423. var bufferHeight = img.height;
  67424. canvas.width = bufferWidth;
  67425. canvas.height = bufferHeight;
  67426. context.drawImage(img, 0, 0);
  67427. // Create VertexData from map data
  67428. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67429. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67430. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67431. width: width, height: height,
  67432. subdivisions: subdivisions,
  67433. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67434. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67435. alphaFilter: alphaFilter
  67436. });
  67437. vertexData.applyToMesh(ground, updatable);
  67438. //execute ready callback, if set
  67439. if (onReady) {
  67440. onReady(ground);
  67441. }
  67442. ground._setReady(true);
  67443. };
  67444. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67445. return ground;
  67446. };
  67447. /**
  67448. * Creates a polygon mesh
  67449. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67450. * * 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
  67451. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67452. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67453. * * 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)
  67454. * * Remember you can only change the shape positions, not their number when updating a polygon
  67455. * @param name defines the name of the mesh
  67456. * @param options defines the options used to create the mesh
  67457. * @param scene defines the hosting scene
  67458. * @returns the polygon mesh
  67459. */
  67460. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67461. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67462. var shape = options.shape;
  67463. var holes = options.holes || [];
  67464. var depth = options.depth || 0;
  67465. var contours = [];
  67466. var hole = [];
  67467. for (var i = 0; i < shape.length; i++) {
  67468. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67469. }
  67470. var epsilon = 0.00000001;
  67471. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67472. contours.pop();
  67473. }
  67474. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67475. for (var hNb = 0; hNb < holes.length; hNb++) {
  67476. hole = [];
  67477. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67478. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67479. }
  67480. polygonTriangulation.addHole(hole);
  67481. }
  67482. var polygon = polygonTriangulation.build(options.updatable, depth);
  67483. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67484. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67485. vertexData.applyToMesh(polygon, options.updatable);
  67486. return polygon;
  67487. };
  67488. ;
  67489. /**
  67490. * Creates an extruded polygon mesh, with depth in the Y direction.
  67491. * * 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)
  67492. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67493. * @param name defines the name of the mesh
  67494. * @param options defines the options used to create the mesh
  67495. * @param scene defines the hosting scene
  67496. * @returns the polygon mesh
  67497. */
  67498. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67499. return MeshBuilder.CreatePolygon(name, options, scene);
  67500. };
  67501. ;
  67502. /**
  67503. * Creates a tube mesh.
  67504. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67505. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67506. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67507. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67508. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67509. * * 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)
  67510. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67511. * * 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
  67512. * * 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
  67513. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67514. * * 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
  67515. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67516. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67517. * @param name defines the name of the mesh
  67518. * @param options defines the options used to create the mesh
  67519. * @param scene defines the hosting scene
  67520. * @returns the tube mesh
  67521. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67522. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67523. */
  67524. MeshBuilder.CreateTube = function (name, options, scene) {
  67525. var path = options.path;
  67526. var instance = options.instance;
  67527. var radius = 1.0;
  67528. if (options.radius !== undefined) {
  67529. radius = options.radius;
  67530. }
  67531. else if (instance) {
  67532. radius = instance._creationDataStorage.radius;
  67533. }
  67534. var tessellation = options.tessellation || 64 | 0;
  67535. var radiusFunction = options.radiusFunction || null;
  67536. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67537. var invertUV = options.invertUV || false;
  67538. var updatable = options.updatable;
  67539. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67540. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67541. // tube geometry
  67542. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67543. var tangents = path3D.getTangents();
  67544. var normals = path3D.getNormals();
  67545. var distances = path3D.getDistances();
  67546. var pi2 = Math.PI * 2;
  67547. var step = pi2 / tessellation * arc;
  67548. var returnRadius = function () { return radius; };
  67549. var radiusFunctionFinal = radiusFunction || returnRadius;
  67550. var circlePath;
  67551. var rad;
  67552. var normal;
  67553. var rotated;
  67554. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67555. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67556. for (var i = 0; i < path.length; i++) {
  67557. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67558. circlePath = Array(); // current circle array
  67559. normal = normals[i]; // current normal
  67560. for (var t = 0; t < tessellation; t++) {
  67561. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67562. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67563. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67564. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67565. circlePath[t] = rotated;
  67566. }
  67567. circlePaths[index] = circlePath;
  67568. index++;
  67569. }
  67570. // cap
  67571. var capPath = function (nbPoints, pathIndex) {
  67572. var pointCap = Array();
  67573. for (var i = 0; i < nbPoints; i++) {
  67574. pointCap.push(path[pathIndex]);
  67575. }
  67576. return pointCap;
  67577. };
  67578. switch (cap) {
  67579. case BABYLON.Mesh.NO_CAP:
  67580. break;
  67581. case BABYLON.Mesh.CAP_START:
  67582. circlePaths[0] = capPath(tessellation, 0);
  67583. circlePaths[1] = circlePaths[2].slice(0);
  67584. break;
  67585. case BABYLON.Mesh.CAP_END:
  67586. circlePaths[index] = circlePaths[index - 1].slice(0);
  67587. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67588. break;
  67589. case BABYLON.Mesh.CAP_ALL:
  67590. circlePaths[0] = capPath(tessellation, 0);
  67591. circlePaths[1] = circlePaths[2].slice(0);
  67592. circlePaths[index] = circlePaths[index - 1].slice(0);
  67593. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67594. break;
  67595. default:
  67596. break;
  67597. }
  67598. return circlePaths;
  67599. };
  67600. var path3D;
  67601. var pathArray;
  67602. if (instance) { // tube update
  67603. var arc = options.arc || instance.arc;
  67604. var storage = instance._creationDataStorage;
  67605. path3D = storage.path3D.update(path);
  67606. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67607. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67608. instance._creationDataStorage = new BABYLON._CreationDataStorage();
  67609. instance._creationDataStorage.path3D = path3D;
  67610. instance._creationDataStorage.pathArray = pathArray;
  67611. instance._creationDataStorage.arc = arc;
  67612. instance._creationDataStorage.radius = radius;
  67613. return instance;
  67614. }
  67615. // tube creation
  67616. path3D = new BABYLON.Path3D(path);
  67617. var newPathArray = new Array();
  67618. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67619. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67620. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67621. tube._creationDataStorage = new BABYLON._CreationDataStorage();
  67622. tube._creationDataStorage.pathArray = pathArray;
  67623. tube._creationDataStorage.path3D = path3D;
  67624. tube._creationDataStorage.tessellation = tessellation;
  67625. tube._creationDataStorage.cap = cap;
  67626. tube._creationDataStorage.arc = options.arc;
  67627. tube._creationDataStorage.radius = radius;
  67628. return tube;
  67629. };
  67630. /**
  67631. * Creates a polyhedron mesh
  67632. * * 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
  67633. * * The parameter `size` (positive float, default 1) sets the polygon size
  67634. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67635. * * 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`
  67636. * * 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
  67637. * * 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)`)
  67638. * * 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
  67639. * * 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
  67640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67641. * * 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
  67642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67643. * @param name defines the name of the mesh
  67644. * @param options defines the options used to create the mesh
  67645. * @param scene defines the hosting scene
  67646. * @returns the polyhedron mesh
  67647. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67648. */
  67649. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67650. var polyhedron = new BABYLON.Mesh(name, scene);
  67651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67652. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67653. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67654. vertexData.applyToMesh(polyhedron, options.updatable);
  67655. return polyhedron;
  67656. };
  67657. /**
  67658. * Creates a decal mesh.
  67659. * 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
  67660. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67661. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67662. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67663. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67664. * @param name defines the name of the mesh
  67665. * @param sourceMesh defines the mesh where the decal must be applied
  67666. * @param options defines the options used to create the mesh
  67667. * @param scene defines the hosting scene
  67668. * @returns the decal mesh
  67669. * @see http://doc.babylonjs.com/how_to/decals
  67670. */
  67671. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67672. var indices = sourceMesh.getIndices();
  67673. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67674. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67675. var position = options.position || BABYLON.Vector3.Zero();
  67676. var normal = options.normal || BABYLON.Vector3.Up();
  67677. var size = options.size || BABYLON.Vector3.One();
  67678. var angle = options.angle || 0;
  67679. // Getting correct rotation
  67680. if (!normal) {
  67681. var target = new BABYLON.Vector3(0, 0, 1);
  67682. var camera = sourceMesh.getScene().activeCamera;
  67683. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67684. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67685. }
  67686. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67687. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67688. var pitch = Math.atan2(normal.y, len);
  67689. // Matrix
  67690. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67691. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67692. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67693. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67694. var vertexData = new BABYLON.VertexData();
  67695. vertexData.indices = [];
  67696. vertexData.positions = [];
  67697. vertexData.normals = [];
  67698. vertexData.uvs = [];
  67699. var currentVertexDataIndex = 0;
  67700. var extractDecalVector3 = function (indexId) {
  67701. var result = new BABYLON.PositionNormalVertex();
  67702. if (!indices || !positions || !normals) {
  67703. return result;
  67704. }
  67705. var vertexId = indices[indexId];
  67706. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67707. // Send vector to decal local world
  67708. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67709. // Get normal
  67710. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67711. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67712. return result;
  67713. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67714. var clip = function (vertices, axis) {
  67715. if (vertices.length === 0) {
  67716. return vertices;
  67717. }
  67718. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67719. var clipVertices = function (v0, v1) {
  67720. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67721. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67722. };
  67723. var result = new Array();
  67724. for (var index = 0; index < vertices.length; index += 3) {
  67725. var v1Out;
  67726. var v2Out;
  67727. var v3Out;
  67728. var total = 0;
  67729. var nV1 = null;
  67730. var nV2 = null;
  67731. var nV3 = null;
  67732. var nV4 = null;
  67733. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67734. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67735. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67736. v1Out = d1 > 0;
  67737. v2Out = d2 > 0;
  67738. v3Out = d3 > 0;
  67739. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67740. switch (total) {
  67741. case 0:
  67742. result.push(vertices[index]);
  67743. result.push(vertices[index + 1]);
  67744. result.push(vertices[index + 2]);
  67745. break;
  67746. case 1:
  67747. if (v1Out) {
  67748. nV1 = vertices[index + 1];
  67749. nV2 = vertices[index + 2];
  67750. nV3 = clipVertices(vertices[index], nV1);
  67751. nV4 = clipVertices(vertices[index], nV2);
  67752. }
  67753. if (v2Out) {
  67754. nV1 = vertices[index];
  67755. nV2 = vertices[index + 2];
  67756. nV3 = clipVertices(vertices[index + 1], nV1);
  67757. nV4 = clipVertices(vertices[index + 1], nV2);
  67758. result.push(nV3);
  67759. result.push(nV2.clone());
  67760. result.push(nV1.clone());
  67761. result.push(nV2.clone());
  67762. result.push(nV3.clone());
  67763. result.push(nV4);
  67764. break;
  67765. }
  67766. if (v3Out) {
  67767. nV1 = vertices[index];
  67768. nV2 = vertices[index + 1];
  67769. nV3 = clipVertices(vertices[index + 2], nV1);
  67770. nV4 = clipVertices(vertices[index + 2], nV2);
  67771. }
  67772. if (nV1 && nV2 && nV3 && nV4) {
  67773. result.push(nV1.clone());
  67774. result.push(nV2.clone());
  67775. result.push(nV3);
  67776. result.push(nV4);
  67777. result.push(nV3.clone());
  67778. result.push(nV2.clone());
  67779. }
  67780. break;
  67781. case 2:
  67782. if (!v1Out) {
  67783. nV1 = vertices[index].clone();
  67784. nV2 = clipVertices(nV1, vertices[index + 1]);
  67785. nV3 = clipVertices(nV1, vertices[index + 2]);
  67786. result.push(nV1);
  67787. result.push(nV2);
  67788. result.push(nV3);
  67789. }
  67790. if (!v2Out) {
  67791. nV1 = vertices[index + 1].clone();
  67792. nV2 = clipVertices(nV1, vertices[index + 2]);
  67793. nV3 = clipVertices(nV1, vertices[index]);
  67794. result.push(nV1);
  67795. result.push(nV2);
  67796. result.push(nV3);
  67797. }
  67798. if (!v3Out) {
  67799. nV1 = vertices[index + 2].clone();
  67800. nV2 = clipVertices(nV1, vertices[index]);
  67801. nV3 = clipVertices(nV1, vertices[index + 1]);
  67802. result.push(nV1);
  67803. result.push(nV2);
  67804. result.push(nV3);
  67805. }
  67806. break;
  67807. case 3:
  67808. break;
  67809. }
  67810. }
  67811. return result;
  67812. };
  67813. for (var index = 0; index < indices.length; index += 3) {
  67814. var faceVertices = new Array();
  67815. faceVertices.push(extractDecalVector3(index));
  67816. faceVertices.push(extractDecalVector3(index + 1));
  67817. faceVertices.push(extractDecalVector3(index + 2));
  67818. // Clip
  67819. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  67820. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  67821. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  67822. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  67823. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  67824. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  67825. if (faceVertices.length === 0) {
  67826. continue;
  67827. }
  67828. // Add UVs and get back to world
  67829. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  67830. var vertex = faceVertices[vIndex];
  67831. //TODO check for Int32Array | Uint32Array | Uint16Array
  67832. vertexData.indices.push(currentVertexDataIndex);
  67833. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  67834. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  67835. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  67836. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  67837. currentVertexDataIndex++;
  67838. }
  67839. }
  67840. // Return mesh
  67841. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  67842. vertexData.applyToMesh(decal);
  67843. decal.position = position.clone();
  67844. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  67845. return decal;
  67846. };
  67847. // Privates
  67848. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  67849. // extrusion geometry
  67850. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  67851. var tangents = path3D.getTangents();
  67852. var normals = path3D.getNormals();
  67853. var binormals = path3D.getBinormals();
  67854. var distances = path3D.getDistances();
  67855. var angle = 0;
  67856. var returnScale = function () { return scale !== null ? scale : 1; };
  67857. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  67858. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  67859. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  67860. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67861. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67862. for (var i = 0; i < curve.length; i++) {
  67863. var shapePath = new Array();
  67864. var angleStep = rotate(i, distances[i]);
  67865. var scaleRatio = scl(i, distances[i]);
  67866. for (var p = 0; p < shape.length; p++) {
  67867. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  67868. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  67869. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  67870. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  67871. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  67872. shapePath[p] = rotated;
  67873. }
  67874. shapePaths[index] = shapePath;
  67875. angle += angleStep;
  67876. index++;
  67877. }
  67878. // cap
  67879. var capPath = function (shapePath) {
  67880. var pointCap = Array();
  67881. var barycenter = BABYLON.Vector3.Zero();
  67882. var i;
  67883. for (i = 0; i < shapePath.length; i++) {
  67884. barycenter.addInPlace(shapePath[i]);
  67885. }
  67886. barycenter.scaleInPlace(1.0 / shapePath.length);
  67887. for (i = 0; i < shapePath.length; i++) {
  67888. pointCap.push(barycenter);
  67889. }
  67890. return pointCap;
  67891. };
  67892. switch (cap) {
  67893. case BABYLON.Mesh.NO_CAP:
  67894. break;
  67895. case BABYLON.Mesh.CAP_START:
  67896. shapePaths[0] = capPath(shapePaths[2]);
  67897. shapePaths[1] = shapePaths[2];
  67898. break;
  67899. case BABYLON.Mesh.CAP_END:
  67900. shapePaths[index] = shapePaths[index - 1];
  67901. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67902. break;
  67903. case BABYLON.Mesh.CAP_ALL:
  67904. shapePaths[0] = capPath(shapePaths[2]);
  67905. shapePaths[1] = shapePaths[2];
  67906. shapePaths[index] = shapePaths[index - 1];
  67907. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67908. break;
  67909. default:
  67910. break;
  67911. }
  67912. return shapePaths;
  67913. };
  67914. var path3D;
  67915. var pathArray;
  67916. if (instance) { // instance update
  67917. var storage = instance._creationDataStorage;
  67918. path3D = storage.path3D.update(curve);
  67919. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  67920. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  67921. return instance;
  67922. }
  67923. // extruded shape creation
  67924. path3D = new BABYLON.Path3D(curve);
  67925. var newShapePaths = new Array();
  67926. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67927. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67928. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67929. extrudedGeneric._creationDataStorage = new BABYLON._CreationDataStorage();
  67930. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  67931. extrudedGeneric._creationDataStorage.path3D = path3D;
  67932. extrudedGeneric._creationDataStorage.cap = cap;
  67933. return extrudedGeneric;
  67934. };
  67935. return MeshBuilder;
  67936. }());
  67937. BABYLON.MeshBuilder = MeshBuilder;
  67938. })(BABYLON || (BABYLON = {}));
  67939. //# sourceMappingURL=babylon.meshBuilder.js.map
  67940. var BABYLON;
  67941. (function (BABYLON) {
  67942. /**
  67943. * Draco compression (https://google.github.io/draco/)
  67944. *
  67945. * This class wraps the Draco module.
  67946. *
  67947. * **Encoder**
  67948. *
  67949. * The encoder is not currently implemented.
  67950. *
  67951. * **Decoder**
  67952. *
  67953. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  67954. *
  67955. * To update the configuration, use the following code:
  67956. * ```javascript
  67957. * BABYLON.DracoCompression.Configuration = {
  67958. * decoder: {
  67959. * wasmUrl: "<url to the WebAssembly library>",
  67960. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67961. * fallbackUrl: "<url to the fallback JavaScript library>",
  67962. * }
  67963. * };
  67964. * ```
  67965. *
  67966. * 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.
  67967. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67968. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67969. *
  67970. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67971. * ```javascript
  67972. * var dracoCompression = new BABYLON.DracoCompression();
  67973. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67974. * [BABYLON.VertexBuffer.PositionKind]: 0
  67975. * });
  67976. * ```
  67977. *
  67978. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67979. */
  67980. var DracoCompression = /** @class */ (function () {
  67981. /**
  67982. * Constructor
  67983. */
  67984. function DracoCompression() {
  67985. }
  67986. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67987. /**
  67988. * Returns true if the decoder is available.
  67989. */
  67990. get: function () {
  67991. if (typeof DracoDecoderModule !== "undefined") {
  67992. return true;
  67993. }
  67994. var decoder = DracoCompression.Configuration.decoder;
  67995. if (decoder) {
  67996. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67997. return true;
  67998. }
  67999. if (decoder.fallbackUrl) {
  68000. return true;
  68001. }
  68002. }
  68003. return false;
  68004. },
  68005. enumerable: true,
  68006. configurable: true
  68007. });
  68008. /**
  68009. * Stop all async operations and release resources.
  68010. */
  68011. DracoCompression.prototype.dispose = function () {
  68012. };
  68013. /**
  68014. * Decode Draco compressed mesh data to vertex data.
  68015. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68016. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68017. * @returns A promise that resolves with the decoded vertex data
  68018. */
  68019. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68020. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68021. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68022. var module = wrappedModule.module;
  68023. var vertexData = new BABYLON.VertexData();
  68024. var buffer = new module.DecoderBuffer();
  68025. buffer.Init(dataView, dataView.byteLength);
  68026. var decoder = new module.Decoder();
  68027. var geometry;
  68028. var status;
  68029. try {
  68030. var type = decoder.GetEncodedGeometryType(buffer);
  68031. switch (type) {
  68032. case module.TRIANGULAR_MESH:
  68033. geometry = new module.Mesh();
  68034. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68035. break;
  68036. case module.POINT_CLOUD:
  68037. geometry = new module.PointCloud();
  68038. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68039. break;
  68040. default:
  68041. throw new Error("Invalid geometry type " + type);
  68042. }
  68043. if (!status.ok() || !geometry.ptr) {
  68044. throw new Error(status.error_msg());
  68045. }
  68046. var numPoints = geometry.num_points();
  68047. if (type === module.TRIANGULAR_MESH) {
  68048. var numFaces = geometry.num_faces();
  68049. var faceIndices = new module.DracoInt32Array();
  68050. try {
  68051. var indices = new Uint32Array(numFaces * 3);
  68052. for (var i = 0; i < numFaces; i++) {
  68053. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68054. var offset = i * 3;
  68055. indices[offset + 0] = faceIndices.GetValue(0);
  68056. indices[offset + 1] = faceIndices.GetValue(1);
  68057. indices[offset + 2] = faceIndices.GetValue(2);
  68058. }
  68059. vertexData.indices = indices;
  68060. }
  68061. finally {
  68062. module.destroy(faceIndices);
  68063. }
  68064. }
  68065. for (var kind in attributes) {
  68066. var uniqueId = attributes[kind];
  68067. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68068. var dracoData = new module.DracoFloat32Array();
  68069. try {
  68070. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68071. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68072. for (var i = 0; i < babylonData.length; i++) {
  68073. babylonData[i] = dracoData.GetValue(i);
  68074. }
  68075. vertexData.set(babylonData, kind);
  68076. }
  68077. finally {
  68078. module.destroy(dracoData);
  68079. }
  68080. }
  68081. }
  68082. finally {
  68083. if (geometry) {
  68084. module.destroy(geometry);
  68085. }
  68086. module.destroy(decoder);
  68087. module.destroy(buffer);
  68088. }
  68089. return vertexData;
  68090. });
  68091. };
  68092. DracoCompression._GetDecoderModule = function () {
  68093. if (!DracoCompression._DecoderModulePromise) {
  68094. var promise = null;
  68095. var config_1 = {};
  68096. if (typeof DracoDecoderModule !== "undefined") {
  68097. promise = Promise.resolve();
  68098. }
  68099. else {
  68100. var decoder = DracoCompression.Configuration.decoder;
  68101. if (decoder) {
  68102. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68103. promise = Promise.all([
  68104. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68105. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68106. config_1.wasmBinary = data;
  68107. })
  68108. ]);
  68109. }
  68110. else if (decoder.fallbackUrl) {
  68111. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68112. }
  68113. }
  68114. }
  68115. if (!promise) {
  68116. throw new Error("Draco decoder module is not available");
  68117. }
  68118. DracoCompression._DecoderModulePromise = promise.then(function () {
  68119. return new Promise(function (resolve) {
  68120. config_1.onModuleLoaded = function (decoderModule) {
  68121. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68122. resolve({ module: decoderModule });
  68123. };
  68124. DracoDecoderModule(config_1);
  68125. });
  68126. });
  68127. }
  68128. return DracoCompression._DecoderModulePromise;
  68129. };
  68130. DracoCompression._LoadScriptAsync = function (url) {
  68131. return new Promise(function (resolve, reject) {
  68132. BABYLON.Tools.LoadScript(url, function () {
  68133. resolve();
  68134. }, function (message) {
  68135. reject(new Error(message));
  68136. });
  68137. });
  68138. };
  68139. DracoCompression._LoadFileAsync = function (url) {
  68140. return new Promise(function (resolve, reject) {
  68141. BABYLON.Tools.LoadFile(url, function (data) {
  68142. resolve(data);
  68143. }, undefined, undefined, true, function (request, exception) {
  68144. reject(exception);
  68145. });
  68146. });
  68147. };
  68148. /**
  68149. * The configuration. Defaults to the following urls:
  68150. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68151. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68152. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68153. */
  68154. DracoCompression.Configuration = {
  68155. decoder: {
  68156. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68157. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68158. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68159. }
  68160. };
  68161. return DracoCompression;
  68162. }());
  68163. BABYLON.DracoCompression = DracoCompression;
  68164. })(BABYLON || (BABYLON = {}));
  68165. //# sourceMappingURL=babylon.dracoCompression.js.map
  68166. var BABYLON;
  68167. (function (BABYLON) {
  68168. // Sets the default audio engine to Babylon JS.
  68169. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68170. /**
  68171. * This represents the default audio engine used in babylon.
  68172. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68173. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68174. */
  68175. var AudioEngine = /** @class */ (function () {
  68176. /**
  68177. * Instantiates a new audio engine.
  68178. *
  68179. * There should be only one per page as some browsers restrict the number
  68180. * of audio contexts you can create.
  68181. * @param engine defines the hosting engine
  68182. */
  68183. function AudioEngine(engine) {
  68184. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68185. var _this = this;
  68186. this._audioContext = null;
  68187. this._audioContextInitialized = false;
  68188. this._muteButton = null;
  68189. /**
  68190. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68191. */
  68192. this.canUseWebAudio = false;
  68193. /**
  68194. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68195. * @ignoreNaming
  68196. */
  68197. this.WarnedWebAudioUnsupported = false;
  68198. /**
  68199. * Gets whether or not mp3 are supported by your browser.
  68200. */
  68201. this.isMP3supported = false;
  68202. /**
  68203. * Gets whether or not ogg are supported by your browser.
  68204. */
  68205. this.isOGGsupported = false;
  68206. /**
  68207. * Gets whether audio has been unlocked on the device.
  68208. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68209. * a user interaction has happened.
  68210. */
  68211. this.unlocked = true;
  68212. /**
  68213. * Defines if the audio engine relies on a custom unlocked button.
  68214. * In this case, the embedded button will not be displayed.
  68215. */
  68216. this.useCustomUnlockedButton = false;
  68217. /**
  68218. * Event raised when audio has been unlocked on the browser.
  68219. */
  68220. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68221. /**
  68222. * Event raised when audio has been locked on the browser.
  68223. */
  68224. this.onAudioLockedObservable = new BABYLON.Observable();
  68225. this._tryToRun = false;
  68226. this._onResize = function () {
  68227. _this._moveButtonToTopLeft();
  68228. };
  68229. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68230. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68231. this.canUseWebAudio = true;
  68232. }
  68233. var audioElem = document.createElement('audio');
  68234. this._engine = engine;
  68235. try {
  68236. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68237. this.isMP3supported = true;
  68238. }
  68239. }
  68240. catch (e) {
  68241. // protect error during capability check.
  68242. }
  68243. try {
  68244. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68245. this.isOGGsupported = true;
  68246. }
  68247. }
  68248. catch (e) {
  68249. // protect error during capability check.
  68250. }
  68251. }
  68252. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68253. /**
  68254. * Gets the current AudioContext if available.
  68255. */
  68256. get: function () {
  68257. if (!this._audioContextInitialized) {
  68258. this._initializeAudioContext();
  68259. }
  68260. else {
  68261. if (!this.unlocked && !this._muteButton) {
  68262. this._displayMuteButton();
  68263. }
  68264. }
  68265. return this._audioContext;
  68266. },
  68267. enumerable: true,
  68268. configurable: true
  68269. });
  68270. /**
  68271. * Flags the audio engine in Locked state.
  68272. * This happens due to new browser policies preventing audio to autoplay.
  68273. */
  68274. AudioEngine.prototype.lock = function () {
  68275. this._triggerSuspendedState();
  68276. };
  68277. /**
  68278. * Unlocks the audio engine once a user action has been done on the dom.
  68279. * This is helpful to resume play once browser policies have been satisfied.
  68280. */
  68281. AudioEngine.prototype.unlock = function () {
  68282. this._triggerRunningState();
  68283. };
  68284. AudioEngine.prototype._resumeAudioContext = function () {
  68285. var result;
  68286. if (this._audioContext.resume) {
  68287. result = this._audioContext.resume();
  68288. }
  68289. return result || Promise.resolve();
  68290. };
  68291. AudioEngine.prototype._initializeAudioContext = function () {
  68292. var _this = this;
  68293. try {
  68294. if (this.canUseWebAudio) {
  68295. this._audioContext = new AudioContext();
  68296. // create a global volume gain node
  68297. this.masterGain = this._audioContext.createGain();
  68298. this.masterGain.gain.value = 1;
  68299. this.masterGain.connect(this._audioContext.destination);
  68300. this._audioContextInitialized = true;
  68301. if (this._audioContext.state === "running") {
  68302. // Do not wait for the promise to unlock.
  68303. this._triggerRunningState();
  68304. }
  68305. else {
  68306. if (this._audioContext && this._audioContext.resume) {
  68307. this._resumeAudioContext().then(function () {
  68308. _this._triggerRunningState();
  68309. }).catch(function () {
  68310. // Can not resume automatically
  68311. // Needs user action
  68312. _this.lock();
  68313. });
  68314. }
  68315. }
  68316. }
  68317. }
  68318. catch (e) {
  68319. this.canUseWebAudio = false;
  68320. BABYLON.Tools.Error("Web Audio: " + e.message);
  68321. }
  68322. };
  68323. AudioEngine.prototype._triggerRunningState = function () {
  68324. var _this = this;
  68325. if (this._tryToRun) {
  68326. return;
  68327. }
  68328. this._tryToRun = true;
  68329. this._resumeAudioContext()
  68330. .then(function () {
  68331. _this._tryToRun = false;
  68332. _this.unlocked = true;
  68333. if (_this._muteButton) {
  68334. _this._hideMuteButton();
  68335. }
  68336. // Notify users that the audio stack is unlocked/unmuted
  68337. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68338. }).catch(function () {
  68339. _this._tryToRun = false;
  68340. _this.unlocked = false;
  68341. });
  68342. };
  68343. AudioEngine.prototype._triggerSuspendedState = function () {
  68344. this.unlocked = false;
  68345. this.onAudioLockedObservable.notifyObservers(this);
  68346. this._displayMuteButton();
  68347. };
  68348. AudioEngine.prototype._displayMuteButton = function () {
  68349. var _this = this;
  68350. if (this.useCustomUnlockedButton) {
  68351. return;
  68352. }
  68353. this._canvas = this._engine.getRenderingCanvas();
  68354. this._muteButton = document.createElement("BUTTON");
  68355. this._muteButton.className = "babylonUnmuteIcon";
  68356. this._muteButton.id = "babylonUnmuteIconBtn";
  68357. this._muteButton.title = "Unmute";
  68358. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  68359. var style = document.createElement('style');
  68360. style.appendChild(document.createTextNode(css));
  68361. document.getElementsByTagName('head')[0].appendChild(style);
  68362. document.body.appendChild(this._muteButton);
  68363. this._moveButtonToTopLeft();
  68364. this._muteButton.addEventListener('mousedown', function () {
  68365. _this._triggerRunningState();
  68366. }, true);
  68367. this._muteButton.addEventListener('touchend', function () {
  68368. _this._triggerRunningState();
  68369. }, true);
  68370. this._muteButton.addEventListener('click', function () {
  68371. _this._triggerRunningState();
  68372. }, true);
  68373. window.addEventListener("resize", this._onResize);
  68374. };
  68375. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68376. if (this._canvas && this._muteButton) {
  68377. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68378. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68379. }
  68380. };
  68381. AudioEngine.prototype._hideMuteButton = function () {
  68382. if (this._muteButton) {
  68383. document.body.removeChild(this._muteButton);
  68384. this._muteButton = null;
  68385. }
  68386. };
  68387. /**
  68388. * Destroy and release the resources associated with the audio ccontext.
  68389. */
  68390. AudioEngine.prototype.dispose = function () {
  68391. if (this.canUseWebAudio && this._audioContextInitialized) {
  68392. if (this._connectedAnalyser && this._audioContext) {
  68393. this._connectedAnalyser.stopDebugCanvas();
  68394. this._connectedAnalyser.dispose();
  68395. this.masterGain.disconnect();
  68396. this.masterGain.connect(this._audioContext.destination);
  68397. this._connectedAnalyser = null;
  68398. }
  68399. this.masterGain.gain.value = 1;
  68400. }
  68401. this.WarnedWebAudioUnsupported = false;
  68402. this._hideMuteButton();
  68403. window.removeEventListener("resize", this._onResize);
  68404. this.onAudioUnlockedObservable.clear();
  68405. this.onAudioLockedObservable.clear();
  68406. };
  68407. /**
  68408. * Gets the global volume sets on the master gain.
  68409. * @returns the global volume if set or -1 otherwise
  68410. */
  68411. AudioEngine.prototype.getGlobalVolume = function () {
  68412. if (this.canUseWebAudio && this._audioContextInitialized) {
  68413. return this.masterGain.gain.value;
  68414. }
  68415. else {
  68416. return -1;
  68417. }
  68418. };
  68419. /**
  68420. * Sets the global volume of your experience (sets on the master gain).
  68421. * @param newVolume Defines the new global volume of the application
  68422. */
  68423. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68424. if (this.canUseWebAudio && this._audioContextInitialized) {
  68425. this.masterGain.gain.value = newVolume;
  68426. }
  68427. };
  68428. /**
  68429. * Connect the audio engine to an audio analyser allowing some amazing
  68430. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68431. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68432. * @param analyser The analyser to connect to the engine
  68433. */
  68434. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68435. if (this._connectedAnalyser) {
  68436. this._connectedAnalyser.stopDebugCanvas();
  68437. }
  68438. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68439. this._connectedAnalyser = analyser;
  68440. this.masterGain.disconnect();
  68441. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68442. }
  68443. };
  68444. return AudioEngine;
  68445. }());
  68446. BABYLON.AudioEngine = AudioEngine;
  68447. })(BABYLON || (BABYLON = {}));
  68448. //# sourceMappingURL=babylon.audioEngine.js.map
  68449. var BABYLON;
  68450. (function (BABYLON) {
  68451. /**
  68452. * Defines a sound that can be played in the application.
  68453. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68454. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68455. */
  68456. var Sound = /** @class */ (function () {
  68457. /**
  68458. * Create a sound and attach it to a scene
  68459. * @param name Name of your sound
  68460. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68461. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68462. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68463. */
  68464. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68465. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68466. var _this = this;
  68467. /**
  68468. * Does the sound autoplay once loaded.
  68469. */
  68470. this.autoplay = false;
  68471. /**
  68472. * Does the sound loop after it finishes playing once.
  68473. */
  68474. this.loop = false;
  68475. /**
  68476. * Does the sound use a custom attenuation curve to simulate the falloff
  68477. * happening when the source gets further away from the camera.
  68478. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68479. */
  68480. this.useCustomAttenuation = false;
  68481. /**
  68482. * Is this sound currently played.
  68483. */
  68484. this.isPlaying = false;
  68485. /**
  68486. * Is this sound currently paused.
  68487. */
  68488. this.isPaused = false;
  68489. /**
  68490. * Does this sound enables spatial sound.
  68491. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68492. */
  68493. this.spatialSound = false;
  68494. /**
  68495. * Define the reference distance the sound should be heard perfectly.
  68496. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68497. */
  68498. this.refDistance = 1;
  68499. /**
  68500. * Define the roll off factor of spatial sounds.
  68501. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68502. */
  68503. this.rolloffFactor = 1;
  68504. /**
  68505. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68506. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68507. */
  68508. this.maxDistance = 100;
  68509. /**
  68510. * Define the distance attenuation model the sound will follow.
  68511. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68512. */
  68513. this.distanceModel = "linear";
  68514. /**
  68515. * Observable event when the current playing sound finishes.
  68516. */
  68517. this.onEndedObservable = new BABYLON.Observable();
  68518. this._panningModel = "equalpower";
  68519. this._playbackRate = 1;
  68520. this._streaming = false;
  68521. this._startTime = 0;
  68522. this._startOffset = 0;
  68523. this._position = BABYLON.Vector3.Zero();
  68524. /** @hidden */
  68525. this._positionInEmitterSpace = false;
  68526. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68527. this._volume = 1;
  68528. this._isReadyToPlay = false;
  68529. this._isDirectional = false;
  68530. // Used if you'd like to create a directional sound.
  68531. // If not set, the sound will be omnidirectional
  68532. this._coneInnerAngle = 360;
  68533. this._coneOuterAngle = 360;
  68534. this._coneOuterGain = 0;
  68535. this._isOutputConnected = false;
  68536. this._urlType = "Unknown";
  68537. this.name = name;
  68538. this._scene = scene;
  68539. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68540. if (!compo) {
  68541. compo = new BABYLON.AudioSceneComponent(scene);
  68542. scene._addComponent(compo);
  68543. }
  68544. this._readyToPlayCallback = readyToPlayCallback;
  68545. // Default custom attenuation function is a linear attenuation
  68546. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68547. if (currentDistance < maxDistance) {
  68548. return currentVolume * (1 - currentDistance / maxDistance);
  68549. }
  68550. else {
  68551. return 0;
  68552. }
  68553. };
  68554. if (options) {
  68555. this.autoplay = options.autoplay || false;
  68556. this.loop = options.loop || false;
  68557. // if volume === 0, we need another way to check this option
  68558. if (options.volume !== undefined) {
  68559. this._volume = options.volume;
  68560. }
  68561. this.spatialSound = options.spatialSound || false;
  68562. this.maxDistance = options.maxDistance || 100;
  68563. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68564. this.rolloffFactor = options.rolloffFactor || 1;
  68565. this.refDistance = options.refDistance || 1;
  68566. this.distanceModel = options.distanceModel || "linear";
  68567. this._playbackRate = options.playbackRate || 1;
  68568. this._streaming = options.streaming || false;
  68569. }
  68570. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68571. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68572. this._soundGain.gain.value = this._volume;
  68573. this._inputAudioNode = this._soundGain;
  68574. this._outputAudioNode = this._soundGain;
  68575. if (this.spatialSound) {
  68576. this._createSpatialParameters();
  68577. }
  68578. this._scene.mainSoundTrack.AddSound(this);
  68579. var validParameter = true;
  68580. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68581. if (urlOrArrayBuffer) {
  68582. try {
  68583. if (typeof (urlOrArrayBuffer) === "string") {
  68584. this._urlType = "String";
  68585. }
  68586. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68587. this._urlType = "ArrayBuffer";
  68588. }
  68589. else if (urlOrArrayBuffer instanceof MediaStream) {
  68590. this._urlType = "MediaStream";
  68591. }
  68592. else if (Array.isArray(urlOrArrayBuffer)) {
  68593. this._urlType = "Array";
  68594. }
  68595. var urls = [];
  68596. var codecSupportedFound = false;
  68597. switch (this._urlType) {
  68598. case "MediaStream":
  68599. this._streaming = true;
  68600. this._isReadyToPlay = true;
  68601. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68602. if (this.autoplay) {
  68603. this.play();
  68604. }
  68605. if (this._readyToPlayCallback) {
  68606. this._readyToPlayCallback();
  68607. }
  68608. break;
  68609. case "ArrayBuffer":
  68610. if (urlOrArrayBuffer.byteLength > 0) {
  68611. codecSupportedFound = true;
  68612. this._soundLoaded(urlOrArrayBuffer);
  68613. }
  68614. break;
  68615. case "String":
  68616. urls.push(urlOrArrayBuffer);
  68617. case "Array":
  68618. if (urls.length === 0)
  68619. urls = urlOrArrayBuffer;
  68620. // If we found a supported format, we load it immediately and stop the loop
  68621. for (var i = 0; i < urls.length; i++) {
  68622. var url = urls[i];
  68623. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68624. codecSupportedFound = true;
  68625. }
  68626. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68627. codecSupportedFound = true;
  68628. }
  68629. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68630. codecSupportedFound = true;
  68631. }
  68632. if (url.indexOf("blob:") !== -1) {
  68633. codecSupportedFound = true;
  68634. }
  68635. if (codecSupportedFound) {
  68636. // Loading sound using XHR2
  68637. if (!this._streaming) {
  68638. this._scene._loadFile(url, function (data) {
  68639. _this._soundLoaded(data);
  68640. }, undefined, true, true, function (exception) {
  68641. if (exception) {
  68642. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68643. }
  68644. BABYLON.Tools.Error("Sound creation aborted.");
  68645. _this._scene.mainSoundTrack.RemoveSound(_this);
  68646. });
  68647. }
  68648. // Streaming sound using HTML5 Audio tag
  68649. else {
  68650. this._htmlAudioElement = new Audio(url);
  68651. this._htmlAudioElement.controls = false;
  68652. this._htmlAudioElement.loop = this.loop;
  68653. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68654. this._htmlAudioElement.preload = "auto";
  68655. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68656. _this._isReadyToPlay = true;
  68657. if (_this.autoplay) {
  68658. _this.play();
  68659. }
  68660. if (_this._readyToPlayCallback) {
  68661. _this._readyToPlayCallback();
  68662. }
  68663. });
  68664. document.body.appendChild(this._htmlAudioElement);
  68665. this._htmlAudioElement.load();
  68666. }
  68667. break;
  68668. }
  68669. }
  68670. break;
  68671. default:
  68672. validParameter = false;
  68673. break;
  68674. }
  68675. if (!validParameter) {
  68676. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68677. }
  68678. else {
  68679. if (!codecSupportedFound) {
  68680. this._isReadyToPlay = true;
  68681. // Simulating a ready to play event to avoid breaking code path
  68682. if (this._readyToPlayCallback) {
  68683. window.setTimeout(function () {
  68684. if (_this._readyToPlayCallback) {
  68685. _this._readyToPlayCallback();
  68686. }
  68687. }, 1000);
  68688. }
  68689. }
  68690. }
  68691. }
  68692. catch (ex) {
  68693. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68694. this._scene.mainSoundTrack.RemoveSound(this);
  68695. }
  68696. }
  68697. }
  68698. else {
  68699. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68700. this._scene.mainSoundTrack.AddSound(this);
  68701. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68702. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68703. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68704. }
  68705. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68706. if (this._readyToPlayCallback) {
  68707. window.setTimeout(function () {
  68708. if (_this._readyToPlayCallback) {
  68709. _this._readyToPlayCallback();
  68710. }
  68711. }, 1000);
  68712. }
  68713. }
  68714. }
  68715. /**
  68716. * Release the sound and its associated resources
  68717. */
  68718. Sound.prototype.dispose = function () {
  68719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68720. if (this.isPlaying) {
  68721. this.stop();
  68722. }
  68723. this._isReadyToPlay = false;
  68724. if (this.soundTrackId === -1) {
  68725. this._scene.mainSoundTrack.RemoveSound(this);
  68726. }
  68727. else if (this._scene.soundTracks) {
  68728. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68729. }
  68730. if (this._soundGain) {
  68731. this._soundGain.disconnect();
  68732. this._soundGain = null;
  68733. }
  68734. if (this._soundPanner) {
  68735. this._soundPanner.disconnect();
  68736. this._soundPanner = null;
  68737. }
  68738. if (this._soundSource) {
  68739. this._soundSource.disconnect();
  68740. this._soundSource = null;
  68741. }
  68742. this._audioBuffer = null;
  68743. if (this._htmlAudioElement) {
  68744. this._htmlAudioElement.pause();
  68745. this._htmlAudioElement.src = "";
  68746. document.body.removeChild(this._htmlAudioElement);
  68747. }
  68748. if (this._streamingSource) {
  68749. this._streamingSource.disconnect();
  68750. }
  68751. if (this._connectedMesh && this._registerFunc) {
  68752. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68753. this._connectedMesh = null;
  68754. }
  68755. }
  68756. };
  68757. /**
  68758. * Gets if the sounds is ready to be played or not.
  68759. * @returns true if ready, otherwise false
  68760. */
  68761. Sound.prototype.isReady = function () {
  68762. return this._isReadyToPlay;
  68763. };
  68764. Sound.prototype._soundLoaded = function (audioData) {
  68765. var _this = this;
  68766. if (!BABYLON.Engine.audioEngine.audioContext) {
  68767. return;
  68768. }
  68769. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68770. _this._audioBuffer = buffer;
  68771. _this._isReadyToPlay = true;
  68772. if (_this.autoplay) {
  68773. _this.play();
  68774. }
  68775. if (_this._readyToPlayCallback) {
  68776. _this._readyToPlayCallback();
  68777. }
  68778. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68779. };
  68780. /**
  68781. * Sets the data of the sound from an audiobuffer
  68782. * @param audioBuffer The audioBuffer containing the data
  68783. */
  68784. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68785. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68786. this._audioBuffer = audioBuffer;
  68787. this._isReadyToPlay = true;
  68788. }
  68789. };
  68790. /**
  68791. * Updates the current sounds options such as maxdistance, loop...
  68792. * @param options A JSON object containing values named as the object properties
  68793. */
  68794. Sound.prototype.updateOptions = function (options) {
  68795. if (options) {
  68796. this.loop = options.loop || this.loop;
  68797. this.maxDistance = options.maxDistance || this.maxDistance;
  68798. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  68799. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  68800. this.refDistance = options.refDistance || this.refDistance;
  68801. this.distanceModel = options.distanceModel || this.distanceModel;
  68802. this._playbackRate = options.playbackRate || this._playbackRate;
  68803. this._updateSpatialParameters();
  68804. if (this.isPlaying) {
  68805. if (this._streaming && this._htmlAudioElement) {
  68806. this._htmlAudioElement.playbackRate = this._playbackRate;
  68807. }
  68808. else {
  68809. if (this._soundSource) {
  68810. this._soundSource.playbackRate.value = this._playbackRate;
  68811. }
  68812. }
  68813. }
  68814. }
  68815. };
  68816. Sound.prototype._createSpatialParameters = function () {
  68817. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68818. if (this._scene.headphone) {
  68819. this._panningModel = "HRTF";
  68820. }
  68821. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  68822. this._updateSpatialParameters();
  68823. this._soundPanner.connect(this._outputAudioNode);
  68824. this._inputAudioNode = this._soundPanner;
  68825. }
  68826. };
  68827. Sound.prototype._updateSpatialParameters = function () {
  68828. if (this.spatialSound && this._soundPanner) {
  68829. if (this.useCustomAttenuation) {
  68830. // Tricks to disable in a way embedded Web Audio attenuation
  68831. this._soundPanner.distanceModel = "linear";
  68832. this._soundPanner.maxDistance = Number.MAX_VALUE;
  68833. this._soundPanner.refDistance = 1;
  68834. this._soundPanner.rolloffFactor = 1;
  68835. this._soundPanner.panningModel = this._panningModel;
  68836. }
  68837. else {
  68838. this._soundPanner.distanceModel = this.distanceModel;
  68839. this._soundPanner.maxDistance = this.maxDistance;
  68840. this._soundPanner.refDistance = this.refDistance;
  68841. this._soundPanner.rolloffFactor = this.rolloffFactor;
  68842. this._soundPanner.panningModel = this._panningModel;
  68843. }
  68844. }
  68845. };
  68846. /**
  68847. * Switch the panning model to HRTF:
  68848. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68849. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68850. */
  68851. Sound.prototype.switchPanningModelToHRTF = function () {
  68852. this._panningModel = "HRTF";
  68853. this._switchPanningModel();
  68854. };
  68855. /**
  68856. * Switch the panning model to Equal Power:
  68857. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68858. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68859. */
  68860. Sound.prototype.switchPanningModelToEqualPower = function () {
  68861. this._panningModel = "equalpower";
  68862. this._switchPanningModel();
  68863. };
  68864. Sound.prototype._switchPanningModel = function () {
  68865. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68866. this._soundPanner.panningModel = this._panningModel;
  68867. }
  68868. };
  68869. /**
  68870. * Connect this sound to a sound track audio node like gain...
  68871. * @param soundTrackAudioNode the sound track audio node to connect to
  68872. */
  68873. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  68874. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68875. if (this._isOutputConnected) {
  68876. this._outputAudioNode.disconnect();
  68877. }
  68878. this._outputAudioNode.connect(soundTrackAudioNode);
  68879. this._isOutputConnected = true;
  68880. }
  68881. };
  68882. /**
  68883. * Transform this sound into a directional source
  68884. * @param coneInnerAngle Size of the inner cone in degree
  68885. * @param coneOuterAngle Size of the outer cone in degree
  68886. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  68887. */
  68888. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  68889. if (coneOuterAngle < coneInnerAngle) {
  68890. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  68891. return;
  68892. }
  68893. this._coneInnerAngle = coneInnerAngle;
  68894. this._coneOuterAngle = coneOuterAngle;
  68895. this._coneOuterGain = coneOuterGain;
  68896. this._isDirectional = true;
  68897. if (this.isPlaying && this.loop) {
  68898. this.stop();
  68899. this.play();
  68900. }
  68901. };
  68902. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  68903. /**
  68904. * Gets or sets the inner angle for the directional cone.
  68905. */
  68906. get: function () {
  68907. return this._coneInnerAngle;
  68908. },
  68909. /**
  68910. * Gets or sets the inner angle for the directional cone.
  68911. */
  68912. set: function (value) {
  68913. if (value != this._coneInnerAngle) {
  68914. if (this._coneOuterAngle < value) {
  68915. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68916. return;
  68917. }
  68918. this._coneInnerAngle = value;
  68919. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68920. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68921. }
  68922. }
  68923. },
  68924. enumerable: true,
  68925. configurable: true
  68926. });
  68927. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68928. /**
  68929. * Gets or sets the outer angle for the directional cone.
  68930. */
  68931. get: function () {
  68932. return this._coneOuterAngle;
  68933. },
  68934. /**
  68935. * Gets or sets the outer angle for the directional cone.
  68936. */
  68937. set: function (value) {
  68938. if (value != this._coneOuterAngle) {
  68939. if (value < this._coneInnerAngle) {
  68940. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68941. return;
  68942. }
  68943. this._coneOuterAngle = value;
  68944. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68945. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68946. }
  68947. }
  68948. },
  68949. enumerable: true,
  68950. configurable: true
  68951. });
  68952. /**
  68953. * Sets the position of the emitter if spatial sound is enabled
  68954. * @param newPosition Defines the new posisiton
  68955. */
  68956. Sound.prototype.setPosition = function (newPosition) {
  68957. this._position = newPosition;
  68958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68959. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68960. }
  68961. };
  68962. /**
  68963. * Sets the local direction of the emitter if spatial sound is enabled
  68964. * @param newLocalDirection Defines the new local direction
  68965. */
  68966. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68967. this._localDirection = newLocalDirection;
  68968. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68969. this._updateDirection();
  68970. }
  68971. };
  68972. Sound.prototype._updateDirection = function () {
  68973. if (!this._connectedMesh || !this._soundPanner) {
  68974. return;
  68975. }
  68976. var mat = this._connectedMesh.getWorldMatrix();
  68977. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68978. direction.normalize();
  68979. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68980. };
  68981. /** @hidden */
  68982. Sound.prototype.updateDistanceFromListener = function () {
  68983. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68984. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68985. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68986. }
  68987. };
  68988. /**
  68989. * Sets a new custom attenuation function for the sound.
  68990. * @param callback Defines the function used for the attenuation
  68991. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68992. */
  68993. Sound.prototype.setAttenuationFunction = function (callback) {
  68994. this._customAttenuationFunction = callback;
  68995. };
  68996. /**
  68997. * Play the sound
  68998. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68999. * @param offset (optional) Start the sound setting it at a specific time
  69000. */
  69001. Sound.prototype.play = function (time, offset) {
  69002. var _this = this;
  69003. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69004. try {
  69005. if (this._startOffset < 0) {
  69006. time = -this._startOffset;
  69007. this._startOffset = 0;
  69008. }
  69009. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69010. if (!this._soundSource || !this._streamingSource) {
  69011. if (this.spatialSound && this._soundPanner) {
  69012. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69013. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69014. }
  69015. if (this._isDirectional) {
  69016. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69017. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69018. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69019. if (this._connectedMesh) {
  69020. this._updateDirection();
  69021. }
  69022. else {
  69023. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69024. }
  69025. }
  69026. }
  69027. }
  69028. if (this._streaming) {
  69029. if (!this._streamingSource) {
  69030. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69031. this._htmlAudioElement.onended = function () { _this._onended(); };
  69032. this._htmlAudioElement.playbackRate = this._playbackRate;
  69033. }
  69034. this._streamingSource.disconnect();
  69035. this._streamingSource.connect(this._inputAudioNode);
  69036. if (this._htmlAudioElement) {
  69037. // required to manage properly the new suspended default state of Chrome
  69038. // When the option 'streaming: true' is used, we need first to wait for
  69039. // the audio engine to be unlocked by a user gesture before trying to play
  69040. // an HTML Audio elememt
  69041. var tryToPlay = function () {
  69042. if (BABYLON.Engine.audioEngine.unlocked) {
  69043. var playPromise = _this._htmlAudioElement.play();
  69044. // In browsers that don’t yet support this functionality,
  69045. // playPromise won’t be defined.
  69046. if (playPromise !== undefined) {
  69047. playPromise.catch(function (error) {
  69048. // Automatic playback failed.
  69049. // Waiting for the audio engine to be unlocked by user click on unmute
  69050. BABYLON.Engine.audioEngine.lock();
  69051. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69052. });
  69053. }
  69054. }
  69055. else {
  69056. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69057. }
  69058. };
  69059. tryToPlay();
  69060. }
  69061. }
  69062. else {
  69063. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69064. this._soundSource.buffer = this._audioBuffer;
  69065. this._soundSource.connect(this._inputAudioNode);
  69066. this._soundSource.loop = this.loop;
  69067. this._soundSource.playbackRate.value = this._playbackRate;
  69068. this._soundSource.onended = function () { _this._onended(); };
  69069. if (this._soundSource.buffer) {
  69070. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69071. }
  69072. }
  69073. this._startTime = startTime;
  69074. this.isPlaying = true;
  69075. this.isPaused = false;
  69076. }
  69077. catch (ex) {
  69078. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69079. }
  69080. }
  69081. };
  69082. Sound.prototype._onended = function () {
  69083. this.isPlaying = false;
  69084. if (this.onended) {
  69085. this.onended();
  69086. }
  69087. this.onEndedObservable.notifyObservers(this);
  69088. };
  69089. /**
  69090. * Stop the sound
  69091. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69092. */
  69093. Sound.prototype.stop = function (time) {
  69094. if (this.isPlaying) {
  69095. if (this._streaming) {
  69096. if (this._htmlAudioElement) {
  69097. this._htmlAudioElement.pause();
  69098. // Test needed for Firefox or it will generate an Invalid State Error
  69099. if (this._htmlAudioElement.currentTime > 0) {
  69100. this._htmlAudioElement.currentTime = 0;
  69101. }
  69102. }
  69103. else {
  69104. this._streamingSource.disconnect();
  69105. }
  69106. }
  69107. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69108. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69109. this._soundSource.stop(stopTime);
  69110. this._soundSource.onended = function () { };
  69111. if (!this.isPaused) {
  69112. this._startOffset = 0;
  69113. }
  69114. }
  69115. this.isPlaying = false;
  69116. }
  69117. };
  69118. /**
  69119. * Put the sound in pause
  69120. */
  69121. Sound.prototype.pause = function () {
  69122. if (this.isPlaying) {
  69123. this.isPaused = true;
  69124. if (this._streaming) {
  69125. if (this._htmlAudioElement) {
  69126. this._htmlAudioElement.pause();
  69127. }
  69128. else {
  69129. this._streamingSource.disconnect();
  69130. }
  69131. }
  69132. else if (BABYLON.Engine.audioEngine.audioContext) {
  69133. this.stop(0);
  69134. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69135. }
  69136. }
  69137. };
  69138. /**
  69139. * Sets a dedicated volume for this sounds
  69140. * @param newVolume Define the new volume of the sound
  69141. * @param time Define in how long the sound should be at this value
  69142. */
  69143. Sound.prototype.setVolume = function (newVolume, time) {
  69144. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69145. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69146. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69147. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69148. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69149. }
  69150. else {
  69151. this._soundGain.gain.value = newVolume;
  69152. }
  69153. }
  69154. this._volume = newVolume;
  69155. };
  69156. /**
  69157. * Set the sound play back rate
  69158. * @param newPlaybackRate Define the playback rate the sound should be played at
  69159. */
  69160. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69161. this._playbackRate = newPlaybackRate;
  69162. if (this.isPlaying) {
  69163. if (this._streaming && this._htmlAudioElement) {
  69164. this._htmlAudioElement.playbackRate = this._playbackRate;
  69165. }
  69166. else if (this._soundSource) {
  69167. this._soundSource.playbackRate.value = this._playbackRate;
  69168. }
  69169. }
  69170. };
  69171. /**
  69172. * Gets the volume of the sound.
  69173. * @returns the volume of the sound
  69174. */
  69175. Sound.prototype.getVolume = function () {
  69176. return this._volume;
  69177. };
  69178. /**
  69179. * Attach the sound to a dedicated mesh
  69180. * @param meshToConnectTo The mesh to connect the sound with
  69181. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69182. */
  69183. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69184. var _this = this;
  69185. if (this._connectedMesh && this._registerFunc) {
  69186. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69187. this._registerFunc = null;
  69188. }
  69189. this._connectedMesh = meshToConnectTo;
  69190. if (!this.spatialSound) {
  69191. this.spatialSound = true;
  69192. this._createSpatialParameters();
  69193. if (this.isPlaying && this.loop) {
  69194. this.stop();
  69195. this.play();
  69196. }
  69197. }
  69198. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69199. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69200. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69201. };
  69202. /**
  69203. * Detach the sound from the previously attached mesh
  69204. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69205. */
  69206. Sound.prototype.detachFromMesh = function () {
  69207. if (this._connectedMesh && this._registerFunc) {
  69208. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69209. this._registerFunc = null;
  69210. this._connectedMesh = null;
  69211. }
  69212. };
  69213. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69214. if (!node.getBoundingInfo) {
  69215. return;
  69216. }
  69217. var mesh = node;
  69218. if (this._positionInEmitterSpace) {
  69219. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69220. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69221. }
  69222. else {
  69223. var boundingInfo = mesh.getBoundingInfo();
  69224. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69225. }
  69226. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69227. this._updateDirection();
  69228. }
  69229. };
  69230. /**
  69231. * Clone the current sound in the scene.
  69232. * @returns the new sound clone
  69233. */
  69234. Sound.prototype.clone = function () {
  69235. var _this = this;
  69236. if (!this._streaming) {
  69237. var setBufferAndRun = function () {
  69238. if (_this._isReadyToPlay) {
  69239. clonedSound._audioBuffer = _this.getAudioBuffer();
  69240. clonedSound._isReadyToPlay = true;
  69241. if (clonedSound.autoplay) {
  69242. clonedSound.play();
  69243. }
  69244. }
  69245. else {
  69246. window.setTimeout(setBufferAndRun, 300);
  69247. }
  69248. };
  69249. var currentOptions = {
  69250. autoplay: this.autoplay, loop: this.loop,
  69251. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69252. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69253. refDistance: this.refDistance, distanceModel: this.distanceModel
  69254. };
  69255. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69256. if (this.useCustomAttenuation) {
  69257. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69258. }
  69259. clonedSound.setPosition(this._position);
  69260. clonedSound.setPlaybackRate(this._playbackRate);
  69261. setBufferAndRun();
  69262. return clonedSound;
  69263. }
  69264. // Can't clone a streaming sound
  69265. else {
  69266. return null;
  69267. }
  69268. };
  69269. /**
  69270. * Gets the current underlying audio buffer containing the data
  69271. * @returns the audio buffer
  69272. */
  69273. Sound.prototype.getAudioBuffer = function () {
  69274. return this._audioBuffer;
  69275. };
  69276. /**
  69277. * Serializes the Sound in a JSON representation
  69278. * @returns the JSON representation of the sound
  69279. */
  69280. Sound.prototype.serialize = function () {
  69281. var serializationObject = {
  69282. name: this.name,
  69283. url: this.name,
  69284. autoplay: this.autoplay,
  69285. loop: this.loop,
  69286. volume: this._volume,
  69287. spatialSound: this.spatialSound,
  69288. maxDistance: this.maxDistance,
  69289. rolloffFactor: this.rolloffFactor,
  69290. refDistance: this.refDistance,
  69291. distanceModel: this.distanceModel,
  69292. playbackRate: this._playbackRate,
  69293. panningModel: this._panningModel,
  69294. soundTrackId: this.soundTrackId
  69295. };
  69296. if (this.spatialSound) {
  69297. if (this._connectedMesh)
  69298. serializationObject.connectedMeshId = this._connectedMesh.id;
  69299. serializationObject.position = this._position.asArray();
  69300. serializationObject.refDistance = this.refDistance;
  69301. serializationObject.distanceModel = this.distanceModel;
  69302. serializationObject.isDirectional = this._isDirectional;
  69303. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69304. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69305. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69306. serializationObject.coneOuterGain = this._coneOuterGain;
  69307. }
  69308. return serializationObject;
  69309. };
  69310. /**
  69311. * Parse a JSON representation of a sound to innstantiate in a given scene
  69312. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69313. * @param scene Define the scene the new parsed sound should be created in
  69314. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69315. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69316. * @returns the newly parsed sound
  69317. */
  69318. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69319. var soundName = parsedSound.name;
  69320. var soundUrl;
  69321. if (parsedSound.url) {
  69322. soundUrl = rootUrl + parsedSound.url;
  69323. }
  69324. else {
  69325. soundUrl = rootUrl + soundName;
  69326. }
  69327. var options = {
  69328. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69329. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69330. rolloffFactor: parsedSound.rolloffFactor,
  69331. refDistance: parsedSound.refDistance,
  69332. distanceModel: parsedSound.distanceModel,
  69333. playbackRate: parsedSound.playbackRate
  69334. };
  69335. var newSound;
  69336. if (!sourceSound) {
  69337. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69338. scene._addPendingData(newSound);
  69339. }
  69340. else {
  69341. var setBufferAndRun = function () {
  69342. if (sourceSound._isReadyToPlay) {
  69343. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69344. newSound._isReadyToPlay = true;
  69345. if (newSound.autoplay) {
  69346. newSound.play();
  69347. }
  69348. }
  69349. else {
  69350. window.setTimeout(setBufferAndRun, 300);
  69351. }
  69352. };
  69353. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69354. setBufferAndRun();
  69355. }
  69356. if (parsedSound.position) {
  69357. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69358. newSound.setPosition(soundPosition);
  69359. }
  69360. if (parsedSound.isDirectional) {
  69361. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69362. if (parsedSound.localDirectionToMesh) {
  69363. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69364. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69365. }
  69366. }
  69367. if (parsedSound.connectedMeshId) {
  69368. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69369. if (connectedMesh) {
  69370. newSound.attachToMesh(connectedMesh);
  69371. }
  69372. }
  69373. return newSound;
  69374. };
  69375. return Sound;
  69376. }());
  69377. BABYLON.Sound = Sound;
  69378. })(BABYLON || (BABYLON = {}));
  69379. //# sourceMappingURL=babylon.sound.js.map
  69380. var BABYLON;
  69381. (function (BABYLON) {
  69382. /**
  69383. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69384. * It will be also used in a future release to apply effects on a specific track.
  69385. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69386. */
  69387. var SoundTrack = /** @class */ (function () {
  69388. /**
  69389. * Creates a new sound track.
  69390. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69391. * @param scene Define the scene the sound track belongs to
  69392. * @param options
  69393. */
  69394. function SoundTrack(scene, options) {
  69395. if (options === void 0) { options = {}; }
  69396. /**
  69397. * The unique identifier of the sound track in the scene.
  69398. */
  69399. this.id = -1;
  69400. this._isMainTrack = false;
  69401. this._isInitialized = false;
  69402. this._scene = scene;
  69403. this.soundCollection = new Array();
  69404. this._options = options;
  69405. if (!this._isMainTrack && this._scene.soundTracks) {
  69406. this._scene.soundTracks.push(this);
  69407. this.id = this._scene.soundTracks.length - 1;
  69408. }
  69409. }
  69410. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69411. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69412. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69413. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69414. if (this._options) {
  69415. if (this._options.volume) {
  69416. this._outputAudioNode.gain.value = this._options.volume;
  69417. }
  69418. if (this._options.mainTrack) {
  69419. this._isMainTrack = this._options.mainTrack;
  69420. }
  69421. }
  69422. this._isInitialized = true;
  69423. }
  69424. };
  69425. /**
  69426. * Release the sound track and its associated resources
  69427. */
  69428. SoundTrack.prototype.dispose = function () {
  69429. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69430. if (this._connectedAnalyser) {
  69431. this._connectedAnalyser.stopDebugCanvas();
  69432. }
  69433. while (this.soundCollection.length) {
  69434. this.soundCollection[0].dispose();
  69435. }
  69436. if (this._outputAudioNode) {
  69437. this._outputAudioNode.disconnect();
  69438. }
  69439. this._outputAudioNode = null;
  69440. }
  69441. };
  69442. /**
  69443. * Adds a sound to this sound track
  69444. * @param sound define the cound to add
  69445. * @ignoreNaming
  69446. */
  69447. SoundTrack.prototype.AddSound = function (sound) {
  69448. if (!this._isInitialized) {
  69449. this._initializeSoundTrackAudioGraph();
  69450. }
  69451. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69452. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69453. }
  69454. if (sound.soundTrackId) {
  69455. if (sound.soundTrackId === -1) {
  69456. this._scene.mainSoundTrack.RemoveSound(sound);
  69457. }
  69458. else if (this._scene.soundTracks) {
  69459. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69460. }
  69461. }
  69462. this.soundCollection.push(sound);
  69463. sound.soundTrackId = this.id;
  69464. };
  69465. /**
  69466. * Removes a sound to this sound track
  69467. * @param sound define the cound to remove
  69468. * @ignoreNaming
  69469. */
  69470. SoundTrack.prototype.RemoveSound = function (sound) {
  69471. var index = this.soundCollection.indexOf(sound);
  69472. if (index !== -1) {
  69473. this.soundCollection.splice(index, 1);
  69474. }
  69475. };
  69476. /**
  69477. * Set a global volume for the full sound track.
  69478. * @param newVolume Define the new volume of the sound track
  69479. */
  69480. SoundTrack.prototype.setVolume = function (newVolume) {
  69481. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69482. this._outputAudioNode.gain.value = newVolume;
  69483. }
  69484. };
  69485. /**
  69486. * Switch the panning model to HRTF:
  69487. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69488. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69489. */
  69490. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69491. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69492. for (var i = 0; i < this.soundCollection.length; i++) {
  69493. this.soundCollection[i].switchPanningModelToHRTF();
  69494. }
  69495. }
  69496. };
  69497. /**
  69498. * Switch the panning model to Equal Power:
  69499. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69500. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69501. */
  69502. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69503. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69504. for (var i = 0; i < this.soundCollection.length; i++) {
  69505. this.soundCollection[i].switchPanningModelToEqualPower();
  69506. }
  69507. }
  69508. };
  69509. /**
  69510. * Connect the sound track to an audio analyser allowing some amazing
  69511. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69512. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69513. * @param analyser The analyser to connect to the engine
  69514. */
  69515. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69516. if (this._connectedAnalyser) {
  69517. this._connectedAnalyser.stopDebugCanvas();
  69518. }
  69519. this._connectedAnalyser = analyser;
  69520. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69521. this._outputAudioNode.disconnect();
  69522. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69523. }
  69524. };
  69525. return SoundTrack;
  69526. }());
  69527. BABYLON.SoundTrack = SoundTrack;
  69528. })(BABYLON || (BABYLON = {}));
  69529. //# sourceMappingURL=babylon.soundtrack.js.map
  69530. var BABYLON;
  69531. (function (BABYLON) {
  69532. /**
  69533. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69534. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69535. */
  69536. var Analyser = /** @class */ (function () {
  69537. /**
  69538. * Creates a new analyser
  69539. * @param scene defines hosting scene
  69540. */
  69541. function Analyser(scene) {
  69542. /**
  69543. * Gets or sets the smoothing
  69544. * @ignorenaming
  69545. */
  69546. this.SMOOTHING = 0.75;
  69547. /**
  69548. * Gets or sets the FFT table size
  69549. * @ignorenaming
  69550. */
  69551. this.FFT_SIZE = 512;
  69552. /**
  69553. * Gets or sets the bar graph amplitude
  69554. * @ignorenaming
  69555. */
  69556. this.BARGRAPHAMPLITUDE = 256;
  69557. /**
  69558. * Gets or sets the position of the debug canvas
  69559. * @ignorenaming
  69560. */
  69561. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69562. /**
  69563. * Gets or sets the debug canvas size
  69564. * @ignorenaming
  69565. */
  69566. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69567. this._scene = scene;
  69568. this._audioEngine = BABYLON.Engine.audioEngine;
  69569. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69570. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69571. this._webAudioAnalyser.minDecibels = -140;
  69572. this._webAudioAnalyser.maxDecibels = 0;
  69573. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69574. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69575. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69576. }
  69577. }
  69578. /**
  69579. * Get the number of data values you will have to play with for the visualization
  69580. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69581. * @returns a number
  69582. */
  69583. Analyser.prototype.getFrequencyBinCount = function () {
  69584. if (this._audioEngine.canUseWebAudio) {
  69585. return this._webAudioAnalyser.frequencyBinCount;
  69586. }
  69587. else {
  69588. return 0;
  69589. }
  69590. };
  69591. /**
  69592. * Gets the current frequency data as a byte array
  69593. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69594. * @returns a Uint8Array
  69595. */
  69596. Analyser.prototype.getByteFrequencyData = function () {
  69597. if (this._audioEngine.canUseWebAudio) {
  69598. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69599. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69600. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69601. }
  69602. return this._byteFreqs;
  69603. };
  69604. /**
  69605. * Gets the current waveform as a byte array
  69606. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69607. * @returns a Uint8Array
  69608. */
  69609. Analyser.prototype.getByteTimeDomainData = function () {
  69610. if (this._audioEngine.canUseWebAudio) {
  69611. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69612. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69613. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69614. }
  69615. return this._byteTime;
  69616. };
  69617. /**
  69618. * Gets the current frequency data as a float array
  69619. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69620. * @returns a Float32Array
  69621. */
  69622. Analyser.prototype.getFloatFrequencyData = function () {
  69623. if (this._audioEngine.canUseWebAudio) {
  69624. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69625. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69626. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69627. }
  69628. return this._floatFreqs;
  69629. };
  69630. /**
  69631. * Renders the debug canvas
  69632. */
  69633. Analyser.prototype.drawDebugCanvas = function () {
  69634. var _this = this;
  69635. if (this._audioEngine.canUseWebAudio) {
  69636. if (!this._debugCanvas) {
  69637. this._debugCanvas = document.createElement("canvas");
  69638. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69639. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69640. this._debugCanvas.style.position = "absolute";
  69641. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69642. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69643. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69644. document.body.appendChild(this._debugCanvas);
  69645. this._registerFunc = function () {
  69646. _this.drawDebugCanvas();
  69647. };
  69648. this._scene.registerBeforeRender(this._registerFunc);
  69649. }
  69650. if (this._registerFunc && this._debugCanvasContext) {
  69651. var workingArray = this.getByteFrequencyData();
  69652. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69653. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69654. // Draw the frequency domain chart.
  69655. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69656. var value = workingArray[i];
  69657. var percent = value / this.BARGRAPHAMPLITUDE;
  69658. var height = this.DEBUGCANVASSIZE.height * percent;
  69659. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69660. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69661. var hue = i / this.getFrequencyBinCount() * 360;
  69662. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69663. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69664. }
  69665. }
  69666. }
  69667. };
  69668. /**
  69669. * Stops rendering the debug canvas and removes it
  69670. */
  69671. Analyser.prototype.stopDebugCanvas = function () {
  69672. if (this._debugCanvas) {
  69673. if (this._registerFunc) {
  69674. this._scene.unregisterBeforeRender(this._registerFunc);
  69675. this._registerFunc = null;
  69676. }
  69677. document.body.removeChild(this._debugCanvas);
  69678. this._debugCanvas = null;
  69679. this._debugCanvasContext = null;
  69680. }
  69681. };
  69682. /**
  69683. * Connects two audio nodes
  69684. * @param inputAudioNode defines first node to connect
  69685. * @param outputAudioNode defines second node to connect
  69686. */
  69687. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69688. if (this._audioEngine.canUseWebAudio) {
  69689. inputAudioNode.connect(this._webAudioAnalyser);
  69690. this._webAudioAnalyser.connect(outputAudioNode);
  69691. }
  69692. };
  69693. /**
  69694. * Releases all associated resources
  69695. */
  69696. Analyser.prototype.dispose = function () {
  69697. if (this._audioEngine.canUseWebAudio) {
  69698. this._webAudioAnalyser.disconnect();
  69699. }
  69700. };
  69701. return Analyser;
  69702. }());
  69703. BABYLON.Analyser = Analyser;
  69704. })(BABYLON || (BABYLON = {}));
  69705. //# sourceMappingURL=babylon.analyser.js.map
  69706. var BABYLON;
  69707. (function (BABYLON) {
  69708. /**
  69709. * Wraps one or more Sound objects and selects one with random weight for playback.
  69710. */
  69711. var WeightedSound = /** @class */ (function () {
  69712. /**
  69713. * Creates a new WeightedSound from the list of sounds given.
  69714. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69715. * @param sounds Array of Sounds that will be selected from.
  69716. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69717. */
  69718. function WeightedSound(loop, sounds, weights) {
  69719. var _this = this;
  69720. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69721. this.loop = false;
  69722. this._coneInnerAngle = 360;
  69723. this._coneOuterAngle = 360;
  69724. this._volume = 1;
  69725. /** A Sound is currently playing. */
  69726. this.isPlaying = false;
  69727. /** A Sound is currently paused. */
  69728. this.isPaused = false;
  69729. this._sounds = [];
  69730. this._weights = [];
  69731. if (sounds.length !== weights.length) {
  69732. throw new Error('Sounds length does not equal weights length');
  69733. }
  69734. this.loop = loop;
  69735. this._weights = weights;
  69736. // Normalize the weights
  69737. var weightSum = 0;
  69738. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69739. var weight = weights_1[_i];
  69740. weightSum += weight;
  69741. }
  69742. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69743. for (var i = 0; i < this._weights.length; i++) {
  69744. this._weights[i] *= invWeightSum;
  69745. }
  69746. this._sounds = sounds;
  69747. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69748. var sound = _b[_a];
  69749. sound.onEndedObservable.add(function () { _this._onended(); });
  69750. }
  69751. }
  69752. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69753. /**
  69754. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69755. */
  69756. get: function () {
  69757. return this._coneInnerAngle;
  69758. },
  69759. /**
  69760. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69761. */
  69762. set: function (value) {
  69763. if (value !== this._coneInnerAngle) {
  69764. if (this._coneOuterAngle < value) {
  69765. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69766. return;
  69767. }
  69768. this._coneInnerAngle = value;
  69769. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69770. var sound = _a[_i];
  69771. sound.directionalConeInnerAngle = value;
  69772. }
  69773. }
  69774. },
  69775. enumerable: true,
  69776. configurable: true
  69777. });
  69778. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69779. /**
  69780. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69781. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69782. */
  69783. get: function () {
  69784. return this._coneOuterAngle;
  69785. },
  69786. /**
  69787. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69788. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69789. */
  69790. set: function (value) {
  69791. if (value !== this._coneOuterAngle) {
  69792. if (value < this._coneInnerAngle) {
  69793. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69794. return;
  69795. }
  69796. this._coneOuterAngle = value;
  69797. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69798. var sound = _a[_i];
  69799. sound.directionalConeOuterAngle = value;
  69800. }
  69801. }
  69802. },
  69803. enumerable: true,
  69804. configurable: true
  69805. });
  69806. Object.defineProperty(WeightedSound.prototype, "volume", {
  69807. /**
  69808. * Playback volume.
  69809. */
  69810. get: function () {
  69811. return this._volume;
  69812. },
  69813. /**
  69814. * Playback volume.
  69815. */
  69816. set: function (value) {
  69817. if (value !== this._volume) {
  69818. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69819. var sound = _a[_i];
  69820. sound.setVolume(value);
  69821. }
  69822. }
  69823. },
  69824. enumerable: true,
  69825. configurable: true
  69826. });
  69827. WeightedSound.prototype._onended = function () {
  69828. if (this._currentIndex !== undefined) {
  69829. this._sounds[this._currentIndex].autoplay = false;
  69830. }
  69831. if (this.loop && this.isPlaying) {
  69832. this.play();
  69833. }
  69834. else {
  69835. this.isPlaying = false;
  69836. }
  69837. };
  69838. /**
  69839. * Suspend playback
  69840. */
  69841. WeightedSound.prototype.pause = function () {
  69842. this.isPaused = true;
  69843. if (this._currentIndex !== undefined) {
  69844. this._sounds[this._currentIndex].pause();
  69845. }
  69846. };
  69847. /**
  69848. * Stop playback
  69849. */
  69850. WeightedSound.prototype.stop = function () {
  69851. this.isPlaying = false;
  69852. if (this._currentIndex !== undefined) {
  69853. this._sounds[this._currentIndex].stop();
  69854. }
  69855. };
  69856. /**
  69857. * Start playback.
  69858. * @param startOffset Position the clip head at a specific time in seconds.
  69859. */
  69860. WeightedSound.prototype.play = function (startOffset) {
  69861. if (!this.isPaused) {
  69862. this.stop();
  69863. var randomValue = Math.random();
  69864. var total = 0;
  69865. for (var i = 0; i < this._weights.length; i++) {
  69866. total += this._weights[i];
  69867. if (randomValue <= total) {
  69868. this._currentIndex = i;
  69869. break;
  69870. }
  69871. }
  69872. }
  69873. var sound = this._sounds[this._currentIndex];
  69874. if (sound.isReady()) {
  69875. sound.play(0, this.isPaused ? undefined : startOffset);
  69876. }
  69877. else {
  69878. sound.autoplay = true;
  69879. }
  69880. this.isPlaying = true;
  69881. this.isPaused = false;
  69882. };
  69883. return WeightedSound;
  69884. }());
  69885. BABYLON.WeightedSound = WeightedSound;
  69886. })(BABYLON || (BABYLON = {}));
  69887. //# sourceMappingURL=babylon.weightedsound.js.map
  69888. var BABYLON;
  69889. (function (BABYLON) {
  69890. // Adds the parser to the scene parsers.
  69891. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  69892. // TODO: add sound
  69893. var loadedSounds = [];
  69894. var loadedSound;
  69895. container.sounds = container.sounds || [];
  69896. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69897. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69898. var parsedSound = parsedData.sounds[index];
  69899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69900. if (!parsedSound.url)
  69901. parsedSound.url = parsedSound.name;
  69902. if (!loadedSounds[parsedSound.url]) {
  69903. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69904. loadedSounds[parsedSound.url] = loadedSound;
  69905. container.sounds.push(loadedSound);
  69906. }
  69907. else {
  69908. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69909. }
  69910. }
  69911. else {
  69912. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69913. }
  69914. }
  69915. }
  69916. loadedSounds = [];
  69917. });
  69918. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  69919. get: function () {
  69920. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69921. if (!compo) {
  69922. compo = new AudioSceneComponent(this);
  69923. this._addComponent(compo);
  69924. }
  69925. if (!this._mainSoundTrack) {
  69926. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69927. }
  69928. return this._mainSoundTrack;
  69929. },
  69930. enumerable: true,
  69931. configurable: true
  69932. });
  69933. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69934. var index;
  69935. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69936. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69937. return this.mainSoundTrack.soundCollection[index];
  69938. }
  69939. }
  69940. if (this.soundTracks) {
  69941. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69942. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69943. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69944. return this.soundTracks[sdIndex].soundCollection[index];
  69945. }
  69946. }
  69947. }
  69948. }
  69949. return null;
  69950. };
  69951. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69952. get: function () {
  69953. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69954. if (!compo) {
  69955. compo = new AudioSceneComponent(this);
  69956. this._addComponent(compo);
  69957. }
  69958. return compo.audioEnabled;
  69959. },
  69960. set: function (value) {
  69961. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69962. if (!compo) {
  69963. compo = new AudioSceneComponent(this);
  69964. this._addComponent(compo);
  69965. }
  69966. if (value) {
  69967. compo.enableAudio();
  69968. }
  69969. else {
  69970. compo.disableAudio();
  69971. }
  69972. },
  69973. enumerable: true,
  69974. configurable: true
  69975. });
  69976. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69977. get: function () {
  69978. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69979. if (!compo) {
  69980. compo = new AudioSceneComponent(this);
  69981. this._addComponent(compo);
  69982. }
  69983. return compo.headphone;
  69984. },
  69985. set: function (value) {
  69986. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69987. if (!compo) {
  69988. compo = new AudioSceneComponent(this);
  69989. this._addComponent(compo);
  69990. }
  69991. if (value) {
  69992. compo.switchAudioModeForHeadphones();
  69993. }
  69994. else {
  69995. compo.switchAudioModeForNormalSpeakers();
  69996. }
  69997. },
  69998. enumerable: true,
  69999. configurable: true
  70000. });
  70001. /**
  70002. * Defines the sound scene component responsible to manage any sounds
  70003. * in a given scene.
  70004. */
  70005. var AudioSceneComponent = /** @class */ (function () {
  70006. /**
  70007. * Creates a new instance of the component for the given scene
  70008. * @param scene Defines the scene to register the component in
  70009. */
  70010. function AudioSceneComponent(scene) {
  70011. /**
  70012. * The component name helpfull to identify the component in the list of scene components.
  70013. */
  70014. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70015. this._audioEnabled = true;
  70016. this._headphone = false;
  70017. this.scene = scene;
  70018. scene.soundTracks = new Array();
  70019. scene.sounds = new Array();
  70020. }
  70021. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70022. /**
  70023. * Gets whether audio is enabled or not.
  70024. * Please use related enable/disable method to switch state.
  70025. */
  70026. get: function () {
  70027. return this._audioEnabled;
  70028. },
  70029. enumerable: true,
  70030. configurable: true
  70031. });
  70032. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70033. /**
  70034. * Gets whether audio is outputing to headphone or not.
  70035. * Please use the according Switch methods to change output.
  70036. */
  70037. get: function () {
  70038. return this._headphone;
  70039. },
  70040. enumerable: true,
  70041. configurable: true
  70042. });
  70043. /**
  70044. * Registers the component in a given scene
  70045. */
  70046. AudioSceneComponent.prototype.register = function () {
  70047. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70048. };
  70049. /**
  70050. * Rebuilds the elements related to this component in case of
  70051. * context lost for instance.
  70052. */
  70053. AudioSceneComponent.prototype.rebuild = function () {
  70054. // Nothing to do here. (Not rendering related)
  70055. };
  70056. /**
  70057. * Serializes the component data to the specified json object
  70058. * @param serializationObject The object to serialize to
  70059. */
  70060. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70061. serializationObject.sounds = [];
  70062. if (this.scene.soundTracks) {
  70063. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70064. var soundtrack = this.scene.soundTracks[index];
  70065. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70066. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70067. }
  70068. }
  70069. }
  70070. };
  70071. /**
  70072. * Adds all the element from the container to the scene
  70073. * @param container the container holding the elements
  70074. */
  70075. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70076. var _this = this;
  70077. if (!container.sounds) {
  70078. return;
  70079. }
  70080. container.sounds.forEach(function (sound) {
  70081. sound.play();
  70082. sound.autoplay = true;
  70083. _this.scene.mainSoundTrack.AddSound(sound);
  70084. });
  70085. };
  70086. /**
  70087. * Removes all the elements in the container from the scene
  70088. * @param container contains the elements to remove
  70089. */
  70090. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70091. var _this = this;
  70092. if (!container.sounds) {
  70093. return;
  70094. }
  70095. container.sounds.forEach(function (sound) {
  70096. sound.stop();
  70097. sound.autoplay = false;
  70098. _this.scene.mainSoundTrack.RemoveSound(sound);
  70099. });
  70100. };
  70101. /**
  70102. * Disposes the component and the associated ressources.
  70103. */
  70104. AudioSceneComponent.prototype.dispose = function () {
  70105. var scene = this.scene;
  70106. if (scene._mainSoundTrack) {
  70107. scene.mainSoundTrack.dispose();
  70108. }
  70109. if (scene.soundTracks) {
  70110. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70111. scene.soundTracks[scIndex].dispose();
  70112. }
  70113. }
  70114. };
  70115. /**
  70116. * Disables audio in the associated scene.
  70117. */
  70118. AudioSceneComponent.prototype.disableAudio = function () {
  70119. var scene = this.scene;
  70120. this._audioEnabled = false;
  70121. var i;
  70122. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70123. scene.mainSoundTrack.soundCollection[i].pause();
  70124. }
  70125. if (scene.soundTracks) {
  70126. for (i = 0; i < scene.soundTracks.length; i++) {
  70127. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70128. scene.soundTracks[i].soundCollection[j].pause();
  70129. }
  70130. }
  70131. }
  70132. };
  70133. /**
  70134. * Enables audio in the associated scene.
  70135. */
  70136. AudioSceneComponent.prototype.enableAudio = function () {
  70137. var scene = this.scene;
  70138. this._audioEnabled = true;
  70139. var i;
  70140. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70141. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70142. scene.mainSoundTrack.soundCollection[i].play();
  70143. }
  70144. }
  70145. if (scene.soundTracks) {
  70146. for (i = 0; i < scene.soundTracks.length; i++) {
  70147. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70148. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70149. scene.soundTracks[i].soundCollection[j].play();
  70150. }
  70151. }
  70152. }
  70153. }
  70154. };
  70155. /**
  70156. * Switch audio to headphone output.
  70157. */
  70158. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70159. var scene = this.scene;
  70160. this._headphone = true;
  70161. scene.mainSoundTrack.switchPanningModelToHRTF();
  70162. if (scene.soundTracks) {
  70163. for (var i = 0; i < scene.soundTracks.length; i++) {
  70164. scene.soundTracks[i].switchPanningModelToHRTF();
  70165. }
  70166. }
  70167. };
  70168. /**
  70169. * Switch audio to normal speakers.
  70170. */
  70171. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70172. var scene = this.scene;
  70173. this._headphone = false;
  70174. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70175. if (scene.soundTracks) {
  70176. for (var i = 0; i < scene.soundTracks.length; i++) {
  70177. scene.soundTracks[i].switchPanningModelToEqualPower();
  70178. }
  70179. }
  70180. };
  70181. AudioSceneComponent.prototype._afterRender = function () {
  70182. var scene = this.scene;
  70183. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70184. return;
  70185. }
  70186. var listeningCamera;
  70187. var audioEngine = BABYLON.Engine.audioEngine;
  70188. if (scene.activeCameras.length > 0) {
  70189. listeningCamera = scene.activeCameras[0];
  70190. }
  70191. else {
  70192. listeningCamera = scene.activeCamera;
  70193. }
  70194. if (listeningCamera && audioEngine.audioContext) {
  70195. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70196. // for VR cameras
  70197. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70198. listeningCamera = listeningCamera.rigCameras[0];
  70199. }
  70200. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70201. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70202. cameraDirection.normalize();
  70203. // To avoid some errors on GearVR
  70204. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70205. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70206. }
  70207. var i;
  70208. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70209. var sound = scene.mainSoundTrack.soundCollection[i];
  70210. if (sound.useCustomAttenuation) {
  70211. sound.updateDistanceFromListener();
  70212. }
  70213. }
  70214. if (scene.soundTracks) {
  70215. for (i = 0; i < scene.soundTracks.length; i++) {
  70216. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70217. sound = scene.soundTracks[i].soundCollection[j];
  70218. if (sound.useCustomAttenuation) {
  70219. sound.updateDistanceFromListener();
  70220. }
  70221. }
  70222. }
  70223. }
  70224. }
  70225. };
  70226. return AudioSceneComponent;
  70227. }());
  70228. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70229. })(BABYLON || (BABYLON = {}));
  70230. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70231. var BABYLON;
  70232. (function (BABYLON) {
  70233. /**
  70234. * This defines an action helpful to play a defined sound on a triggered action.
  70235. */
  70236. var PlaySoundAction = /** @class */ (function (_super) {
  70237. __extends(PlaySoundAction, _super);
  70238. /**
  70239. * Instantiate the action
  70240. * @param triggerOptions defines the trigger options
  70241. * @param sound defines the sound to play
  70242. * @param condition defines the trigger related conditions
  70243. */
  70244. function PlaySoundAction(triggerOptions, sound, condition) {
  70245. var _this = _super.call(this, triggerOptions, condition) || this;
  70246. _this._sound = sound;
  70247. return _this;
  70248. }
  70249. /** @hidden */
  70250. PlaySoundAction.prototype._prepare = function () {
  70251. };
  70252. /**
  70253. * Execute the action and play the sound.
  70254. */
  70255. PlaySoundAction.prototype.execute = function () {
  70256. if (this._sound !== undefined)
  70257. this._sound.play();
  70258. };
  70259. /**
  70260. * Serializes the actions and its related information.
  70261. * @param parent defines the object to serialize in
  70262. * @returns the serialized object
  70263. */
  70264. PlaySoundAction.prototype.serialize = function (parent) {
  70265. return _super.prototype._serialize.call(this, {
  70266. name: "PlaySoundAction",
  70267. properties: [{ name: "sound", value: this._sound.name }]
  70268. }, parent);
  70269. };
  70270. return PlaySoundAction;
  70271. }(BABYLON.Action));
  70272. BABYLON.PlaySoundAction = PlaySoundAction;
  70273. /**
  70274. * This defines an action helpful to stop a defined sound on a triggered action.
  70275. */
  70276. var StopSoundAction = /** @class */ (function (_super) {
  70277. __extends(StopSoundAction, _super);
  70278. /**
  70279. * Instantiate the action
  70280. * @param triggerOptions defines the trigger options
  70281. * @param sound defines the sound to stop
  70282. * @param condition defines the trigger related conditions
  70283. */
  70284. function StopSoundAction(triggerOptions, sound, condition) {
  70285. var _this = _super.call(this, triggerOptions, condition) || this;
  70286. _this._sound = sound;
  70287. return _this;
  70288. }
  70289. /** @hidden */
  70290. StopSoundAction.prototype._prepare = function () {
  70291. };
  70292. /**
  70293. * Execute the action and stop the sound.
  70294. */
  70295. StopSoundAction.prototype.execute = function () {
  70296. if (this._sound !== undefined)
  70297. this._sound.stop();
  70298. };
  70299. /**
  70300. * Serializes the actions and its related information.
  70301. * @param parent defines the object to serialize in
  70302. * @returns the serialized object
  70303. */
  70304. StopSoundAction.prototype.serialize = function (parent) {
  70305. return _super.prototype._serialize.call(this, {
  70306. name: "StopSoundAction",
  70307. properties: [{ name: "sound", value: this._sound.name }]
  70308. }, parent);
  70309. };
  70310. return StopSoundAction;
  70311. }(BABYLON.Action));
  70312. BABYLON.StopSoundAction = StopSoundAction;
  70313. })(BABYLON || (BABYLON = {}));
  70314. //# sourceMappingURL=babylon.directAudioActions.js.map
  70315. var BABYLON;
  70316. (function (BABYLON) {
  70317. /**
  70318. * Class for creating a cube texture
  70319. */
  70320. var CubeTexture = /** @class */ (function (_super) {
  70321. __extends(CubeTexture, _super);
  70322. /**
  70323. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70324. * as prefiltered data.
  70325. * @param rootUrl defines the url of the texture or the root name of the six images
  70326. * @param scene defines the scene the texture is attached to
  70327. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70328. * @param noMipmap defines if mipmaps should be created or not
  70329. * @param files defines the six files to load for the different faces
  70330. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70331. * @param onError defines a callback triggered in case of error during load
  70332. * @param format defines the internal format to use for the texture once loaded
  70333. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70334. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70335. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70336. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70337. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70338. * @return the cube texture
  70339. */
  70340. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70341. if (extensions === void 0) { extensions = null; }
  70342. if (noMipmap === void 0) { noMipmap = false; }
  70343. if (files === void 0) { files = null; }
  70344. if (onLoad === void 0) { onLoad = null; }
  70345. if (onError === void 0) { onError = null; }
  70346. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70347. if (prefiltered === void 0) { prefiltered = false; }
  70348. if (forcedExtension === void 0) { forcedExtension = null; }
  70349. if (createPolynomials === void 0) { createPolynomials = false; }
  70350. if (lodScale === void 0) { lodScale = 0.8; }
  70351. if (lodOffset === void 0) { lodOffset = 0; }
  70352. var _this = _super.call(this, scene) || this;
  70353. /**
  70354. * Gets or sets the center of the bounding box associated with the cube texture.
  70355. * It must define where the camera used to render the texture was set
  70356. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70357. */
  70358. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70359. _this._rotationY = 0;
  70360. /** @hidden */
  70361. _this._prefiltered = false;
  70362. _this.name = rootUrl;
  70363. _this.url = rootUrl;
  70364. _this._noMipmap = noMipmap;
  70365. _this.hasAlpha = false;
  70366. _this._format = format;
  70367. _this.isCube = true;
  70368. _this._textureMatrix = BABYLON.Matrix.Identity();
  70369. _this._createPolynomials = createPolynomials;
  70370. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70371. if (!rootUrl && !files) {
  70372. return _this;
  70373. }
  70374. var lastDot = rootUrl.lastIndexOf(".");
  70375. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70376. var isDDS = (extension === ".dds");
  70377. var isEnv = (extension === ".env");
  70378. if (isEnv) {
  70379. _this.gammaSpace = false;
  70380. _this._prefiltered = false;
  70381. }
  70382. else {
  70383. _this._prefiltered = prefiltered;
  70384. if (prefiltered) {
  70385. _this.gammaSpace = false;
  70386. }
  70387. }
  70388. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70389. if (!files) {
  70390. if (!isEnv && !isDDS && !extensions) {
  70391. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70392. }
  70393. files = [];
  70394. if (extensions) {
  70395. for (var index = 0; index < extensions.length; index++) {
  70396. files.push(rootUrl + extensions[index]);
  70397. }
  70398. }
  70399. }
  70400. _this._files = files;
  70401. if (!_this._texture) {
  70402. if (!scene.useDelayedTextureLoading) {
  70403. if (prefiltered) {
  70404. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70405. }
  70406. else {
  70407. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70408. }
  70409. }
  70410. else {
  70411. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70412. }
  70413. }
  70414. else if (onLoad) {
  70415. if (_this._texture.isReady) {
  70416. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70417. }
  70418. else {
  70419. _this._texture.onLoadedObservable.add(onLoad);
  70420. }
  70421. }
  70422. return _this;
  70423. }
  70424. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70425. /**
  70426. * Returns the bounding box size
  70427. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70428. */
  70429. get: function () {
  70430. return this._boundingBoxSize;
  70431. },
  70432. /**
  70433. * Gets or sets the size of the bounding box associated with the cube texture
  70434. * When defined, the cubemap will switch to local mode
  70435. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70436. * @example https://www.babylonjs-playground.com/#RNASML
  70437. */
  70438. set: function (value) {
  70439. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70440. return;
  70441. }
  70442. this._boundingBoxSize = value;
  70443. var scene = this.getScene();
  70444. if (scene) {
  70445. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70446. }
  70447. },
  70448. enumerable: true,
  70449. configurable: true
  70450. });
  70451. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70452. /**
  70453. * Gets texture matrix rotation angle around Y axis radians.
  70454. */
  70455. get: function () {
  70456. return this._rotationY;
  70457. },
  70458. /**
  70459. * Sets texture matrix rotation angle around Y axis in radians.
  70460. */
  70461. set: function (value) {
  70462. this._rotationY = value;
  70463. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70464. },
  70465. enumerable: true,
  70466. configurable: true
  70467. });
  70468. /**
  70469. * Creates a cube texture from an array of image urls
  70470. * @param files defines an array of image urls
  70471. * @param scene defines the hosting scene
  70472. * @param noMipmap specifies if mip maps are not used
  70473. * @returns a cube texture
  70474. */
  70475. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70476. var rootUrlKey = "";
  70477. files.forEach(function (url) { return rootUrlKey += url; });
  70478. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70479. };
  70480. /**
  70481. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70482. * @param url defines the url of the prefiltered texture
  70483. * @param scene defines the scene the texture is attached to
  70484. * @param forcedExtension defines the extension of the file if different from the url
  70485. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70486. * @return the prefiltered texture
  70487. */
  70488. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70489. if (forcedExtension === void 0) { forcedExtension = null; }
  70490. if (createPolynomials === void 0) { createPolynomials = true; }
  70491. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70492. };
  70493. /**
  70494. * Delays loading of the cube texture
  70495. */
  70496. CubeTexture.prototype.delayLoad = function () {
  70497. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70498. return;
  70499. }
  70500. var scene = this.getScene();
  70501. if (!scene) {
  70502. return;
  70503. }
  70504. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70505. this._texture = this._getFromCache(this.url, this._noMipmap);
  70506. if (!this._texture) {
  70507. if (this._prefiltered) {
  70508. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70509. }
  70510. else {
  70511. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70512. }
  70513. }
  70514. };
  70515. /**
  70516. * Returns the reflection texture matrix
  70517. * @returns the reflection texture matrix
  70518. */
  70519. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70520. return this._textureMatrix;
  70521. };
  70522. /**
  70523. * Sets the reflection texture matrix
  70524. * @param value Reflection texture matrix
  70525. */
  70526. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70527. this._textureMatrix = value;
  70528. };
  70529. /**
  70530. * Parses text to create a cube texture
  70531. * @param parsedTexture define the serialized text to read from
  70532. * @param scene defines the hosting scene
  70533. * @param rootUrl defines the root url of the cube texture
  70534. * @returns a cube texture
  70535. */
  70536. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70537. var texture = BABYLON.SerializationHelper.Parse(function () {
  70538. var prefiltered = false;
  70539. if (parsedTexture.prefiltered) {
  70540. prefiltered = parsedTexture.prefiltered;
  70541. }
  70542. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70543. }, parsedTexture, scene);
  70544. // Local Cubemaps
  70545. if (parsedTexture.boundingBoxPosition) {
  70546. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70547. }
  70548. if (parsedTexture.boundingBoxSize) {
  70549. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70550. }
  70551. // Animations
  70552. if (parsedTexture.animations) {
  70553. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70554. var parsedAnimation = parsedTexture.animations[animationIndex];
  70555. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70556. }
  70557. }
  70558. return texture;
  70559. };
  70560. /**
  70561. * Makes a clone, or deep copy, of the cube texture
  70562. * @returns a new cube texture
  70563. */
  70564. CubeTexture.prototype.clone = function () {
  70565. var _this = this;
  70566. return BABYLON.SerializationHelper.Clone(function () {
  70567. var scene = _this.getScene();
  70568. if (!scene) {
  70569. return _this;
  70570. }
  70571. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70572. }, this);
  70573. };
  70574. __decorate([
  70575. BABYLON.serialize("rotationY")
  70576. ], CubeTexture.prototype, "rotationY", null);
  70577. return CubeTexture;
  70578. }(BABYLON.BaseTexture));
  70579. BABYLON.CubeTexture = CubeTexture;
  70580. })(BABYLON || (BABYLON = {}));
  70581. //# sourceMappingURL=babylon.cubeTexture.js.map
  70582. var BABYLON;
  70583. (function (BABYLON) {
  70584. /**
  70585. * Raw cube texture where the raw buffers are passed in
  70586. */
  70587. var RawCubeTexture = /** @class */ (function (_super) {
  70588. __extends(RawCubeTexture, _super);
  70589. /**
  70590. * Creates a cube texture where the raw buffers are passed in.
  70591. * @param scene defines the scene the texture is attached to
  70592. * @param data defines the array of data to use to create each face
  70593. * @param size defines the size of the textures
  70594. * @param format defines the format of the data
  70595. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70596. * @param generateMipMaps defines if the engine should generate the mip levels
  70597. * @param invertY defines if data must be stored with Y axis inverted
  70598. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70599. * @param compression defines the compression used (null by default)
  70600. */
  70601. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70602. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70603. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70604. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70605. if (invertY === void 0) { invertY = false; }
  70606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70607. if (compression === void 0) { compression = null; }
  70608. var _this = _super.call(this, "", scene) || this;
  70609. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70610. return _this;
  70611. }
  70612. /**
  70613. * Updates the raw cube texture.
  70614. * @param data defines the data to store
  70615. * @param format defines the data format
  70616. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70617. * @param invertY defines if data must be stored with Y axis inverted
  70618. * @param compression defines the compression used (null by default)
  70619. * @param level defines which level of the texture to update
  70620. */
  70621. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70622. if (compression === void 0) { compression = null; }
  70623. if (level === void 0) { level = 0; }
  70624. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70625. };
  70626. /**
  70627. * Updates a raw cube texture with RGBD encoded data.
  70628. * @param data defines the array of data [mipmap][face] to use to create each face
  70629. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70630. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70631. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70632. * @returns a promsie that resolves when the operation is complete
  70633. */
  70634. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70635. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70636. if (lodScale === void 0) { lodScale = 0.8; }
  70637. if (lodOffset === void 0) { lodOffset = 0; }
  70638. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70639. };
  70640. /**
  70641. * Clones the raw cube texture.
  70642. * @return a new cube texture
  70643. */
  70644. RawCubeTexture.prototype.clone = function () {
  70645. var _this = this;
  70646. return BABYLON.SerializationHelper.Clone(function () {
  70647. var scene = _this.getScene();
  70648. var internalTexture = _this._texture;
  70649. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70650. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70651. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70652. }
  70653. return texture;
  70654. }, this);
  70655. };
  70656. /** @hidden */
  70657. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70658. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70659. internalTexture._bufferViewArrayArray = data;
  70660. internalTexture._lodGenerationScale = lodScale;
  70661. internalTexture._lodGenerationOffset = lodOffset;
  70662. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70663. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70664. internalTexture.isReady = true;
  70665. });
  70666. };
  70667. return RawCubeTexture;
  70668. }(BABYLON.CubeTexture));
  70669. BABYLON.RawCubeTexture = RawCubeTexture;
  70670. })(BABYLON || (BABYLON = {}));
  70671. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70672. var BABYLON;
  70673. (function (BABYLON) {
  70674. var RenderTargetTexture = /** @class */ (function (_super) {
  70675. __extends(RenderTargetTexture, _super);
  70676. /**
  70677. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70678. * or used a shadow, depth texture...
  70679. * @param name The friendly name of the texture
  70680. * @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)
  70681. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70682. * @param generateMipMaps True if mip maps need to be generated after render.
  70683. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70684. * @param type The type of the buffer in the RTT (int, half float, float...)
  70685. * @param isCube True if a cube texture needs to be created
  70686. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70687. * @param generateDepthBuffer True to generate a depth buffer
  70688. * @param generateStencilBuffer True to generate a stencil buffer
  70689. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70690. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70691. */
  70692. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70693. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70694. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70695. if (isCube === void 0) { isCube = false; }
  70696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70697. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70698. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70699. if (isMulti === void 0) { isMulti = false; }
  70700. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70701. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70702. _this.isCube = isCube;
  70703. _this.renderParticles = true;
  70704. _this.renderSprites = false;
  70705. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70706. _this.ignoreCameraViewport = false;
  70707. // Events
  70708. /**
  70709. * An event triggered when the texture is unbind.
  70710. */
  70711. _this.onBeforeBindObservable = new BABYLON.Observable();
  70712. /**
  70713. * An event triggered when the texture is unbind.
  70714. */
  70715. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70716. /**
  70717. * An event triggered before rendering the texture
  70718. */
  70719. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70720. /**
  70721. * An event triggered after rendering the texture
  70722. */
  70723. _this.onAfterRenderObservable = new BABYLON.Observable();
  70724. /**
  70725. * An event triggered after the texture clear
  70726. */
  70727. _this.onClearObservable = new BABYLON.Observable();
  70728. _this._currentRefreshId = -1;
  70729. _this._refreshRate = 1;
  70730. _this._samples = 1;
  70731. /**
  70732. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70733. * It must define where the camera used to render the texture is set
  70734. */
  70735. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70736. scene = _this.getScene();
  70737. if (!scene) {
  70738. return _this;
  70739. }
  70740. _this.renderList = new Array();
  70741. _this._engine = scene.getEngine();
  70742. _this.name = name;
  70743. _this.isRenderTarget = true;
  70744. _this._initialSizeParameter = size;
  70745. _this._processSizeParameter(size);
  70746. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70747. });
  70748. _this._generateMipMaps = generateMipMaps ? true : false;
  70749. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70750. // Rendering groups
  70751. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70752. _this._renderingManager._useSceneAutoClearSetup = true;
  70753. if (isMulti) {
  70754. return _this;
  70755. }
  70756. _this._renderTargetOptions = {
  70757. generateMipMaps: generateMipMaps,
  70758. type: type,
  70759. format: format,
  70760. samplingMode: samplingMode,
  70761. generateDepthBuffer: generateDepthBuffer,
  70762. generateStencilBuffer: generateStencilBuffer
  70763. };
  70764. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70765. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70766. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70767. }
  70768. if (isCube) {
  70769. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70770. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70771. _this._textureMatrix = BABYLON.Matrix.Identity();
  70772. }
  70773. else {
  70774. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70775. }
  70776. return _this;
  70777. }
  70778. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70779. get: function () {
  70780. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70781. },
  70782. enumerable: true,
  70783. configurable: true
  70784. });
  70785. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70786. get: function () {
  70787. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70788. },
  70789. enumerable: true,
  70790. configurable: true
  70791. });
  70792. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  70793. get: function () {
  70794. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  70795. },
  70796. enumerable: true,
  70797. configurable: true
  70798. });
  70799. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  70800. /**
  70801. * Use this list to define the list of mesh you want to render.
  70802. */
  70803. get: function () {
  70804. return this._renderList;
  70805. },
  70806. set: function (value) {
  70807. this._renderList = value;
  70808. if (this._renderList) {
  70809. this._hookArray(this._renderList);
  70810. }
  70811. },
  70812. enumerable: true,
  70813. configurable: true
  70814. });
  70815. RenderTargetTexture.prototype._hookArray = function (array) {
  70816. var _this = this;
  70817. var oldPush = array.push;
  70818. array.push = function () {
  70819. var items = [];
  70820. for (var _i = 0; _i < arguments.length; _i++) {
  70821. items[_i] = arguments[_i];
  70822. }
  70823. var wasEmpty = array.length === 0;
  70824. var result = oldPush.apply(array, items);
  70825. if (wasEmpty) {
  70826. _this.getScene().meshes.forEach(function (mesh) {
  70827. mesh._markSubMeshesAsLightDirty();
  70828. });
  70829. }
  70830. return result;
  70831. };
  70832. var oldSplice = array.splice;
  70833. array.splice = function (index, deleteCount) {
  70834. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70835. if (array.length === 0) {
  70836. _this.getScene().meshes.forEach(function (mesh) {
  70837. mesh._markSubMeshesAsLightDirty();
  70838. });
  70839. }
  70840. return deleted;
  70841. };
  70842. };
  70843. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  70844. set: function (callback) {
  70845. if (this._onAfterUnbindObserver) {
  70846. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  70847. }
  70848. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  70849. },
  70850. enumerable: true,
  70851. configurable: true
  70852. });
  70853. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  70854. set: function (callback) {
  70855. if (this._onBeforeRenderObserver) {
  70856. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70857. }
  70858. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70859. },
  70860. enumerable: true,
  70861. configurable: true
  70862. });
  70863. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  70864. set: function (callback) {
  70865. if (this._onAfterRenderObserver) {
  70866. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70867. }
  70868. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70869. },
  70870. enumerable: true,
  70871. configurable: true
  70872. });
  70873. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  70874. set: function (callback) {
  70875. if (this._onClearObserver) {
  70876. this.onClearObservable.remove(this._onClearObserver);
  70877. }
  70878. this._onClearObserver = this.onClearObservable.add(callback);
  70879. },
  70880. enumerable: true,
  70881. configurable: true
  70882. });
  70883. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  70884. get: function () {
  70885. return this._renderTargetOptions;
  70886. },
  70887. enumerable: true,
  70888. configurable: true
  70889. });
  70890. RenderTargetTexture.prototype._onRatioRescale = function () {
  70891. if (this._sizeRatio) {
  70892. this.resize(this._initialSizeParameter);
  70893. }
  70894. };
  70895. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  70896. get: function () {
  70897. return this._boundingBoxSize;
  70898. },
  70899. /**
  70900. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  70901. * When defined, the cubemap will switch to local mode
  70902. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70903. * @example https://www.babylonjs-playground.com/#RNASML
  70904. */
  70905. set: function (value) {
  70906. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70907. return;
  70908. }
  70909. this._boundingBoxSize = value;
  70910. var scene = this.getScene();
  70911. if (scene) {
  70912. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70913. }
  70914. },
  70915. enumerable: true,
  70916. configurable: true
  70917. });
  70918. /**
  70919. * Creates a depth stencil texture.
  70920. * This is only available in WebGL 2 or with the depth texture extension available.
  70921. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  70922. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  70923. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  70924. */
  70925. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  70926. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  70927. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  70928. if (generateStencil === void 0) { generateStencil = false; }
  70929. if (!this.getScene()) {
  70930. return;
  70931. }
  70932. var engine = this.getScene().getEngine();
  70933. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  70934. bilinearFiltering: bilinearFiltering,
  70935. comparisonFunction: comparisonFunction,
  70936. generateStencil: generateStencil,
  70937. isCube: this.isCube
  70938. });
  70939. engine.setFrameBufferDepthStencilTexture(this);
  70940. };
  70941. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  70942. if (size.ratio) {
  70943. this._sizeRatio = size.ratio;
  70944. this._size = {
  70945. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  70946. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  70947. };
  70948. }
  70949. else {
  70950. this._size = size;
  70951. }
  70952. };
  70953. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  70954. get: function () {
  70955. return this._samples;
  70956. },
  70957. set: function (value) {
  70958. if (this._samples === value) {
  70959. return;
  70960. }
  70961. var scene = this.getScene();
  70962. if (!scene) {
  70963. return;
  70964. }
  70965. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  70966. },
  70967. enumerable: true,
  70968. configurable: true
  70969. });
  70970. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70971. this._currentRefreshId = -1;
  70972. };
  70973. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70974. get: function () {
  70975. return this._refreshRate;
  70976. },
  70977. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70978. set: function (value) {
  70979. this._refreshRate = value;
  70980. this.resetRefreshCounter();
  70981. },
  70982. enumerable: true,
  70983. configurable: true
  70984. });
  70985. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70986. if (!this._postProcessManager) {
  70987. var scene = this.getScene();
  70988. if (!scene) {
  70989. return;
  70990. }
  70991. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70992. this._postProcesses = new Array();
  70993. }
  70994. this._postProcesses.push(postProcess);
  70995. this._postProcesses[0].autoClear = false;
  70996. };
  70997. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70998. if (!this._postProcesses) {
  70999. return;
  71000. }
  71001. if (dispose) {
  71002. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71003. var postProcess = _a[_i];
  71004. postProcess.dispose();
  71005. }
  71006. }
  71007. this._postProcesses = [];
  71008. };
  71009. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71010. if (!this._postProcesses) {
  71011. return;
  71012. }
  71013. var index = this._postProcesses.indexOf(postProcess);
  71014. if (index === -1) {
  71015. return;
  71016. }
  71017. this._postProcesses.splice(index, 1);
  71018. if (this._postProcesses.length > 0) {
  71019. this._postProcesses[0].autoClear = false;
  71020. }
  71021. };
  71022. /** @hidden */
  71023. RenderTargetTexture.prototype._shouldRender = function () {
  71024. if (this._currentRefreshId === -1) { // At least render once
  71025. this._currentRefreshId = 1;
  71026. return true;
  71027. }
  71028. if (this.refreshRate === this._currentRefreshId) {
  71029. this._currentRefreshId = 1;
  71030. return true;
  71031. }
  71032. this._currentRefreshId++;
  71033. return false;
  71034. };
  71035. RenderTargetTexture.prototype.getRenderSize = function () {
  71036. if (this._size.width) {
  71037. return this._size.width;
  71038. }
  71039. return this._size;
  71040. };
  71041. RenderTargetTexture.prototype.getRenderWidth = function () {
  71042. if (this._size.width) {
  71043. return this._size.width;
  71044. }
  71045. return this._size;
  71046. };
  71047. RenderTargetTexture.prototype.getRenderHeight = function () {
  71048. if (this._size.width) {
  71049. return this._size.height;
  71050. }
  71051. return this._size;
  71052. };
  71053. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71054. get: function () {
  71055. return true;
  71056. },
  71057. enumerable: true,
  71058. configurable: true
  71059. });
  71060. RenderTargetTexture.prototype.scale = function (ratio) {
  71061. var newSize = this.getRenderSize() * ratio;
  71062. this.resize(newSize);
  71063. };
  71064. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71065. if (this.isCube) {
  71066. return this._textureMatrix;
  71067. }
  71068. return _super.prototype.getReflectionTextureMatrix.call(this);
  71069. };
  71070. RenderTargetTexture.prototype.resize = function (size) {
  71071. this.releaseInternalTexture();
  71072. var scene = this.getScene();
  71073. if (!scene) {
  71074. return;
  71075. }
  71076. this._processSizeParameter(size);
  71077. if (this.isCube) {
  71078. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71079. }
  71080. else {
  71081. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71082. }
  71083. };
  71084. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71085. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71086. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71087. var scene = this.getScene();
  71088. if (!scene) {
  71089. return;
  71090. }
  71091. var engine = scene.getEngine();
  71092. if (this.useCameraPostProcesses !== undefined) {
  71093. useCameraPostProcess = this.useCameraPostProcesses;
  71094. }
  71095. if (this._waitingRenderList) {
  71096. this.renderList = [];
  71097. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71098. var id = this._waitingRenderList[index];
  71099. var mesh_1 = scene.getMeshByID(id);
  71100. if (mesh_1) {
  71101. this.renderList.push(mesh_1);
  71102. }
  71103. }
  71104. delete this._waitingRenderList;
  71105. }
  71106. // Is predicate defined?
  71107. if (this.renderListPredicate) {
  71108. if (this.renderList) {
  71109. this.renderList.splice(0); // Clear previous renderList
  71110. }
  71111. else {
  71112. this.renderList = [];
  71113. }
  71114. var scene = this.getScene();
  71115. if (!scene) {
  71116. return;
  71117. }
  71118. var sceneMeshes = scene.meshes;
  71119. for (var index = 0; index < sceneMeshes.length; index++) {
  71120. var mesh = sceneMeshes[index];
  71121. if (this.renderListPredicate(mesh)) {
  71122. this.renderList.push(mesh);
  71123. }
  71124. }
  71125. }
  71126. this.onBeforeBindObservable.notifyObservers(this);
  71127. // Set custom projection.
  71128. // Needs to be before binding to prevent changing the aspect ratio.
  71129. var camera;
  71130. if (this.activeCamera) {
  71131. camera = this.activeCamera;
  71132. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71133. if (this.activeCamera !== scene.activeCamera) {
  71134. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71135. }
  71136. }
  71137. else {
  71138. camera = scene.activeCamera;
  71139. if (camera) {
  71140. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71141. }
  71142. }
  71143. // Prepare renderingManager
  71144. this._renderingManager.reset();
  71145. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71146. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71147. var sceneRenderId = scene.getRenderId();
  71148. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71149. var mesh = currentRenderList[meshIndex];
  71150. if (mesh) {
  71151. if (!mesh.isReady(this.refreshRate === 0)) {
  71152. this.resetRefreshCounter();
  71153. continue;
  71154. }
  71155. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71156. var isMasked = void 0;
  71157. if (!this.renderList && camera) {
  71158. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71159. }
  71160. else {
  71161. isMasked = false;
  71162. }
  71163. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71164. mesh._activate(sceneRenderId);
  71165. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71166. var subMesh = mesh.subMeshes[subIndex];
  71167. scene._activeIndices.addCount(subMesh.indexCount, false);
  71168. this._renderingManager.dispatch(subMesh, mesh);
  71169. }
  71170. }
  71171. }
  71172. }
  71173. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71174. var particleSystem = scene.particleSystems[particleIndex];
  71175. var emitter = particleSystem.emitter;
  71176. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71177. continue;
  71178. }
  71179. if (currentRenderList.indexOf(emitter) >= 0) {
  71180. this._renderingManager.dispatchParticles(particleSystem);
  71181. }
  71182. }
  71183. if (this.isCube) {
  71184. for (var face = 0; face < 6; face++) {
  71185. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71186. scene.incrementRenderId();
  71187. scene.resetCachedMaterial();
  71188. }
  71189. }
  71190. else {
  71191. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71192. }
  71193. this.onAfterUnbindObservable.notifyObservers(this);
  71194. if (scene.activeCamera) {
  71195. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71196. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71197. }
  71198. engine.setViewport(scene.activeCamera.viewport);
  71199. }
  71200. scene.resetCachedMaterial();
  71201. };
  71202. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71203. var minimum = 128;
  71204. var x = renderDimension * scale;
  71205. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71206. // Ensure we don't exceed the render dimension (while staying POT)
  71207. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71208. };
  71209. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71210. var _this = this;
  71211. if (!this._texture) {
  71212. return;
  71213. }
  71214. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71215. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71216. });
  71217. };
  71218. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71219. var scene = this.getScene();
  71220. if (!scene) {
  71221. return;
  71222. }
  71223. var engine = scene.getEngine();
  71224. if (!this._texture) {
  71225. return;
  71226. }
  71227. // Bind
  71228. if (this._postProcessManager) {
  71229. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71230. }
  71231. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71232. if (this._texture) {
  71233. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71234. }
  71235. }
  71236. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71237. // Clear
  71238. if (this.onClearObservable.hasObservers()) {
  71239. this.onClearObservable.notifyObservers(engine);
  71240. }
  71241. else {
  71242. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71243. }
  71244. if (!this._doNotChangeAspectRatio) {
  71245. scene.updateTransformMatrix(true);
  71246. }
  71247. // Render
  71248. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71249. if (this._postProcessManager) {
  71250. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71251. }
  71252. else if (useCameraPostProcess) {
  71253. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71254. }
  71255. if (!this._doNotChangeAspectRatio) {
  71256. scene.updateTransformMatrix(true);
  71257. }
  71258. // Dump ?
  71259. if (dumpForDebug) {
  71260. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71261. }
  71262. // Unbind
  71263. if (!this.isCube || faceIndex === 5) {
  71264. if (this.isCube) {
  71265. if (faceIndex === 5) {
  71266. engine.generateMipMapsForCubemap(this._texture);
  71267. }
  71268. }
  71269. this.unbindFrameBuffer(engine, faceIndex);
  71270. }
  71271. else {
  71272. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71273. }
  71274. };
  71275. /**
  71276. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71277. * This allowed control for front to back rendering or reversly depending of the special needs.
  71278. *
  71279. * @param renderingGroupId The rendering group id corresponding to its index
  71280. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71281. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71282. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71283. */
  71284. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71285. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71286. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71287. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71288. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71289. };
  71290. /**
  71291. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71292. *
  71293. * @param renderingGroupId The rendering group id corresponding to its index
  71294. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71295. */
  71296. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71297. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71298. this._renderingManager._useSceneAutoClearSetup = false;
  71299. };
  71300. RenderTargetTexture.prototype.clone = function () {
  71301. var textureSize = this.getSize();
  71302. 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);
  71303. // Base texture
  71304. newTexture.hasAlpha = this.hasAlpha;
  71305. newTexture.level = this.level;
  71306. // RenderTarget Texture
  71307. newTexture.coordinatesMode = this.coordinatesMode;
  71308. if (this.renderList) {
  71309. newTexture.renderList = this.renderList.slice(0);
  71310. }
  71311. return newTexture;
  71312. };
  71313. RenderTargetTexture.prototype.serialize = function () {
  71314. if (!this.name) {
  71315. return null;
  71316. }
  71317. var serializationObject = _super.prototype.serialize.call(this);
  71318. serializationObject.renderTargetSize = this.getRenderSize();
  71319. serializationObject.renderList = [];
  71320. if (this.renderList) {
  71321. for (var index = 0; index < this.renderList.length; index++) {
  71322. serializationObject.renderList.push(this.renderList[index].id);
  71323. }
  71324. }
  71325. return serializationObject;
  71326. };
  71327. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71328. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71329. var objBuffer = this.getInternalTexture();
  71330. var scene = this.getScene();
  71331. if (objBuffer && scene) {
  71332. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71333. }
  71334. };
  71335. RenderTargetTexture.prototype.dispose = function () {
  71336. if (this._postProcessManager) {
  71337. this._postProcessManager.dispose();
  71338. this._postProcessManager = null;
  71339. }
  71340. this.clearPostProcesses(true);
  71341. if (this._resizeObserver) {
  71342. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71343. this._resizeObserver = null;
  71344. }
  71345. this.renderList = null;
  71346. // Remove from custom render targets
  71347. var scene = this.getScene();
  71348. if (!scene) {
  71349. return;
  71350. }
  71351. var index = scene.customRenderTargets.indexOf(this);
  71352. if (index >= 0) {
  71353. scene.customRenderTargets.splice(index, 1);
  71354. }
  71355. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71356. var camera = _a[_i];
  71357. index = camera.customRenderTargets.indexOf(this);
  71358. if (index >= 0) {
  71359. camera.customRenderTargets.splice(index, 1);
  71360. }
  71361. }
  71362. _super.prototype.dispose.call(this);
  71363. };
  71364. /** @hidden */
  71365. RenderTargetTexture.prototype._rebuild = function () {
  71366. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71367. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71368. }
  71369. if (this._postProcessManager) {
  71370. this._postProcessManager._rebuild();
  71371. }
  71372. };
  71373. /**
  71374. * Clear the info related to rendering groups preventing retention point in material dispose.
  71375. */
  71376. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71377. if (this._renderingManager) {
  71378. this._renderingManager.freeRenderingGroups();
  71379. }
  71380. };
  71381. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71382. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71383. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71384. return RenderTargetTexture;
  71385. }(BABYLON.Texture));
  71386. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71387. })(BABYLON || (BABYLON = {}));
  71388. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71389. var BABYLON;
  71390. (function (BABYLON) {
  71391. ;
  71392. var MultiRenderTarget = /** @class */ (function (_super) {
  71393. __extends(MultiRenderTarget, _super);
  71394. function MultiRenderTarget(name, size, count, scene, options) {
  71395. var _this = this;
  71396. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71397. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71398. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71399. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71400. _this._engine = scene.getEngine();
  71401. if (!_this.isSupported) {
  71402. _this.dispose();
  71403. return;
  71404. }
  71405. var types = [];
  71406. var samplingModes = [];
  71407. for (var i = 0; i < count; i++) {
  71408. if (options && options.types && options.types[i] !== undefined) {
  71409. types.push(options.types[i]);
  71410. }
  71411. else {
  71412. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71413. }
  71414. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71415. samplingModes.push(options.samplingModes[i]);
  71416. }
  71417. else {
  71418. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71419. }
  71420. }
  71421. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71422. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71423. _this._size = size;
  71424. _this._multiRenderTargetOptions = {
  71425. samplingModes: samplingModes,
  71426. generateMipMaps: generateMipMaps,
  71427. generateDepthBuffer: generateDepthBuffer,
  71428. generateStencilBuffer: generateStencilBuffer,
  71429. generateDepthTexture: generateDepthTexture,
  71430. types: types,
  71431. textureCount: count
  71432. };
  71433. _this._createInternalTextures();
  71434. _this._createTextures();
  71435. return _this;
  71436. }
  71437. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71438. get: function () {
  71439. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71440. },
  71441. enumerable: true,
  71442. configurable: true
  71443. });
  71444. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71445. get: function () {
  71446. return this._textures;
  71447. },
  71448. enumerable: true,
  71449. configurable: true
  71450. });
  71451. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71452. get: function () {
  71453. return this._textures[this._textures.length - 1];
  71454. },
  71455. enumerable: true,
  71456. configurable: true
  71457. });
  71458. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71459. set: function (wrap) {
  71460. if (this._textures) {
  71461. for (var i = 0; i < this._textures.length; i++) {
  71462. this._textures[i].wrapU = wrap;
  71463. }
  71464. }
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71470. set: function (wrap) {
  71471. if (this._textures) {
  71472. for (var i = 0; i < this._textures.length; i++) {
  71473. this._textures[i].wrapV = wrap;
  71474. }
  71475. }
  71476. },
  71477. enumerable: true,
  71478. configurable: true
  71479. });
  71480. /** @hidden */
  71481. MultiRenderTarget.prototype._rebuild = function () {
  71482. this.releaseInternalTextures();
  71483. this._createInternalTextures();
  71484. for (var i = 0; i < this._internalTextures.length; i++) {
  71485. var texture = this._textures[i];
  71486. texture._texture = this._internalTextures[i];
  71487. }
  71488. // Keeps references to frame buffer and stencil/depth buffer
  71489. this._texture = this._internalTextures[0];
  71490. };
  71491. MultiRenderTarget.prototype._createInternalTextures = function () {
  71492. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71493. };
  71494. MultiRenderTarget.prototype._createTextures = function () {
  71495. this._textures = [];
  71496. for (var i = 0; i < this._internalTextures.length; i++) {
  71497. var texture = new BABYLON.Texture(null, this.getScene());
  71498. texture._texture = this._internalTextures[i];
  71499. this._textures.push(texture);
  71500. }
  71501. // Keeps references to frame buffer and stencil/depth buffer
  71502. this._texture = this._internalTextures[0];
  71503. };
  71504. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71505. get: function () {
  71506. return this._samples;
  71507. },
  71508. set: function (value) {
  71509. if (this._samples === value) {
  71510. return;
  71511. }
  71512. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71513. },
  71514. enumerable: true,
  71515. configurable: true
  71516. });
  71517. MultiRenderTarget.prototype.resize = function (size) {
  71518. this.releaseInternalTextures();
  71519. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71520. this._createInternalTextures();
  71521. };
  71522. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71523. var _this = this;
  71524. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71525. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71526. });
  71527. };
  71528. MultiRenderTarget.prototype.dispose = function () {
  71529. this.releaseInternalTextures();
  71530. _super.prototype.dispose.call(this);
  71531. };
  71532. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71533. if (!this._internalTextures) {
  71534. return;
  71535. }
  71536. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71537. if (this._internalTextures[i] !== undefined) {
  71538. this._internalTextures[i].dispose();
  71539. this._internalTextures.splice(i, 1);
  71540. }
  71541. }
  71542. };
  71543. return MultiRenderTarget;
  71544. }(BABYLON.RenderTargetTexture));
  71545. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71546. })(BABYLON || (BABYLON = {}));
  71547. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71548. var BABYLON;
  71549. (function (BABYLON) {
  71550. var MirrorTexture = /** @class */ (function (_super) {
  71551. __extends(MirrorTexture, _super);
  71552. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71553. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71555. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71556. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71557. _this.scene = scene;
  71558. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71559. _this._transformMatrix = BABYLON.Matrix.Zero();
  71560. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71561. _this._adaptiveBlurKernel = 0;
  71562. _this._blurKernelX = 0;
  71563. _this._blurKernelY = 0;
  71564. _this._blurRatio = 1.0;
  71565. _this.ignoreCameraViewport = true;
  71566. _this._updateGammaSpace();
  71567. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71568. _this._updateGammaSpace;
  71569. });
  71570. _this.onBeforeRenderObservable.add(function () {
  71571. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71572. _this._savedViewMatrix = scene.getViewMatrix();
  71573. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71574. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71575. scene.clipPlane = _this.mirrorPlane;
  71576. scene.getEngine().cullBackFaces = false;
  71577. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71578. });
  71579. _this.onAfterRenderObservable.add(function () {
  71580. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71581. scene.getEngine().cullBackFaces = true;
  71582. scene._mirroredCameraPosition = null;
  71583. delete scene.clipPlane;
  71584. });
  71585. return _this;
  71586. }
  71587. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71588. get: function () {
  71589. return this._blurRatio;
  71590. },
  71591. set: function (value) {
  71592. if (this._blurRatio === value) {
  71593. return;
  71594. }
  71595. this._blurRatio = value;
  71596. this._preparePostProcesses();
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71602. set: function (value) {
  71603. this._adaptiveBlurKernel = value;
  71604. this._autoComputeBlurKernel();
  71605. },
  71606. enumerable: true,
  71607. configurable: true
  71608. });
  71609. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71610. set: function (value) {
  71611. this.blurKernelX = value;
  71612. this.blurKernelY = value;
  71613. },
  71614. enumerable: true,
  71615. configurable: true
  71616. });
  71617. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71618. get: function () {
  71619. return this._blurKernelX;
  71620. },
  71621. set: function (value) {
  71622. if (this._blurKernelX === value) {
  71623. return;
  71624. }
  71625. this._blurKernelX = value;
  71626. this._preparePostProcesses();
  71627. },
  71628. enumerable: true,
  71629. configurable: true
  71630. });
  71631. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71632. get: function () {
  71633. return this._blurKernelY;
  71634. },
  71635. set: function (value) {
  71636. if (this._blurKernelY === value) {
  71637. return;
  71638. }
  71639. this._blurKernelY = value;
  71640. this._preparePostProcesses();
  71641. },
  71642. enumerable: true,
  71643. configurable: true
  71644. });
  71645. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  71646. var engine = this.getScene().getEngine();
  71647. var dw = this.getRenderWidth() / engine.getRenderWidth();
  71648. var dh = this.getRenderHeight() / engine.getRenderHeight();
  71649. this.blurKernelX = this._adaptiveBlurKernel * dw;
  71650. this.blurKernelY = this._adaptiveBlurKernel * dh;
  71651. };
  71652. MirrorTexture.prototype._onRatioRescale = function () {
  71653. if (this._sizeRatio) {
  71654. this.resize(this._initialSizeParameter);
  71655. if (!this._adaptiveBlurKernel) {
  71656. this._preparePostProcesses();
  71657. }
  71658. }
  71659. if (this._adaptiveBlurKernel) {
  71660. this._autoComputeBlurKernel();
  71661. }
  71662. };
  71663. MirrorTexture.prototype._updateGammaSpace = function () {
  71664. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  71665. };
  71666. MirrorTexture.prototype._preparePostProcesses = function () {
  71667. this.clearPostProcesses(true);
  71668. if (this._blurKernelX && this._blurKernelY) {
  71669. var engine = this.getScene().getEngine();
  71670. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71671. 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);
  71672. this._blurX.autoClear = false;
  71673. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  71674. this._blurX.inputTexture = this._texture;
  71675. }
  71676. else {
  71677. this._blurX.alwaysForcePOT = true;
  71678. }
  71679. 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);
  71680. this._blurY.autoClear = false;
  71681. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  71682. this.addPostProcess(this._blurX);
  71683. this.addPostProcess(this._blurY);
  71684. }
  71685. else {
  71686. if (this._blurY) {
  71687. this.removePostProcess(this._blurY);
  71688. this._blurY.dispose();
  71689. this._blurY = null;
  71690. }
  71691. if (this._blurX) {
  71692. this.removePostProcess(this._blurX);
  71693. this._blurX.dispose();
  71694. this._blurX = null;
  71695. }
  71696. }
  71697. };
  71698. MirrorTexture.prototype.clone = function () {
  71699. var scene = this.getScene();
  71700. if (!scene) {
  71701. return this;
  71702. }
  71703. var textureSize = this.getSize();
  71704. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  71705. // Base texture
  71706. newTexture.hasAlpha = this.hasAlpha;
  71707. newTexture.level = this.level;
  71708. // Mirror Texture
  71709. newTexture.mirrorPlane = this.mirrorPlane.clone();
  71710. if (this.renderList) {
  71711. newTexture.renderList = this.renderList.slice(0);
  71712. }
  71713. return newTexture;
  71714. };
  71715. MirrorTexture.prototype.serialize = function () {
  71716. if (!this.name) {
  71717. return null;
  71718. }
  71719. var serializationObject = _super.prototype.serialize.call(this);
  71720. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  71721. return serializationObject;
  71722. };
  71723. MirrorTexture.prototype.dispose = function () {
  71724. _super.prototype.dispose.call(this);
  71725. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  71726. };
  71727. return MirrorTexture;
  71728. }(BABYLON.RenderTargetTexture));
  71729. BABYLON.MirrorTexture = MirrorTexture;
  71730. })(BABYLON || (BABYLON = {}));
  71731. //# sourceMappingURL=babylon.mirrorTexture.js.map
  71732. var BABYLON;
  71733. (function (BABYLON) {
  71734. /**
  71735. * Creates a refraction texture used by refraction channel of the standard material.
  71736. * @param name the texture name
  71737. * @param size size of the underlying texture
  71738. * @param scene root scene
  71739. */
  71740. var RefractionTexture = /** @class */ (function (_super) {
  71741. __extends(RefractionTexture, _super);
  71742. function RefractionTexture(name, size, scene, generateMipMaps) {
  71743. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  71744. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  71745. _this.depth = 2.0;
  71746. _this.onBeforeRenderObservable.add(function () {
  71747. scene.clipPlane = _this.refractionPlane;
  71748. });
  71749. _this.onAfterRenderObservable.add(function () {
  71750. delete scene.clipPlane;
  71751. });
  71752. return _this;
  71753. }
  71754. RefractionTexture.prototype.clone = function () {
  71755. var scene = this.getScene();
  71756. if (!scene) {
  71757. return this;
  71758. }
  71759. var textureSize = this.getSize();
  71760. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  71761. // Base texture
  71762. newTexture.hasAlpha = this.hasAlpha;
  71763. newTexture.level = this.level;
  71764. // Refraction Texture
  71765. newTexture.refractionPlane = this.refractionPlane.clone();
  71766. if (this.renderList) {
  71767. newTexture.renderList = this.renderList.slice(0);
  71768. }
  71769. newTexture.depth = this.depth;
  71770. return newTexture;
  71771. };
  71772. RefractionTexture.prototype.serialize = function () {
  71773. if (!this.name) {
  71774. return null;
  71775. }
  71776. var serializationObject = _super.prototype.serialize.call(this);
  71777. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  71778. serializationObject.depth = this.depth;
  71779. return serializationObject;
  71780. };
  71781. return RefractionTexture;
  71782. }(BABYLON.RenderTargetTexture));
  71783. BABYLON.RefractionTexture = RefractionTexture;
  71784. })(BABYLON || (BABYLON = {}));
  71785. //# sourceMappingURL=babylon.refractionTexture.js.map
  71786. var BABYLON;
  71787. (function (BABYLON) {
  71788. /**
  71789. * A class extending {BABYLON.Texture} allowing drawing on a texture
  71790. * @see http://doc.babylonjs.com/how_to/dynamictexture
  71791. */
  71792. var DynamicTexture = /** @class */ (function (_super) {
  71793. __extends(DynamicTexture, _super);
  71794. /**
  71795. * Creates a {BABYLON.DynamicTexture}
  71796. * @param name defines the name of the texture
  71797. * @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
  71798. * @param scene defines the scene where you want the texture
  71799. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  71800. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  71801. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  71802. */
  71803. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  71804. if (scene === void 0) { scene = null; }
  71805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71806. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71807. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  71808. _this.name = name;
  71809. _this._engine = _this.getScene().getEngine();
  71810. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71811. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71812. _this._generateMipMaps = generateMipMaps;
  71813. if (options.getContext) {
  71814. _this._canvas = options;
  71815. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71816. }
  71817. else {
  71818. _this._canvas = document.createElement("canvas");
  71819. if (options.width || options.width === 0) {
  71820. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71821. }
  71822. else {
  71823. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  71824. }
  71825. }
  71826. var textureSize = _this.getSize();
  71827. _this._canvas.width = textureSize.width;
  71828. _this._canvas.height = textureSize.height;
  71829. _this._context = _this._canvas.getContext("2d");
  71830. return _this;
  71831. }
  71832. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  71833. /**
  71834. * Gets the current state of canRescale
  71835. */
  71836. get: function () {
  71837. return true;
  71838. },
  71839. enumerable: true,
  71840. configurable: true
  71841. });
  71842. DynamicTexture.prototype._recreate = function (textureSize) {
  71843. this._canvas.width = textureSize.width;
  71844. this._canvas.height = textureSize.height;
  71845. this.releaseInternalTexture();
  71846. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  71847. };
  71848. /**
  71849. * Scales the texture
  71850. * @param ratio the scale factor to apply to both width and height
  71851. */
  71852. DynamicTexture.prototype.scale = function (ratio) {
  71853. var textureSize = this.getSize();
  71854. textureSize.width *= ratio;
  71855. textureSize.height *= ratio;
  71856. this._recreate(textureSize);
  71857. };
  71858. /**
  71859. * Resizes the texture
  71860. * @param width the new width
  71861. * @param height the new height
  71862. */
  71863. DynamicTexture.prototype.scaleTo = function (width, height) {
  71864. var textureSize = this.getSize();
  71865. textureSize.width = width;
  71866. textureSize.height = height;
  71867. this._recreate(textureSize);
  71868. };
  71869. /**
  71870. * Gets the context of the canvas used by the texture
  71871. * @returns the canvas context of the dynamic texture
  71872. */
  71873. DynamicTexture.prototype.getContext = function () {
  71874. return this._context;
  71875. };
  71876. /**
  71877. * Clears the texture
  71878. */
  71879. DynamicTexture.prototype.clear = function () {
  71880. var size = this.getSize();
  71881. this._context.fillRect(0, 0, size.width, size.height);
  71882. };
  71883. /**
  71884. * Updates the texture
  71885. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71886. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  71887. */
  71888. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  71889. if (premulAlpha === void 0) { premulAlpha = false; }
  71890. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  71891. };
  71892. /**
  71893. * Draws text onto the texture
  71894. * @param text defines the text to be drawn
  71895. * @param x defines the placement of the text from the left
  71896. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  71897. * @param font defines the font to be used with font-style, font-size, font-name
  71898. * @param color defines the color used for the text
  71899. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  71900. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71901. * @param update defines whether texture is immediately update (default is true)
  71902. */
  71903. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  71904. if (update === void 0) { update = true; }
  71905. var size = this.getSize();
  71906. if (clearColor) {
  71907. this._context.fillStyle = clearColor;
  71908. this._context.fillRect(0, 0, size.width, size.height);
  71909. }
  71910. this._context.font = font;
  71911. if (x === null || x === undefined) {
  71912. var textSize = this._context.measureText(text);
  71913. x = (size.width - textSize.width) / 2;
  71914. }
  71915. if (y === null || y === undefined) {
  71916. var fontSize = parseInt((font.replace(/\D/g, '')));
  71917. y = (size.height / 2) + (fontSize / 3.65);
  71918. }
  71919. this._context.fillStyle = color;
  71920. this._context.fillText(text, x, y);
  71921. if (update) {
  71922. this.update(invertY);
  71923. }
  71924. };
  71925. /**
  71926. * Clones the texture
  71927. * @returns the clone of the texture.
  71928. */
  71929. DynamicTexture.prototype.clone = function () {
  71930. var scene = this.getScene();
  71931. if (!scene) {
  71932. return this;
  71933. }
  71934. var textureSize = this.getSize();
  71935. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  71936. // Base texture
  71937. newTexture.hasAlpha = this.hasAlpha;
  71938. newTexture.level = this.level;
  71939. // Dynamic Texture
  71940. newTexture.wrapU = this.wrapU;
  71941. newTexture.wrapV = this.wrapV;
  71942. return newTexture;
  71943. };
  71944. /**
  71945. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  71946. * @returns a serialized dynamic texture object
  71947. */
  71948. DynamicTexture.prototype.serialize = function () {
  71949. var scene = this.getScene();
  71950. if (scene && !scene.isReady()) {
  71951. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  71952. }
  71953. var serializationObject = _super.prototype.serialize.call(this);
  71954. serializationObject.base64String = this._canvas.toDataURL();
  71955. serializationObject.invertY = this._invertY;
  71956. serializationObject.samplingMode = this.samplingMode;
  71957. return serializationObject;
  71958. };
  71959. /** @hidden */
  71960. DynamicTexture.prototype._rebuild = function () {
  71961. this.update();
  71962. };
  71963. return DynamicTexture;
  71964. }(BABYLON.Texture));
  71965. BABYLON.DynamicTexture = DynamicTexture;
  71966. })(BABYLON || (BABYLON = {}));
  71967. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71968. var BABYLON;
  71969. (function (BABYLON) {
  71970. var VideoTexture = /** @class */ (function (_super) {
  71971. __extends(VideoTexture, _super);
  71972. /**
  71973. * Creates a video texture.
  71974. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71975. * @param {string | null} name optional name, will detect from video source, if not defined
  71976. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71977. * @param {BABYLON.Scene} scene is obviously the current scene.
  71978. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71979. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71980. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71981. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71982. */
  71983. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71984. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71985. if (invertY === void 0) { invertY = false; }
  71986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71987. if (settings === void 0) { settings = {
  71988. autoPlay: true,
  71989. loop: true,
  71990. autoUpdateTexture: true,
  71991. }; }
  71992. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71993. _this._onUserActionRequestedObservable = null;
  71994. _this._stillImageCaptured = false;
  71995. _this._poster = false;
  71996. _this._createInternalTexture = function () {
  71997. if (_this._texture != null) {
  71998. if (_this._poster) {
  71999. _this._texture.dispose();
  72000. _this._poster = false;
  72001. }
  72002. else {
  72003. return;
  72004. }
  72005. }
  72006. if (!_this._engine.needPOTTextures ||
  72007. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  72008. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72009. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72010. }
  72011. else {
  72012. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72013. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72014. _this._generateMipMaps = false;
  72015. }
  72016. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  72017. if (!_this.video.autoplay) {
  72018. var oldHandler_1 = _this.video.onplaying;
  72019. var error_1 = false;
  72020. _this.video.onplaying = function () {
  72021. _this.video.onplaying = oldHandler_1;
  72022. _this._texture.isReady = true;
  72023. _this._updateInternalTexture();
  72024. if (!error_1) {
  72025. _this.video.pause();
  72026. }
  72027. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72028. _this.onLoadObservable.notifyObservers(_this);
  72029. }
  72030. };
  72031. var playing = _this.video.play();
  72032. if (playing) {
  72033. playing.then(function () {
  72034. // Everything is good.
  72035. })
  72036. .catch(function () {
  72037. error_1 = true;
  72038. // On Chrome for instance, new policies might prevent playing without user interaction.
  72039. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72040. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72041. }
  72042. });
  72043. }
  72044. else {
  72045. _this.video.onplaying = oldHandler_1;
  72046. _this._texture.isReady = true;
  72047. _this._updateInternalTexture();
  72048. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72049. _this.onLoadObservable.notifyObservers(_this);
  72050. }
  72051. }
  72052. }
  72053. else {
  72054. _this._texture.isReady = true;
  72055. _this._updateInternalTexture();
  72056. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72057. _this.onLoadObservable.notifyObservers(_this);
  72058. }
  72059. }
  72060. };
  72061. _this.reset = function () {
  72062. if (_this._texture == null) {
  72063. return;
  72064. }
  72065. if (!_this._poster) {
  72066. _this._texture.dispose();
  72067. _this._texture = null;
  72068. }
  72069. };
  72070. _this._updateInternalTexture = function (e) {
  72071. if (_this._texture == null || !_this._texture.isReady) {
  72072. return;
  72073. }
  72074. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72075. return;
  72076. }
  72077. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72078. };
  72079. _this._engine = _this.getScene().getEngine();
  72080. _this._generateMipMaps = generateMipMaps;
  72081. _this._samplingMode = samplingMode;
  72082. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72083. _this.name = name || _this._getName(src);
  72084. _this.video = _this._getVideo(src);
  72085. if (settings.poster) {
  72086. _this.video.poster = settings.poster;
  72087. }
  72088. if (settings.autoPlay !== undefined) {
  72089. _this.video.autoplay = settings.autoPlay;
  72090. }
  72091. if (settings.loop !== undefined) {
  72092. _this.video.loop = settings.loop;
  72093. }
  72094. _this.video.setAttribute("playsinline", "");
  72095. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72096. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72097. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72098. _this.video.addEventListener("emptied", _this.reset);
  72099. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72100. _this._createInternalTexture();
  72101. }
  72102. if (settings.poster) {
  72103. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72104. _this._poster = true;
  72105. }
  72106. return _this;
  72107. }
  72108. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72109. get: function () {
  72110. if (!this._onUserActionRequestedObservable) {
  72111. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72112. }
  72113. return this._onUserActionRequestedObservable;
  72114. },
  72115. enumerable: true,
  72116. configurable: true
  72117. });
  72118. VideoTexture.prototype._getName = function (src) {
  72119. if (src instanceof HTMLVideoElement) {
  72120. return src.currentSrc;
  72121. }
  72122. if (typeof src === "object") {
  72123. return src.toString();
  72124. }
  72125. return src;
  72126. };
  72127. ;
  72128. VideoTexture.prototype._getVideo = function (src) {
  72129. if (src instanceof HTMLVideoElement) {
  72130. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72131. return src;
  72132. }
  72133. var video = document.createElement("video");
  72134. if (typeof src === "string") {
  72135. BABYLON.Tools.SetCorsBehavior(src, video);
  72136. video.src = src;
  72137. }
  72138. else {
  72139. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72140. src.forEach(function (url) {
  72141. var source = document.createElement("source");
  72142. source.src = url;
  72143. video.appendChild(source);
  72144. });
  72145. }
  72146. return video;
  72147. };
  72148. ;
  72149. /**
  72150. * @hidden Internal method to initiate `update`.
  72151. */
  72152. VideoTexture.prototype._rebuild = function () {
  72153. this.update();
  72154. };
  72155. /**
  72156. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72157. */
  72158. VideoTexture.prototype.update = function () {
  72159. if (!this.autoUpdateTexture) {
  72160. // Expecting user to call `updateTexture` manually
  72161. return;
  72162. }
  72163. this.updateTexture(true);
  72164. };
  72165. /**
  72166. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72167. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72168. */
  72169. VideoTexture.prototype.updateTexture = function (isVisible) {
  72170. if (!isVisible) {
  72171. return;
  72172. }
  72173. if (this.video.paused && this._stillImageCaptured) {
  72174. return;
  72175. }
  72176. this._stillImageCaptured = true;
  72177. this._updateInternalTexture();
  72178. };
  72179. /**
  72180. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72181. * @param url New url.
  72182. */
  72183. VideoTexture.prototype.updateURL = function (url) {
  72184. this.video.src = url;
  72185. };
  72186. VideoTexture.prototype.dispose = function () {
  72187. _super.prototype.dispose.call(this);
  72188. if (this._onUserActionRequestedObservable) {
  72189. this._onUserActionRequestedObservable.clear();
  72190. this._onUserActionRequestedObservable = null;
  72191. }
  72192. this.video.removeEventListener("canplay", this._createInternalTexture);
  72193. this.video.removeEventListener("paused", this._updateInternalTexture);
  72194. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72195. this.video.removeEventListener("emptied", this.reset);
  72196. this.video.pause();
  72197. };
  72198. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72199. var video = document.createElement("video");
  72200. video.setAttribute('autoplay', '');
  72201. video.setAttribute('muted', '');
  72202. video.setAttribute('playsinline', '');
  72203. var constraintsDeviceId;
  72204. if (constraints && constraints.deviceId) {
  72205. constraintsDeviceId = {
  72206. exact: constraints.deviceId,
  72207. };
  72208. }
  72209. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72210. if (navigator.mediaDevices) {
  72211. navigator.mediaDevices.getUserMedia({ video: constraints })
  72212. .then(function (stream) {
  72213. if (video.mozSrcObject !== undefined) {
  72214. // hack for Firefox < 19
  72215. video.mozSrcObject = stream;
  72216. }
  72217. else {
  72218. video.srcObject = stream;
  72219. }
  72220. var onPlaying = function () {
  72221. if (onReady) {
  72222. onReady(new VideoTexture("video", video, scene, true, true));
  72223. }
  72224. video.removeEventListener("playing", onPlaying);
  72225. };
  72226. video.addEventListener("playing", onPlaying);
  72227. video.play();
  72228. })
  72229. .catch(function (err) {
  72230. BABYLON.Tools.Error(err.name);
  72231. });
  72232. }
  72233. else {
  72234. navigator.getUserMedia =
  72235. navigator.getUserMedia ||
  72236. navigator.webkitGetUserMedia ||
  72237. navigator.mozGetUserMedia ||
  72238. navigator.msGetUserMedia;
  72239. if (navigator.getUserMedia) {
  72240. navigator.getUserMedia({
  72241. video: {
  72242. deviceId: constraintsDeviceId,
  72243. width: {
  72244. min: (constraints && constraints.minWidth) || 256,
  72245. max: (constraints && constraints.maxWidth) || 640,
  72246. },
  72247. height: {
  72248. min: (constraints && constraints.minHeight) || 256,
  72249. max: (constraints && constraints.maxHeight) || 480,
  72250. },
  72251. },
  72252. }, function (stream) {
  72253. if (video.mozSrcObject !== undefined) {
  72254. // hack for Firefox < 19
  72255. video.mozSrcObject = stream;
  72256. }
  72257. else {
  72258. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72259. }
  72260. video.play();
  72261. if (onReady) {
  72262. onReady(new VideoTexture("video", video, scene, true, true));
  72263. }
  72264. }, function (e) {
  72265. BABYLON.Tools.Error(e.name);
  72266. });
  72267. }
  72268. }
  72269. };
  72270. return VideoTexture;
  72271. }(BABYLON.Texture));
  72272. BABYLON.VideoTexture = VideoTexture;
  72273. })(BABYLON || (BABYLON = {}));
  72274. //# sourceMappingURL=babylon.videoTexture.js.map
  72275. var BABYLON;
  72276. (function (BABYLON) {
  72277. var RawTexture = /** @class */ (function (_super) {
  72278. __extends(RawTexture, _super);
  72279. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72281. if (invertY === void 0) { invertY = false; }
  72282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72283. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72284. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72285. _this.format = format;
  72286. _this._engine = scene.getEngine();
  72287. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72288. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72289. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72290. return _this;
  72291. }
  72292. RawTexture.prototype.update = function (data) {
  72293. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72294. };
  72295. // Statics
  72296. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72297. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72298. if (invertY === void 0) { invertY = false; }
  72299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72300. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72301. };
  72302. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72304. if (invertY === void 0) { invertY = false; }
  72305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72306. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72307. };
  72308. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72310. if (invertY === void 0) { invertY = false; }
  72311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72312. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72313. };
  72314. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72315. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72316. if (invertY === void 0) { invertY = false; }
  72317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72318. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72319. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72320. };
  72321. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72322. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72323. if (invertY === void 0) { invertY = false; }
  72324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72325. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72326. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72327. };
  72328. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72329. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72330. if (invertY === void 0) { invertY = false; }
  72331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72332. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72333. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72334. };
  72335. return RawTexture;
  72336. }(BABYLON.Texture));
  72337. BABYLON.RawTexture = RawTexture;
  72338. })(BABYLON || (BABYLON = {}));
  72339. //# sourceMappingURL=babylon.rawTexture.js.map
  72340. var BABYLON;
  72341. (function (BABYLON) {
  72342. /**
  72343. * Class used to store 3D textures containing user data
  72344. */
  72345. var RawTexture3D = /** @class */ (function (_super) {
  72346. __extends(RawTexture3D, _super);
  72347. /**
  72348. * Create a new RawTexture3D
  72349. * @param data defines the data of the texture
  72350. * @param width defines the width of the texture
  72351. * @param height defines the height of the texture
  72352. * @param depth defines the depth of the texture
  72353. * @param format defines the texture format to use
  72354. * @param scene defines the hosting scene
  72355. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72356. * @param invertY defines if texture must be stored with Y axis inverted
  72357. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72358. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72359. */
  72360. function RawTexture3D(data, width, height, depth,
  72361. /** Gets or sets the texture format to use */
  72362. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72364. if (invertY === void 0) { invertY = false; }
  72365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72366. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72367. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72368. _this.format = format;
  72369. _this._engine = scene.getEngine();
  72370. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72371. _this.is3D = true;
  72372. return _this;
  72373. }
  72374. /**
  72375. * Update the texture with new data
  72376. * @param data defines the data to store in the texture
  72377. */
  72378. RawTexture3D.prototype.update = function (data) {
  72379. if (!this._texture) {
  72380. return;
  72381. }
  72382. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72383. };
  72384. return RawTexture3D;
  72385. }(BABYLON.Texture));
  72386. BABYLON.RawTexture3D = RawTexture3D;
  72387. })(BABYLON || (BABYLON = {}));
  72388. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72389. var BABYLON;
  72390. (function (BABYLON) {
  72391. /**
  72392. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72393. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72394. */
  72395. var PostProcessManager = /** @class */ (function () {
  72396. /**
  72397. * Creates a new instance PostProcess
  72398. * @param scene The scene that the post process is associated with.
  72399. */
  72400. function PostProcessManager(scene) {
  72401. this._vertexBuffers = {};
  72402. this._scene = scene;
  72403. }
  72404. PostProcessManager.prototype._prepareBuffers = function () {
  72405. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72406. return;
  72407. }
  72408. // VBO
  72409. var vertices = [];
  72410. vertices.push(1, 1);
  72411. vertices.push(-1, 1);
  72412. vertices.push(-1, -1);
  72413. vertices.push(1, -1);
  72414. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72415. this._buildIndexBuffer();
  72416. };
  72417. PostProcessManager.prototype._buildIndexBuffer = function () {
  72418. // Indices
  72419. var indices = [];
  72420. indices.push(0);
  72421. indices.push(1);
  72422. indices.push(2);
  72423. indices.push(0);
  72424. indices.push(2);
  72425. indices.push(3);
  72426. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72427. };
  72428. /**
  72429. * Rebuilds the vertex buffers of the manager.
  72430. * @hidden
  72431. */
  72432. PostProcessManager.prototype._rebuild = function () {
  72433. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72434. if (!vb) {
  72435. return;
  72436. }
  72437. vb._rebuild();
  72438. this._buildIndexBuffer();
  72439. };
  72440. // Methods
  72441. /**
  72442. * Prepares a frame to be run through a post process.
  72443. * @param sourceTexture The input texture to the post procesess. (default: null)
  72444. * @param postProcesses An array of post processes to be run. (default: null)
  72445. * @returns True if the post processes were able to be run.
  72446. * @hidden
  72447. */
  72448. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72449. if (sourceTexture === void 0) { sourceTexture = null; }
  72450. if (postProcesses === void 0) { postProcesses = null; }
  72451. var camera = this._scene.activeCamera;
  72452. if (!camera) {
  72453. return false;
  72454. }
  72455. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72456. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72457. return false;
  72458. }
  72459. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72460. return true;
  72461. };
  72462. /**
  72463. * Manually render a set of post processes to a texture.
  72464. * @param postProcesses An array of post processes to be run.
  72465. * @param targetTexture The target texture to render to.
  72466. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72467. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72468. * @param lodLevel defines which lod of the texture to render to
  72469. */
  72470. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72471. if (targetTexture === void 0) { targetTexture = null; }
  72472. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72473. if (faceIndex === void 0) { faceIndex = 0; }
  72474. if (lodLevel === void 0) { lodLevel = 0; }
  72475. var engine = this._scene.getEngine();
  72476. for (var index = 0; index < postProcesses.length; index++) {
  72477. if (index < postProcesses.length - 1) {
  72478. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72479. }
  72480. else {
  72481. if (targetTexture) {
  72482. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72483. }
  72484. else {
  72485. engine.restoreDefaultFramebuffer();
  72486. }
  72487. }
  72488. var pp = postProcesses[index];
  72489. var effect = pp.apply();
  72490. if (effect) {
  72491. pp.onBeforeRenderObservable.notifyObservers(effect);
  72492. // VBOs
  72493. this._prepareBuffers();
  72494. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72495. // Draw order
  72496. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72497. pp.onAfterRenderObservable.notifyObservers(effect);
  72498. }
  72499. }
  72500. // Restore depth buffer
  72501. engine.setDepthBuffer(true);
  72502. engine.setDepthWrite(true);
  72503. };
  72504. /**
  72505. * Finalize the result of the output of the postprocesses.
  72506. * @param doNotPresent If true the result will not be displayed to the screen.
  72507. * @param targetTexture The target texture to render to.
  72508. * @param faceIndex The index of the face to bind the target texture to.
  72509. * @param postProcesses The array of post processes to render.
  72510. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  72511. * @hidden
  72512. */
  72513. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  72514. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72515. var camera = this._scene.activeCamera;
  72516. if (!camera) {
  72517. return;
  72518. }
  72519. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72520. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72521. return;
  72522. }
  72523. var engine = this._scene.getEngine();
  72524. for (var index = 0, len = postProcesses.length; index < len; index++) {
  72525. var pp = postProcesses[index];
  72526. if (index < len - 1) {
  72527. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  72528. }
  72529. else {
  72530. if (targetTexture) {
  72531. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  72532. pp._outputTexture = targetTexture;
  72533. }
  72534. else {
  72535. engine.restoreDefaultFramebuffer();
  72536. pp._outputTexture = null;
  72537. }
  72538. }
  72539. if (doNotPresent) {
  72540. break;
  72541. }
  72542. var effect = pp.apply();
  72543. if (effect) {
  72544. pp.onBeforeRenderObservable.notifyObservers(effect);
  72545. // VBOs
  72546. this._prepareBuffers();
  72547. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72548. // Draw order
  72549. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72550. pp.onAfterRenderObservable.notifyObservers(effect);
  72551. }
  72552. }
  72553. // Restore states
  72554. engine.setDepthBuffer(true);
  72555. engine.setDepthWrite(true);
  72556. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72557. };
  72558. /**
  72559. * Disposes of the post process manager.
  72560. */
  72561. PostProcessManager.prototype.dispose = function () {
  72562. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72563. if (buffer) {
  72564. buffer.dispose();
  72565. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72566. }
  72567. if (this._indexBuffer) {
  72568. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72569. this._indexBuffer = null;
  72570. }
  72571. };
  72572. return PostProcessManager;
  72573. }());
  72574. BABYLON.PostProcessManager = PostProcessManager;
  72575. })(BABYLON || (BABYLON = {}));
  72576. //# sourceMappingURL=babylon.postProcessManager.js.map
  72577. var BABYLON;
  72578. (function (BABYLON) {
  72579. /**
  72580. * PostProcess can be used to apply a shader to a texture after it has been rendered
  72581. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72582. */
  72583. var PostProcess = /** @class */ (function () {
  72584. /**
  72585. * Creates a new instance PostProcess
  72586. * @param name The name of the PostProcess.
  72587. * @param fragmentUrl The url of the fragment shader to be used.
  72588. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  72589. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  72590. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72591. * @param camera The camera to apply the render pass to.
  72592. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72593. * @param engine The engine which the post process will be applied. (default: current engine)
  72594. * @param reusable If the post process can be reused on the same frame. (default: false)
  72595. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  72596. * @param textureType Type of textures used when performing the post process. (default: 0)
  72597. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  72598. * @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
  72599. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  72600. */
  72601. function PostProcess(
  72602. /** Name of the PostProcess. */
  72603. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  72604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  72605. if (defines === void 0) { defines = null; }
  72606. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72607. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  72608. if (blockCompilation === void 0) { blockCompilation = false; }
  72609. this.name = name;
  72610. /**
  72611. * Width of the texture to apply the post process on
  72612. */
  72613. this.width = -1;
  72614. /**
  72615. * Height of the texture to apply the post process on
  72616. */
  72617. this.height = -1;
  72618. /**
  72619. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  72620. * @hidden
  72621. */
  72622. this._outputTexture = null;
  72623. /**
  72624. * If the buffer needs to be cleared before applying the post process. (default: true)
  72625. * Should be set to false if shader will overwrite all previous pixels.
  72626. */
  72627. this.autoClear = true;
  72628. /**
  72629. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  72630. */
  72631. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  72632. /**
  72633. * Animations to be used for the post processing
  72634. */
  72635. this.animations = new Array();
  72636. /**
  72637. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  72638. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  72639. */
  72640. this.enablePixelPerfectMode = false;
  72641. /**
  72642. * Force the postprocess to be applied without taking in account viewport
  72643. */
  72644. this.forceFullscreenViewport = true;
  72645. /**
  72646. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  72647. *
  72648. * | Value | Type | Description |
  72649. * | ----- | ----------------------------------- | ----------- |
  72650. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  72651. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  72652. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  72653. *
  72654. */
  72655. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  72656. /**
  72657. * Force textures to be a power of two (default: false)
  72658. */
  72659. this.alwaysForcePOT = false;
  72660. this._samples = 1;
  72661. /**
  72662. * Modify the scale of the post process to be the same as the viewport (default: false)
  72663. */
  72664. this.adaptScaleToCurrentViewport = false;
  72665. this._reusable = false;
  72666. /**
  72667. * Smart array of input and output textures for the post process.
  72668. * @hidden
  72669. */
  72670. this._textures = new BABYLON.SmartArray(2);
  72671. /**
  72672. * The index in _textures that corresponds to the output texture.
  72673. * @hidden
  72674. */
  72675. this._currentRenderTextureInd = 0;
  72676. this._scaleRatio = new BABYLON.Vector2(1, 1);
  72677. this._texelSize = BABYLON.Vector2.Zero();
  72678. // Events
  72679. /**
  72680. * An event triggered when the postprocess is activated.
  72681. */
  72682. this.onActivateObservable = new BABYLON.Observable();
  72683. /**
  72684. * An event triggered when the postprocess changes its size.
  72685. */
  72686. this.onSizeChangedObservable = new BABYLON.Observable();
  72687. /**
  72688. * An event triggered when the postprocess applies its effect.
  72689. */
  72690. this.onApplyObservable = new BABYLON.Observable();
  72691. /**
  72692. * An event triggered before rendering the postprocess
  72693. */
  72694. this.onBeforeRenderObservable = new BABYLON.Observable();
  72695. /**
  72696. * An event triggered after rendering the postprocess
  72697. */
  72698. this.onAfterRenderObservable = new BABYLON.Observable();
  72699. if (camera != null) {
  72700. this._camera = camera;
  72701. this._scene = camera.getScene();
  72702. camera.attachPostProcess(this);
  72703. this._engine = this._scene.getEngine();
  72704. this._scene.postProcesses.push(this);
  72705. }
  72706. else if (engine) {
  72707. this._engine = engine;
  72708. this._engine.postProcesses.push(this);
  72709. }
  72710. this._options = options;
  72711. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  72712. this._reusable = reusable || false;
  72713. this._textureType = textureType;
  72714. this._samplers = samplers || [];
  72715. this._samplers.push("textureSampler");
  72716. this._fragmentUrl = fragmentUrl;
  72717. this._vertexUrl = vertexUrl;
  72718. this._parameters = parameters || [];
  72719. this._parameters.push("scale");
  72720. this._indexParameters = indexParameters;
  72721. if (!blockCompilation) {
  72722. this.updateEffect(defines);
  72723. }
  72724. }
  72725. Object.defineProperty(PostProcess.prototype, "samples", {
  72726. /**
  72727. * Number of sample textures (default: 1)
  72728. */
  72729. get: function () {
  72730. return this._samples;
  72731. },
  72732. set: function (n) {
  72733. var _this = this;
  72734. this._samples = n;
  72735. this._textures.forEach(function (texture) {
  72736. if (texture.samples !== _this._samples) {
  72737. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  72738. }
  72739. });
  72740. },
  72741. enumerable: true,
  72742. configurable: true
  72743. });
  72744. Object.defineProperty(PostProcess.prototype, "onActivate", {
  72745. /**
  72746. * A function that is added to the onActivateObservable
  72747. */
  72748. set: function (callback) {
  72749. if (this._onActivateObserver) {
  72750. this.onActivateObservable.remove(this._onActivateObserver);
  72751. }
  72752. if (callback) {
  72753. this._onActivateObserver = this.onActivateObservable.add(callback);
  72754. }
  72755. },
  72756. enumerable: true,
  72757. configurable: true
  72758. });
  72759. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  72760. /**
  72761. * A function that is added to the onSizeChangedObservable
  72762. */
  72763. set: function (callback) {
  72764. if (this._onSizeChangedObserver) {
  72765. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  72766. }
  72767. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  72768. },
  72769. enumerable: true,
  72770. configurable: true
  72771. });
  72772. Object.defineProperty(PostProcess.prototype, "onApply", {
  72773. /**
  72774. * A function that is added to the onApplyObservable
  72775. */
  72776. set: function (callback) {
  72777. if (this._onApplyObserver) {
  72778. this.onApplyObservable.remove(this._onApplyObserver);
  72779. }
  72780. this._onApplyObserver = this.onApplyObservable.add(callback);
  72781. },
  72782. enumerable: true,
  72783. configurable: true
  72784. });
  72785. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  72786. /**
  72787. * A function that is added to the onBeforeRenderObservable
  72788. */
  72789. set: function (callback) {
  72790. if (this._onBeforeRenderObserver) {
  72791. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72792. }
  72793. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72794. },
  72795. enumerable: true,
  72796. configurable: true
  72797. });
  72798. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  72799. /**
  72800. * A function that is added to the onAfterRenderObservable
  72801. */
  72802. set: function (callback) {
  72803. if (this._onAfterRenderObserver) {
  72804. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72805. }
  72806. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72807. },
  72808. enumerable: true,
  72809. configurable: true
  72810. });
  72811. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  72812. /**
  72813. * 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
  72814. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  72815. */
  72816. get: function () {
  72817. return this._textures.data[this._currentRenderTextureInd];
  72818. },
  72819. set: function (value) {
  72820. this._forcedOutputTexture = value;
  72821. },
  72822. enumerable: true,
  72823. configurable: true
  72824. });
  72825. /**
  72826. * Gets the camera which post process is applied to.
  72827. * @returns The camera the post process is applied to.
  72828. */
  72829. PostProcess.prototype.getCamera = function () {
  72830. return this._camera;
  72831. };
  72832. Object.defineProperty(PostProcess.prototype, "texelSize", {
  72833. /**
  72834. * Gets the texel size of the postprocess.
  72835. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  72836. */
  72837. get: function () {
  72838. if (this._shareOutputWithPostProcess) {
  72839. return this._shareOutputWithPostProcess.texelSize;
  72840. }
  72841. if (this._forcedOutputTexture) {
  72842. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  72843. }
  72844. return this._texelSize;
  72845. },
  72846. enumerable: true,
  72847. configurable: true
  72848. });
  72849. /**
  72850. * Gets the engine which this post process belongs to.
  72851. * @returns The engine the post process was enabled with.
  72852. */
  72853. PostProcess.prototype.getEngine = function () {
  72854. return this._engine;
  72855. };
  72856. /**
  72857. * The effect that is created when initializing the post process.
  72858. * @returns The created effect corrisponding the the postprocess.
  72859. */
  72860. PostProcess.prototype.getEffect = function () {
  72861. return this._effect;
  72862. };
  72863. /**
  72864. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  72865. * @param postProcess The post process to share the output with.
  72866. * @returns This post process.
  72867. */
  72868. PostProcess.prototype.shareOutputWith = function (postProcess) {
  72869. this._disposeTextures();
  72870. this._shareOutputWithPostProcess = postProcess;
  72871. return this;
  72872. };
  72873. /**
  72874. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  72875. * This should be called if the post process that shares output with this post process is disabled/disposed.
  72876. */
  72877. PostProcess.prototype.useOwnOutput = function () {
  72878. if (this._textures.length == 0) {
  72879. this._textures = new BABYLON.SmartArray(2);
  72880. }
  72881. this._shareOutputWithPostProcess = null;
  72882. };
  72883. /**
  72884. * Updates the effect with the current post process compile time values and recompiles the shader.
  72885. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72886. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72887. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72888. * @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
  72889. * @param onCompiled Called when the shader has been compiled.
  72890. * @param onError Called if there is an error when compiling a shader.
  72891. */
  72892. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72893. if (defines === void 0) { defines = null; }
  72894. if (uniforms === void 0) { uniforms = null; }
  72895. if (samplers === void 0) { samplers = null; }
  72896. 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);
  72897. };
  72898. /**
  72899. * The post process is reusable if it can be used multiple times within one frame.
  72900. * @returns If the post process is reusable
  72901. */
  72902. PostProcess.prototype.isReusable = function () {
  72903. return this._reusable;
  72904. };
  72905. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  72906. PostProcess.prototype.markTextureDirty = function () {
  72907. this.width = -1;
  72908. };
  72909. /**
  72910. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  72911. * 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.
  72912. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  72913. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  72914. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  72915. * @returns The target texture that was bound to be written to.
  72916. */
  72917. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  72918. var _this = this;
  72919. if (sourceTexture === void 0) { sourceTexture = null; }
  72920. camera = camera || this._camera;
  72921. var scene = camera.getScene();
  72922. var engine = scene.getEngine();
  72923. var maxSize = engine.getCaps().maxTextureSize;
  72924. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  72925. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  72926. // 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
  72927. var webVRCamera = camera.parent;
  72928. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  72929. requiredWidth /= 2;
  72930. }
  72931. var desiredWidth = (this._options.width || requiredWidth);
  72932. var desiredHeight = this._options.height || requiredHeight;
  72933. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  72934. if (this.adaptScaleToCurrentViewport) {
  72935. var currentViewport = engine.currentViewport;
  72936. if (currentViewport) {
  72937. desiredWidth *= currentViewport.width;
  72938. desiredHeight *= currentViewport.height;
  72939. }
  72940. }
  72941. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  72942. if (!this._options.width) {
  72943. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  72944. }
  72945. if (!this._options.height) {
  72946. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  72947. }
  72948. }
  72949. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  72950. if (this._textures.length > 0) {
  72951. for (var i = 0; i < this._textures.length; i++) {
  72952. this._engine._releaseTexture(this._textures.data[i]);
  72953. }
  72954. this._textures.reset();
  72955. }
  72956. this.width = desiredWidth;
  72957. this.height = desiredHeight;
  72958. var textureSize = { width: this.width, height: this.height };
  72959. var textureOptions = {
  72960. generateMipMaps: false,
  72961. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  72962. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  72963. samplingMode: this.renderTargetSamplingMode,
  72964. type: this._textureType
  72965. };
  72966. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72967. if (this._reusable) {
  72968. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72969. }
  72970. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72971. this.onSizeChangedObservable.notifyObservers(this);
  72972. }
  72973. this._textures.forEach(function (texture) {
  72974. if (texture.samples !== _this.samples) {
  72975. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72976. }
  72977. });
  72978. }
  72979. var target;
  72980. if (this._shareOutputWithPostProcess) {
  72981. target = this._shareOutputWithPostProcess.inputTexture;
  72982. }
  72983. else if (this._forcedOutputTexture) {
  72984. target = this._forcedOutputTexture;
  72985. this.width = this._forcedOutputTexture.width;
  72986. this.height = this._forcedOutputTexture.height;
  72987. }
  72988. else {
  72989. target = this.inputTexture;
  72990. }
  72991. // Bind the input of this post process to be used as the output of the previous post process.
  72992. if (this.enablePixelPerfectMode) {
  72993. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72994. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72995. }
  72996. else {
  72997. this._scaleRatio.copyFromFloats(1, 1);
  72998. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72999. }
  73000. this.onActivateObservable.notifyObservers(camera);
  73001. // Clear
  73002. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  73003. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  73004. }
  73005. if (this._reusable) {
  73006. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  73007. }
  73008. return target;
  73009. };
  73010. Object.defineProperty(PostProcess.prototype, "isSupported", {
  73011. /**
  73012. * If the post process is supported.
  73013. */
  73014. get: function () {
  73015. return this._effect.isSupported;
  73016. },
  73017. enumerable: true,
  73018. configurable: true
  73019. });
  73020. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  73021. /**
  73022. * The aspect ratio of the output texture.
  73023. */
  73024. get: function () {
  73025. if (this._shareOutputWithPostProcess) {
  73026. return this._shareOutputWithPostProcess.aspectRatio;
  73027. }
  73028. if (this._forcedOutputTexture) {
  73029. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73030. }
  73031. return this.width / this.height;
  73032. },
  73033. enumerable: true,
  73034. configurable: true
  73035. });
  73036. /**
  73037. * Get a value indicating if the post-process is ready to be used
  73038. * @returns true if the post-process is ready (shader is compiled)
  73039. */
  73040. PostProcess.prototype.isReady = function () {
  73041. return this._effect && this._effect.isReady();
  73042. };
  73043. /**
  73044. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73045. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73046. */
  73047. PostProcess.prototype.apply = function () {
  73048. // Check
  73049. if (!this._effect || !this._effect.isReady())
  73050. return null;
  73051. // States
  73052. this._engine.enableEffect(this._effect);
  73053. this._engine.setState(false);
  73054. this._engine.setDepthBuffer(false);
  73055. this._engine.setDepthWrite(false);
  73056. // Alpha
  73057. this._engine.setAlphaMode(this.alphaMode);
  73058. if (this.alphaConstants) {
  73059. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73060. }
  73061. // Bind the output texture of the preivous post process as the input to this post process.
  73062. var source;
  73063. if (this._shareOutputWithPostProcess) {
  73064. source = this._shareOutputWithPostProcess.inputTexture;
  73065. }
  73066. else if (this._forcedOutputTexture) {
  73067. source = this._forcedOutputTexture;
  73068. }
  73069. else {
  73070. source = this.inputTexture;
  73071. }
  73072. this._effect._bindTexture("textureSampler", source);
  73073. // Parameters
  73074. this._effect.setVector2("scale", this._scaleRatio);
  73075. this.onApplyObservable.notifyObservers(this._effect);
  73076. return this._effect;
  73077. };
  73078. PostProcess.prototype._disposeTextures = function () {
  73079. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73080. return;
  73081. }
  73082. if (this._textures.length > 0) {
  73083. for (var i = 0; i < this._textures.length; i++) {
  73084. this._engine._releaseTexture(this._textures.data[i]);
  73085. }
  73086. }
  73087. this._textures.dispose();
  73088. };
  73089. /**
  73090. * Disposes the post process.
  73091. * @param camera The camera to dispose the post process on.
  73092. */
  73093. PostProcess.prototype.dispose = function (camera) {
  73094. camera = camera || this._camera;
  73095. this._disposeTextures();
  73096. if (this._scene) {
  73097. var index_1 = this._scene.postProcesses.indexOf(this);
  73098. if (index_1 !== -1) {
  73099. this._scene.postProcesses.splice(index_1, 1);
  73100. }
  73101. }
  73102. else {
  73103. var index_2 = this._engine.postProcesses.indexOf(this);
  73104. if (index_2 !== -1) {
  73105. this._engine.postProcesses.splice(index_2, 1);
  73106. }
  73107. }
  73108. if (!camera) {
  73109. return;
  73110. }
  73111. camera.detachPostProcess(this);
  73112. var index = camera._postProcesses.indexOf(this);
  73113. if (index === 0 && camera._postProcesses.length > 0) {
  73114. var firstPostProcess = this._camera._getFirstPostProcess();
  73115. if (firstPostProcess) {
  73116. firstPostProcess.markTextureDirty();
  73117. }
  73118. }
  73119. this.onActivateObservable.clear();
  73120. this.onAfterRenderObservable.clear();
  73121. this.onApplyObservable.clear();
  73122. this.onBeforeRenderObservable.clear();
  73123. this.onSizeChangedObservable.clear();
  73124. };
  73125. return PostProcess;
  73126. }());
  73127. BABYLON.PostProcess = PostProcess;
  73128. })(BABYLON || (BABYLON = {}));
  73129. //# sourceMappingURL=babylon.postProcess.js.map
  73130. var BABYLON;
  73131. (function (BABYLON) {
  73132. var PassPostProcess = /** @class */ (function (_super) {
  73133. __extends(PassPostProcess, _super);
  73134. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73135. if (camera === void 0) { camera = null; }
  73136. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73137. if (blockCompilation === void 0) { blockCompilation = false; }
  73138. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73139. }
  73140. return PassPostProcess;
  73141. }(BABYLON.PostProcess));
  73142. BABYLON.PassPostProcess = PassPostProcess;
  73143. })(BABYLON || (BABYLON = {}));
  73144. //# sourceMappingURL=babylon.passPostProcess.js.map
  73145. var __assign = (this && this.__assign) || function () {
  73146. __assign = Object.assign || function(t) {
  73147. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73148. s = arguments[i];
  73149. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73150. t[p] = s[p];
  73151. }
  73152. return t;
  73153. };
  73154. return __assign.apply(this, arguments);
  73155. };
  73156. var BABYLON;
  73157. (function (BABYLON) {
  73158. /**
  73159. * Default implementation IShadowGenerator.
  73160. * This is the main object responsible of generating shadows in the framework.
  73161. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73162. */
  73163. var ShadowGenerator = /** @class */ (function () {
  73164. /**
  73165. * Creates a ShadowGenerator object.
  73166. * A ShadowGenerator is the required tool to use the shadows.
  73167. * Each light casting shadows needs to use its own ShadowGenerator.
  73168. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73169. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73170. * @param light The light object generating the shadows.
  73171. * @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.
  73172. */
  73173. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73174. this._bias = 0.00005;
  73175. this._normalBias = 0;
  73176. this._blurBoxOffset = 1;
  73177. this._blurScale = 2;
  73178. this._blurKernel = 1;
  73179. this._useKernelBlur = false;
  73180. this._filter = ShadowGenerator.FILTER_NONE;
  73181. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73182. this._contactHardeningLightSizeUVRatio = 0.1;
  73183. this._darkness = 0;
  73184. this._transparencyShadow = false;
  73185. /**
  73186. * Controls the extent to which the shadows fade out at the edge of the frustum
  73187. * Used only by directionals and spots
  73188. */
  73189. this.frustumEdgeFalloff = 0;
  73190. /**
  73191. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73192. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73193. * It might on the other hand introduce peter panning.
  73194. */
  73195. this.forceBackFacesOnly = false;
  73196. this._lightDirection = BABYLON.Vector3.Zero();
  73197. this._viewMatrix = BABYLON.Matrix.Zero();
  73198. this._projectionMatrix = BABYLON.Matrix.Zero();
  73199. this._transformMatrix = BABYLON.Matrix.Zero();
  73200. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73201. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73202. this._currentFaceIndex = 0;
  73203. this._currentFaceIndexCache = 0;
  73204. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73205. this._mapSize = mapSize;
  73206. this._light = light;
  73207. this._scene = light.getScene();
  73208. light._shadowGenerator = this;
  73209. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73210. if (!component) {
  73211. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73212. this._scene._addComponent(component);
  73213. }
  73214. // Texture type fallback from float to int if not supported.
  73215. var caps = this._scene.getEngine().getCaps();
  73216. if (!useFullFloatFirst) {
  73217. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73218. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73219. }
  73220. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73221. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73222. }
  73223. else {
  73224. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73225. }
  73226. }
  73227. else {
  73228. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73229. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73230. }
  73231. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73232. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73233. }
  73234. else {
  73235. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73236. }
  73237. }
  73238. this._initializeGenerator();
  73239. this._applyFilterValues();
  73240. }
  73241. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73242. /**
  73243. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73244. */
  73245. get: function () {
  73246. return this._bias;
  73247. },
  73248. /**
  73249. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73250. */
  73251. set: function (bias) {
  73252. this._bias = bias;
  73253. },
  73254. enumerable: true,
  73255. configurable: true
  73256. });
  73257. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73258. /**
  73259. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73260. */
  73261. get: function () {
  73262. return this._normalBias;
  73263. },
  73264. /**
  73265. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73266. */
  73267. set: function (normalBias) {
  73268. this._normalBias = normalBias;
  73269. },
  73270. enumerable: true,
  73271. configurable: true
  73272. });
  73273. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73274. /**
  73275. * Gets the blur box offset: offset applied during the blur pass.
  73276. * Only usefull if useKernelBlur = false
  73277. */
  73278. get: function () {
  73279. return this._blurBoxOffset;
  73280. },
  73281. /**
  73282. * Sets the blur box offset: offset applied during the blur pass.
  73283. * Only usefull if useKernelBlur = false
  73284. */
  73285. set: function (value) {
  73286. if (this._blurBoxOffset === value) {
  73287. return;
  73288. }
  73289. this._blurBoxOffset = value;
  73290. this._disposeBlurPostProcesses();
  73291. },
  73292. enumerable: true,
  73293. configurable: true
  73294. });
  73295. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73296. /**
  73297. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73298. * 2 means half of the size.
  73299. */
  73300. get: function () {
  73301. return this._blurScale;
  73302. },
  73303. /**
  73304. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73305. * 2 means half of the size.
  73306. */
  73307. set: function (value) {
  73308. if (this._blurScale === value) {
  73309. return;
  73310. }
  73311. this._blurScale = value;
  73312. this._disposeBlurPostProcesses();
  73313. },
  73314. enumerable: true,
  73315. configurable: true
  73316. });
  73317. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73318. /**
  73319. * Gets the blur kernel: kernel size of the blur pass.
  73320. * Only usefull if useKernelBlur = true
  73321. */
  73322. get: function () {
  73323. return this._blurKernel;
  73324. },
  73325. /**
  73326. * Sets the blur kernel: kernel size of the blur pass.
  73327. * Only usefull if useKernelBlur = true
  73328. */
  73329. set: function (value) {
  73330. if (this._blurKernel === value) {
  73331. return;
  73332. }
  73333. this._blurKernel = value;
  73334. this._disposeBlurPostProcesses();
  73335. },
  73336. enumerable: true,
  73337. configurable: true
  73338. });
  73339. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73340. /**
  73341. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73342. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73343. */
  73344. get: function () {
  73345. return this._useKernelBlur;
  73346. },
  73347. /**
  73348. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73349. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73350. */
  73351. set: function (value) {
  73352. if (this._useKernelBlur === value) {
  73353. return;
  73354. }
  73355. this._useKernelBlur = value;
  73356. this._disposeBlurPostProcesses();
  73357. },
  73358. enumerable: true,
  73359. configurable: true
  73360. });
  73361. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73362. /**
  73363. * Gets the depth scale used in ESM mode.
  73364. */
  73365. get: function () {
  73366. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73367. },
  73368. /**
  73369. * Sets the depth scale used in ESM mode.
  73370. * This can override the scale stored on the light.
  73371. */
  73372. set: function (value) {
  73373. this._depthScale = value;
  73374. },
  73375. enumerable: true,
  73376. configurable: true
  73377. });
  73378. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73379. /**
  73380. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73381. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73382. */
  73383. get: function () {
  73384. return this._filter;
  73385. },
  73386. /**
  73387. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73388. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73389. */
  73390. set: function (value) {
  73391. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73392. if (this._light.needCube()) {
  73393. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73394. this.useExponentialShadowMap = true;
  73395. return;
  73396. }
  73397. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73398. this.useCloseExponentialShadowMap = true;
  73399. return;
  73400. }
  73401. // PCF on cubemap would also be expensive
  73402. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73403. this.usePoissonSampling = true;
  73404. return;
  73405. }
  73406. }
  73407. // Weblg1 fallback for PCF.
  73408. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73409. if (this._scene.getEngine().webGLVersion === 1) {
  73410. this.usePoissonSampling = true;
  73411. return;
  73412. }
  73413. }
  73414. if (this._filter === value) {
  73415. return;
  73416. }
  73417. this._filter = value;
  73418. this._disposeBlurPostProcesses();
  73419. this._applyFilterValues();
  73420. this._light._markMeshesAsLightDirty();
  73421. },
  73422. enumerable: true,
  73423. configurable: true
  73424. });
  73425. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73426. /**
  73427. * Gets if the current filter is set to Poisson Sampling.
  73428. */
  73429. get: function () {
  73430. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73431. },
  73432. /**
  73433. * Sets the current filter to Poisson Sampling.
  73434. */
  73435. set: function (value) {
  73436. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73437. return;
  73438. }
  73439. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73440. },
  73441. enumerable: true,
  73442. configurable: true
  73443. });
  73444. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73445. /**
  73446. * Gets if the current filter is set to VSM.
  73447. * DEPRECATED. Should use useExponentialShadowMap instead.
  73448. */
  73449. get: function () {
  73450. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73451. return this.useExponentialShadowMap;
  73452. },
  73453. /**
  73454. * Sets the current filter is to VSM.
  73455. * DEPRECATED. Should use useExponentialShadowMap instead.
  73456. */
  73457. set: function (value) {
  73458. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73459. this.useExponentialShadowMap = value;
  73460. },
  73461. enumerable: true,
  73462. configurable: true
  73463. });
  73464. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73465. /**
  73466. * Gets if the current filter is set to blurred VSM.
  73467. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73468. */
  73469. get: function () {
  73470. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73471. return this.useBlurExponentialShadowMap;
  73472. },
  73473. /**
  73474. * Sets the current filter is to blurred VSM.
  73475. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73476. */
  73477. set: function (value) {
  73478. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73479. this.useBlurExponentialShadowMap = value;
  73480. },
  73481. enumerable: true,
  73482. configurable: true
  73483. });
  73484. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73485. /**
  73486. * Gets if the current filter is set to ESM.
  73487. */
  73488. get: function () {
  73489. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73490. },
  73491. /**
  73492. * Sets the current filter is to ESM.
  73493. */
  73494. set: function (value) {
  73495. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  73496. return;
  73497. }
  73498. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73499. },
  73500. enumerable: true,
  73501. configurable: true
  73502. });
  73503. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  73504. /**
  73505. * Gets if the current filter is set to filtered ESM.
  73506. */
  73507. get: function () {
  73508. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  73509. },
  73510. /**
  73511. * Gets if the current filter is set to filtered ESM.
  73512. */
  73513. set: function (value) {
  73514. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73515. return;
  73516. }
  73517. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73518. },
  73519. enumerable: true,
  73520. configurable: true
  73521. });
  73522. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  73523. /**
  73524. * Gets if the current filter is set to "close ESM" (using the inverse of the
  73525. * exponential to prevent steep falloff artifacts).
  73526. */
  73527. get: function () {
  73528. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  73529. },
  73530. /**
  73531. * Sets the current filter to "close ESM" (using the inverse of the
  73532. * exponential to prevent steep falloff artifacts).
  73533. */
  73534. set: function (value) {
  73535. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  73536. return;
  73537. }
  73538. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73539. },
  73540. enumerable: true,
  73541. configurable: true
  73542. });
  73543. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  73544. /**
  73545. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  73546. * exponential to prevent steep falloff artifacts).
  73547. */
  73548. get: function () {
  73549. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  73550. },
  73551. /**
  73552. * Sets the current filter to filtered "close ESM" (using the inverse of the
  73553. * exponential to prevent steep falloff artifacts).
  73554. */
  73555. set: function (value) {
  73556. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73557. return;
  73558. }
  73559. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73560. },
  73561. enumerable: true,
  73562. configurable: true
  73563. });
  73564. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  73565. /**
  73566. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  73567. */
  73568. get: function () {
  73569. return this.filter === ShadowGenerator.FILTER_PCF;
  73570. },
  73571. /**
  73572. * Sets the current filter to "PCF" (percentage closer filtering).
  73573. */
  73574. set: function (value) {
  73575. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  73576. return;
  73577. }
  73578. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  73579. },
  73580. enumerable: true,
  73581. configurable: true
  73582. });
  73583. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  73584. /**
  73585. * Gets the PCF or PCSS Quality.
  73586. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  73587. */
  73588. get: function () {
  73589. return this._filteringQuality;
  73590. },
  73591. /**
  73592. * Sets the PCF or PCSS Quality.
  73593. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  73594. */
  73595. set: function (filteringQuality) {
  73596. this._filteringQuality = filteringQuality;
  73597. },
  73598. enumerable: true,
  73599. configurable: true
  73600. });
  73601. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  73602. /**
  73603. * Gets if the current filter is set to "PCSS" (contact hardening).
  73604. */
  73605. get: function () {
  73606. return this.filter === ShadowGenerator.FILTER_PCSS;
  73607. },
  73608. /**
  73609. * Sets the current filter to "PCSS" (contact hardening).
  73610. */
  73611. set: function (value) {
  73612. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  73613. return;
  73614. }
  73615. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  73616. },
  73617. enumerable: true,
  73618. configurable: true
  73619. });
  73620. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  73621. /**
  73622. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  73623. * Using a ratio helps keeping shape stability independently of the map size.
  73624. *
  73625. * It does not account for the light projection as it was having too much
  73626. * instability during the light setup or during light position changes.
  73627. *
  73628. * Only valid if useContactHardeningShadow is true.
  73629. */
  73630. get: function () {
  73631. return this._contactHardeningLightSizeUVRatio;
  73632. },
  73633. /**
  73634. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  73635. * Using a ratio helps keeping shape stability independently of the map size.
  73636. *
  73637. * It does not account for the light projection as it was having too much
  73638. * instability during the light setup or during light position changes.
  73639. *
  73640. * Only valid if useContactHardeningShadow is true.
  73641. */
  73642. set: function (contactHardeningLightSizeUVRatio) {
  73643. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  73644. },
  73645. enumerable: true,
  73646. configurable: true
  73647. });
  73648. /**
  73649. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  73650. * 0 means strongest and 1 would means no shadow.
  73651. * @returns the darkness.
  73652. */
  73653. ShadowGenerator.prototype.getDarkness = function () {
  73654. return this._darkness;
  73655. };
  73656. /**
  73657. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  73658. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  73659. * @returns the shadow generator allowing fluent coding.
  73660. */
  73661. ShadowGenerator.prototype.setDarkness = function (darkness) {
  73662. if (darkness >= 1.0)
  73663. this._darkness = 1.0;
  73664. else if (darkness <= 0.0)
  73665. this._darkness = 0.0;
  73666. else
  73667. this._darkness = darkness;
  73668. return this;
  73669. };
  73670. /**
  73671. * Sets the ability to have transparent shadow (boolean).
  73672. * @param transparent True if transparent else False
  73673. * @returns the shadow generator allowing fluent coding
  73674. */
  73675. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  73676. this._transparencyShadow = transparent;
  73677. return this;
  73678. };
  73679. /**
  73680. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  73681. * @returns The render target texture if present otherwise, null
  73682. */
  73683. ShadowGenerator.prototype.getShadowMap = function () {
  73684. return this._shadowMap;
  73685. };
  73686. /**
  73687. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  73688. * @returns The render target texture if the shadow map is present otherwise, null
  73689. */
  73690. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  73691. if (this._shadowMap2) {
  73692. return this._shadowMap2;
  73693. }
  73694. return this._shadowMap;
  73695. };
  73696. /**
  73697. * Helper function to add a mesh and its descendants to the list of shadow casters.
  73698. * @param mesh Mesh to add
  73699. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  73700. * @returns the Shadow Generator itself
  73701. */
  73702. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  73703. if (includeDescendants === void 0) { includeDescendants = true; }
  73704. var _a;
  73705. if (!this._shadowMap) {
  73706. return this;
  73707. }
  73708. if (!this._shadowMap.renderList) {
  73709. this._shadowMap.renderList = [];
  73710. }
  73711. this._shadowMap.renderList.push(mesh);
  73712. if (includeDescendants) {
  73713. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  73714. }
  73715. return this;
  73716. };
  73717. /**
  73718. * Helper function to remove a mesh and its descendants from the list of shadow casters
  73719. * @param mesh Mesh to remove
  73720. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  73721. * @returns the Shadow Generator itself
  73722. */
  73723. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  73724. if (includeDescendants === void 0) { includeDescendants = true; }
  73725. if (!this._shadowMap || !this._shadowMap.renderList) {
  73726. return this;
  73727. }
  73728. var index = this._shadowMap.renderList.indexOf(mesh);
  73729. if (index !== -1) {
  73730. this._shadowMap.renderList.splice(index, 1);
  73731. }
  73732. if (includeDescendants) {
  73733. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  73734. var child = _a[_i];
  73735. this.removeShadowCaster(child);
  73736. }
  73737. }
  73738. return this;
  73739. };
  73740. /**
  73741. * Returns the associated light object.
  73742. * @returns the light generating the shadow
  73743. */
  73744. ShadowGenerator.prototype.getLight = function () {
  73745. return this._light;
  73746. };
  73747. ShadowGenerator.prototype._initializeGenerator = function () {
  73748. this._light._markMeshesAsLightDirty();
  73749. this._initializeShadowMap();
  73750. };
  73751. ShadowGenerator.prototype._initializeShadowMap = function () {
  73752. var _this = this;
  73753. // Render target
  73754. var engine = this._scene.getEngine();
  73755. if (engine.webGLVersion > 1) {
  73756. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  73757. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  73758. }
  73759. else {
  73760. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  73761. }
  73762. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73763. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73764. this._shadowMap.anisotropicFilteringLevel = 1;
  73765. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73766. this._shadowMap.renderParticles = false;
  73767. this._shadowMap.ignoreCameraViewport = true;
  73768. // Record Face Index before render.
  73769. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  73770. _this._currentFaceIndex = faceIndex;
  73771. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73772. engine.setColorWrite(false);
  73773. }
  73774. });
  73775. // Custom render function.
  73776. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  73777. // Blur if required afer render.
  73778. this._shadowMap.onAfterUnbindObservable.add(function () {
  73779. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73780. engine.setColorWrite(true);
  73781. }
  73782. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  73783. return;
  73784. }
  73785. var shadowMap = _this.getShadowMapForRendering();
  73786. if (shadowMap) {
  73787. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  73788. }
  73789. });
  73790. // Clear according to the chosen filter.
  73791. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  73792. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  73793. this._shadowMap.onClearObservable.add(function (engine) {
  73794. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73795. engine.clear(clearOne, false, true, false);
  73796. }
  73797. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  73798. engine.clear(clearZero, true, true, false);
  73799. }
  73800. else {
  73801. engine.clear(clearOne, true, true, false);
  73802. }
  73803. });
  73804. };
  73805. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  73806. var _this = this;
  73807. var engine = this._scene.getEngine();
  73808. var targetSize = this._mapSize / this.blurScale;
  73809. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  73810. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  73811. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73812. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73813. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73814. }
  73815. if (this.useKernelBlur) {
  73816. 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);
  73817. this._kernelBlurXPostprocess.width = targetSize;
  73818. this._kernelBlurXPostprocess.height = targetSize;
  73819. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  73820. effect.setTexture("textureSampler", _this._shadowMap);
  73821. });
  73822. 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);
  73823. this._kernelBlurXPostprocess.autoClear = false;
  73824. this._kernelBlurYPostprocess.autoClear = false;
  73825. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73826. this._kernelBlurXPostprocess.packedFloat = true;
  73827. this._kernelBlurYPostprocess.packedFloat = true;
  73828. }
  73829. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  73830. }
  73831. else {
  73832. 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);
  73833. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  73834. effect.setFloat2("screenSize", targetSize, targetSize);
  73835. effect.setTexture("textureSampler", _this._shadowMap);
  73836. });
  73837. this._boxBlurPostprocess.autoClear = false;
  73838. this._blurPostProcesses = [this._boxBlurPostprocess];
  73839. }
  73840. };
  73841. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73842. var index;
  73843. var engine = this._scene.getEngine();
  73844. if (depthOnlySubMeshes.length) {
  73845. engine.setColorWrite(false);
  73846. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73847. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  73848. }
  73849. engine.setColorWrite(true);
  73850. }
  73851. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73852. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  73853. }
  73854. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73855. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  73856. }
  73857. if (this._transparencyShadow) {
  73858. for (index = 0; index < transparentSubMeshes.length; index++) {
  73859. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  73860. }
  73861. }
  73862. };
  73863. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  73864. var _this = this;
  73865. var mesh = subMesh.getRenderingMesh();
  73866. var scene = this._scene;
  73867. var engine = scene.getEngine();
  73868. var material = subMesh.getMaterial();
  73869. if (!material) {
  73870. return;
  73871. }
  73872. // Culling
  73873. engine.setState(material.backFaceCulling);
  73874. // Managing instances
  73875. var batch = mesh._getInstancesRenderList(subMesh._id);
  73876. if (batch.mustReturn) {
  73877. return;
  73878. }
  73879. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73880. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  73881. engine.enableEffect(this._effect);
  73882. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73883. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  73884. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  73885. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73886. this._effect.setVector3("lightData", this._cachedDirection);
  73887. }
  73888. else {
  73889. this._effect.setVector3("lightData", this._cachedPosition);
  73890. }
  73891. if (scene.activeCamera) {
  73892. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  73893. }
  73894. // Alpha test
  73895. if (material && material.needAlphaTesting()) {
  73896. var alphaTexture = material.getAlphaTestTexture();
  73897. if (alphaTexture) {
  73898. this._effect.setTexture("diffuseSampler", alphaTexture);
  73899. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  73900. }
  73901. }
  73902. // Bones
  73903. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73904. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  73905. }
  73906. // Morph targets
  73907. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  73908. if (this.forceBackFacesOnly) {
  73909. engine.setState(true, 0, false, true);
  73910. }
  73911. // Draw
  73912. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73913. if (this.forceBackFacesOnly) {
  73914. engine.setState(true, 0, false, false);
  73915. }
  73916. }
  73917. else {
  73918. // Need to reset refresh rate of the shadowMap
  73919. if (this._shadowMap) {
  73920. this._shadowMap.resetRefreshCounter();
  73921. }
  73922. }
  73923. };
  73924. ShadowGenerator.prototype._applyFilterValues = function () {
  73925. if (!this._shadowMap) {
  73926. return;
  73927. }
  73928. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  73929. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  73930. }
  73931. else {
  73932. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73933. }
  73934. };
  73935. /**
  73936. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73937. * @param onCompiled Callback triggered at the and of the effects compilation
  73938. * @param options Sets of optional options forcing the compilation with different modes
  73939. */
  73940. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  73941. var _this = this;
  73942. var localOptions = __assign({ useInstances: false }, options);
  73943. var shadowMap = this.getShadowMap();
  73944. if (!shadowMap) {
  73945. if (onCompiled) {
  73946. onCompiled(this);
  73947. }
  73948. return;
  73949. }
  73950. var renderList = shadowMap.renderList;
  73951. if (!renderList) {
  73952. if (onCompiled) {
  73953. onCompiled(this);
  73954. }
  73955. return;
  73956. }
  73957. var subMeshes = new Array();
  73958. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  73959. var mesh = renderList_1[_i];
  73960. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  73961. }
  73962. if (subMeshes.length === 0) {
  73963. if (onCompiled) {
  73964. onCompiled(this);
  73965. }
  73966. return;
  73967. }
  73968. var currentIndex = 0;
  73969. var checkReady = function () {
  73970. if (!_this._scene || !_this._scene.getEngine()) {
  73971. return;
  73972. }
  73973. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73974. currentIndex++;
  73975. if (currentIndex >= subMeshes.length) {
  73976. if (onCompiled) {
  73977. onCompiled(_this);
  73978. }
  73979. return;
  73980. }
  73981. }
  73982. setTimeout(checkReady, 16);
  73983. };
  73984. checkReady();
  73985. };
  73986. /**
  73987. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73988. * @param options Sets of optional options forcing the compilation with different modes
  73989. * @returns A promise that resolves when the compilation completes
  73990. */
  73991. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73992. var _this = this;
  73993. return new Promise(function (resolve) {
  73994. _this.forceCompilation(function () {
  73995. resolve();
  73996. }, options);
  73997. });
  73998. };
  73999. /**
  74000. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  74001. * @param subMesh The submesh we want to render in the shadow map
  74002. * @param useInstances Defines wether will draw in the map using instances
  74003. * @returns true if ready otherwise, false
  74004. */
  74005. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  74006. var defines = [];
  74007. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74008. defines.push("#define FLOAT");
  74009. }
  74010. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74011. defines.push("#define ESM");
  74012. }
  74013. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  74014. defines.push("#define DEPTHTEXTURE");
  74015. }
  74016. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74017. var mesh = subMesh.getMesh();
  74018. var material = subMesh.getMaterial();
  74019. // Normal bias.
  74020. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74021. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74022. defines.push("#define NORMAL");
  74023. if (mesh.nonUniformScaling) {
  74024. defines.push("#define NONUNIFORMSCALING");
  74025. }
  74026. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74027. defines.push("#define DIRECTIONINLIGHTDATA");
  74028. }
  74029. }
  74030. // Alpha test
  74031. if (material && material.needAlphaTesting()) {
  74032. var alphaTexture = material.getAlphaTestTexture();
  74033. if (alphaTexture) {
  74034. defines.push("#define ALPHATEST");
  74035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74036. attribs.push(BABYLON.VertexBuffer.UVKind);
  74037. defines.push("#define UV1");
  74038. }
  74039. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74040. if (alphaTexture.coordinatesIndex === 1) {
  74041. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74042. defines.push("#define UV2");
  74043. }
  74044. }
  74045. }
  74046. }
  74047. // Bones
  74048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74051. if (mesh.numBoneInfluencers > 4) {
  74052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74054. }
  74055. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74056. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74057. }
  74058. else {
  74059. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74060. }
  74061. // Morph targets
  74062. var manager = mesh.morphTargetManager;
  74063. var morphInfluencers = 0;
  74064. if (manager) {
  74065. if (manager.numInfluencers > 0) {
  74066. defines.push("#define MORPHTARGETS");
  74067. morphInfluencers = manager.numInfluencers;
  74068. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74069. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74070. }
  74071. }
  74072. // Instances
  74073. if (useInstances) {
  74074. defines.push("#define INSTANCES");
  74075. attribs.push("world0");
  74076. attribs.push("world1");
  74077. attribs.push("world2");
  74078. attribs.push("world3");
  74079. }
  74080. // Get correct effect
  74081. var join = defines.join("\n");
  74082. if (this._cachedDefines !== join) {
  74083. this._cachedDefines = join;
  74084. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74085. }
  74086. if (!this._effect.isReady()) {
  74087. return false;
  74088. }
  74089. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74090. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74091. this._initializeBlurRTTAndPostProcesses();
  74092. }
  74093. }
  74094. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74095. return false;
  74096. }
  74097. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74098. return false;
  74099. }
  74100. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74101. return false;
  74102. }
  74103. return true;
  74104. };
  74105. /**
  74106. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74107. * @param defines Defines of the material we want to update
  74108. * @param lightIndex Index of the light in the enabled light list of the material
  74109. */
  74110. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74111. var scene = this._scene;
  74112. var light = this._light;
  74113. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74114. return;
  74115. }
  74116. defines["SHADOW" + lightIndex] = true;
  74117. if (this.useContactHardeningShadow) {
  74118. defines["SHADOWPCSS" + lightIndex] = true;
  74119. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74120. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74121. }
  74122. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74123. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74124. }
  74125. // else default to high.
  74126. }
  74127. if (this.usePercentageCloserFiltering) {
  74128. defines["SHADOWPCF" + lightIndex] = true;
  74129. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74130. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74131. }
  74132. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74133. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74134. }
  74135. // else default to high.
  74136. }
  74137. else if (this.usePoissonSampling) {
  74138. defines["SHADOWPOISSON" + lightIndex] = true;
  74139. }
  74140. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74141. defines["SHADOWESM" + lightIndex] = true;
  74142. }
  74143. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74144. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74145. }
  74146. if (light.needCube()) {
  74147. defines["SHADOWCUBE" + lightIndex] = true;
  74148. }
  74149. };
  74150. /**
  74151. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74152. * defined in the generator but impacting the effect).
  74153. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74154. * @param effect The effect we are binfing the information for
  74155. */
  74156. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74157. var light = this._light;
  74158. var scene = this._scene;
  74159. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74160. return;
  74161. }
  74162. var camera = scene.activeCamera;
  74163. if (!camera) {
  74164. return;
  74165. }
  74166. var shadowMap = this.getShadowMap();
  74167. if (!shadowMap) {
  74168. return;
  74169. }
  74170. if (!light.needCube()) {
  74171. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74172. }
  74173. // Only PCF uses depth stencil texture.
  74174. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74175. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74176. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74177. }
  74178. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74179. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74180. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74181. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74182. }
  74183. else {
  74184. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74185. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74186. }
  74187. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74188. };
  74189. /**
  74190. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74191. * (eq to shadow prjection matrix * light transform matrix)
  74192. * @returns The transform matrix used to create the shadow map
  74193. */
  74194. ShadowGenerator.prototype.getTransformMatrix = function () {
  74195. var scene = this._scene;
  74196. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74197. return this._transformMatrix;
  74198. }
  74199. this._currentRenderID = scene.getRenderId();
  74200. this._currentFaceIndexCache = this._currentFaceIndex;
  74201. var lightPosition = this._light.position;
  74202. if (this._light.computeTransformedInformation()) {
  74203. lightPosition = this._light.transformedPosition;
  74204. }
  74205. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74206. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74207. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74208. }
  74209. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74210. this._cachedPosition.copyFrom(lightPosition);
  74211. this._cachedDirection.copyFrom(this._lightDirection);
  74212. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74213. var shadowMap = this.getShadowMap();
  74214. if (shadowMap) {
  74215. var renderList = shadowMap.renderList;
  74216. if (renderList) {
  74217. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74218. }
  74219. }
  74220. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74221. }
  74222. return this._transformMatrix;
  74223. };
  74224. /**
  74225. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74226. * Cube and 2D textures for instance.
  74227. */
  74228. ShadowGenerator.prototype.recreateShadowMap = function () {
  74229. var shadowMap = this._shadowMap;
  74230. if (!shadowMap) {
  74231. return;
  74232. }
  74233. // Track render list.
  74234. var renderList = shadowMap.renderList;
  74235. // Clean up existing data.
  74236. this._disposeRTTandPostProcesses();
  74237. // Reinitializes.
  74238. this._initializeGenerator();
  74239. // Reaffect the filter to ensure a correct fallback if necessary.
  74240. this.filter = this.filter;
  74241. // Reaffect the filter.
  74242. this._applyFilterValues();
  74243. // Reaffect Render List.
  74244. this._shadowMap.renderList = renderList;
  74245. };
  74246. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74247. if (this._shadowMap2) {
  74248. this._shadowMap2.dispose();
  74249. this._shadowMap2 = null;
  74250. }
  74251. if (this._boxBlurPostprocess) {
  74252. this._boxBlurPostprocess.dispose();
  74253. this._boxBlurPostprocess = null;
  74254. }
  74255. if (this._kernelBlurXPostprocess) {
  74256. this._kernelBlurXPostprocess.dispose();
  74257. this._kernelBlurXPostprocess = null;
  74258. }
  74259. if (this._kernelBlurYPostprocess) {
  74260. this._kernelBlurYPostprocess.dispose();
  74261. this._kernelBlurYPostprocess = null;
  74262. }
  74263. this._blurPostProcesses = [];
  74264. };
  74265. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74266. if (this._shadowMap) {
  74267. this._shadowMap.dispose();
  74268. this._shadowMap = null;
  74269. }
  74270. this._disposeBlurPostProcesses();
  74271. };
  74272. /**
  74273. * Disposes the ShadowGenerator.
  74274. * Returns nothing.
  74275. */
  74276. ShadowGenerator.prototype.dispose = function () {
  74277. this._disposeRTTandPostProcesses();
  74278. if (this._light) {
  74279. this._light._shadowGenerator = null;
  74280. this._light._markMeshesAsLightDirty();
  74281. }
  74282. };
  74283. /**
  74284. * Serializes the shadow generator setup to a json object.
  74285. * @returns The serialized JSON object
  74286. */
  74287. ShadowGenerator.prototype.serialize = function () {
  74288. var serializationObject = {};
  74289. var shadowMap = this.getShadowMap();
  74290. if (!shadowMap) {
  74291. return serializationObject;
  74292. }
  74293. serializationObject.lightId = this._light.id;
  74294. serializationObject.mapSize = shadowMap.getRenderSize();
  74295. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74296. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74297. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74298. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74299. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74300. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74301. serializationObject.depthScale = this.depthScale;
  74302. serializationObject.darkness = this.getDarkness();
  74303. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74304. serializationObject.blurKernel = this.blurKernel;
  74305. serializationObject.blurScale = this.blurScale;
  74306. serializationObject.useKernelBlur = this.useKernelBlur;
  74307. serializationObject.transparencyShadow = this._transparencyShadow;
  74308. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74309. serializationObject.bias = this.bias;
  74310. serializationObject.normalBias = this.normalBias;
  74311. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74312. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74313. serializationObject.filteringQuality = this.filteringQuality;
  74314. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74315. serializationObject.renderList = [];
  74316. if (shadowMap.renderList) {
  74317. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74318. var mesh = shadowMap.renderList[meshIndex];
  74319. serializationObject.renderList.push(mesh.id);
  74320. }
  74321. }
  74322. return serializationObject;
  74323. };
  74324. /**
  74325. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74326. * @param parsedShadowGenerator The JSON object to parse
  74327. * @param scene The scene to create the shadow map for
  74328. * @returns The parsed shadow generator
  74329. */
  74330. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74331. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74332. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74333. var shadowMap = shadowGenerator.getShadowMap();
  74334. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74335. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74336. meshes.forEach(function (mesh) {
  74337. if (!shadowMap) {
  74338. return;
  74339. }
  74340. if (!shadowMap.renderList) {
  74341. shadowMap.renderList = [];
  74342. }
  74343. shadowMap.renderList.push(mesh);
  74344. });
  74345. }
  74346. if (parsedShadowGenerator.usePoissonSampling) {
  74347. shadowGenerator.usePoissonSampling = true;
  74348. }
  74349. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74350. shadowGenerator.useExponentialShadowMap = true;
  74351. }
  74352. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74353. shadowGenerator.useBlurExponentialShadowMap = true;
  74354. }
  74355. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74356. shadowGenerator.useCloseExponentialShadowMap = true;
  74357. }
  74358. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74359. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74360. }
  74361. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74362. shadowGenerator.usePercentageCloserFiltering = true;
  74363. }
  74364. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74365. shadowGenerator.useContactHardeningShadow = true;
  74366. }
  74367. if (parsedShadowGenerator.filteringQuality) {
  74368. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74369. }
  74370. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74371. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74372. }
  74373. // Backward compat
  74374. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74375. shadowGenerator.useExponentialShadowMap = true;
  74376. }
  74377. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74378. shadowGenerator.useBlurExponentialShadowMap = true;
  74379. }
  74380. if (parsedShadowGenerator.depthScale) {
  74381. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74382. }
  74383. if (parsedShadowGenerator.blurScale) {
  74384. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74385. }
  74386. if (parsedShadowGenerator.blurBoxOffset) {
  74387. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74388. }
  74389. if (parsedShadowGenerator.useKernelBlur) {
  74390. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74391. }
  74392. if (parsedShadowGenerator.blurKernel) {
  74393. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74394. }
  74395. if (parsedShadowGenerator.bias !== undefined) {
  74396. shadowGenerator.bias = parsedShadowGenerator.bias;
  74397. }
  74398. if (parsedShadowGenerator.normalBias !== undefined) {
  74399. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74400. }
  74401. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74402. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74403. }
  74404. if (parsedShadowGenerator.darkness) {
  74405. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74406. }
  74407. if (parsedShadowGenerator.transparencyShadow) {
  74408. shadowGenerator.setTransparencyShadow(true);
  74409. }
  74410. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74411. return shadowGenerator;
  74412. };
  74413. /**
  74414. * Shadow generator mode None: no filtering applied.
  74415. */
  74416. ShadowGenerator.FILTER_NONE = 0;
  74417. /**
  74418. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74419. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74420. */
  74421. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74422. /**
  74423. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74424. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74425. */
  74426. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74427. /**
  74428. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74429. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74430. */
  74431. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74432. /**
  74433. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74434. * edge artifacts on steep falloff.
  74435. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74436. */
  74437. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74438. /**
  74439. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74440. * edge artifacts on steep falloff.
  74441. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74442. */
  74443. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74444. /**
  74445. * Shadow generator mode PCF: Percentage Closer Filtering
  74446. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74447. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74448. */
  74449. ShadowGenerator.FILTER_PCF = 6;
  74450. /**
  74451. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74452. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74453. * Contact Hardening
  74454. */
  74455. ShadowGenerator.FILTER_PCSS = 7;
  74456. /**
  74457. * Reserved for PCF and PCSS
  74458. * Highest Quality.
  74459. *
  74460. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74461. *
  74462. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74463. */
  74464. ShadowGenerator.QUALITY_HIGH = 0;
  74465. /**
  74466. * Reserved for PCF and PCSS
  74467. * Good tradeoff for quality/perf cross devices
  74468. *
  74469. * Execute PCF on a 3*3 kernel.
  74470. *
  74471. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74472. */
  74473. ShadowGenerator.QUALITY_MEDIUM = 1;
  74474. /**
  74475. * Reserved for PCF and PCSS
  74476. * The lowest quality but the fastest.
  74477. *
  74478. * Execute PCF on a 1*1 kernel.
  74479. *
  74480. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74481. */
  74482. ShadowGenerator.QUALITY_LOW = 2;
  74483. return ShadowGenerator;
  74484. }());
  74485. BABYLON.ShadowGenerator = ShadowGenerator;
  74486. })(BABYLON || (BABYLON = {}));
  74487. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74488. var BABYLON;
  74489. (function (BABYLON) {
  74490. // Adds the parser to the scene parsers.
  74491. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74492. // Shadows
  74493. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  74494. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  74495. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  74496. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  74497. // SG would be available on their associated lights
  74498. }
  74499. }
  74500. });
  74501. /**
  74502. * Defines the shadow generator component responsible to manage any shadow generators
  74503. * in a given scene.
  74504. */
  74505. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  74506. /**
  74507. * Creates a new instance of the component for the given scene
  74508. * @param scene Defines the scene to register the component in
  74509. */
  74510. function ShadowGeneratorSceneComponent(scene) {
  74511. /**
  74512. * The component name helpfull to identify the component in the list of scene components.
  74513. */
  74514. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  74515. this.scene = scene;
  74516. }
  74517. /**
  74518. * Registers the component in a given scene
  74519. */
  74520. ShadowGeneratorSceneComponent.prototype.register = function () {
  74521. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  74522. };
  74523. /**
  74524. * Rebuilds the elements related to this component in case of
  74525. * context lost for instance.
  74526. */
  74527. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  74528. // Nothing To Do Here.
  74529. };
  74530. /**
  74531. * Serializes the component data to the specified json object
  74532. * @param serializationObject The object to serialize to
  74533. */
  74534. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  74535. // Shadows
  74536. serializationObject.shadowGenerators = [];
  74537. var lights = this.scene.lights;
  74538. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  74539. var light = lights_1[_i];
  74540. var shadowGenerator = light.getShadowGenerator();
  74541. if (shadowGenerator) {
  74542. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74543. }
  74544. }
  74545. };
  74546. /**
  74547. * Adds all the element from the container to the scene
  74548. * @param container the container holding the elements
  74549. */
  74550. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  74551. // Nothing To Do Here. (directly attached to a light)
  74552. };
  74553. /**
  74554. * Removes all the elements in the container from the scene
  74555. * @param container contains the elements to remove
  74556. */
  74557. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  74558. // Nothing To Do Here. (directly attached to a light)
  74559. };
  74560. /**
  74561. * Rebuilds the elements related to this component in case of
  74562. * context lost for instance.
  74563. */
  74564. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  74565. // Nothing To Do Here.
  74566. };
  74567. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  74568. // Shadows
  74569. var scene = this.scene;
  74570. if (this.scene.shadowsEnabled) {
  74571. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  74572. var light = scene.lights[lightIndex];
  74573. var shadowGenerator = light.getShadowGenerator();
  74574. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  74575. var shadowMap = (shadowGenerator.getShadowMap());
  74576. if (scene.textures.indexOf(shadowMap) !== -1) {
  74577. renderTargets.push(shadowMap);
  74578. }
  74579. }
  74580. }
  74581. }
  74582. };
  74583. return ShadowGeneratorSceneComponent;
  74584. }());
  74585. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  74586. })(BABYLON || (BABYLON = {}));
  74587. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  74588. var BABYLON;
  74589. (function (BABYLON) {
  74590. var DefaultLoadingScreen = /** @class */ (function () {
  74591. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  74592. if (_loadingText === void 0) { _loadingText = ""; }
  74593. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  74594. var _this = this;
  74595. this._renderingCanvas = _renderingCanvas;
  74596. this._loadingText = _loadingText;
  74597. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  74598. // Resize
  74599. this._resizeLoadingUI = function () {
  74600. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  74601. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  74602. if (!_this._loadingDiv) {
  74603. return;
  74604. }
  74605. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  74606. _this._loadingDiv.style.left = canvasRect.left + "px";
  74607. _this._loadingDiv.style.top = canvasRect.top + "px";
  74608. _this._loadingDiv.style.width = canvasRect.width + "px";
  74609. _this._loadingDiv.style.height = canvasRect.height + "px";
  74610. };
  74611. }
  74612. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  74613. if (this._loadingDiv) {
  74614. // Do not add a loading screen if there is already one
  74615. return;
  74616. }
  74617. this._loadingDiv = document.createElement("div");
  74618. this._loadingDiv.id = "babylonjsLoadingDiv";
  74619. this._loadingDiv.style.opacity = "0";
  74620. this._loadingDiv.style.transition = "opacity 1.5s ease";
  74621. this._loadingDiv.style.pointerEvents = "none";
  74622. // Loading text
  74623. this._loadingTextDiv = document.createElement("div");
  74624. this._loadingTextDiv.style.position = "absolute";
  74625. this._loadingTextDiv.style.left = "0";
  74626. this._loadingTextDiv.style.top = "50%";
  74627. this._loadingTextDiv.style.marginTop = "80px";
  74628. this._loadingTextDiv.style.width = "100%";
  74629. this._loadingTextDiv.style.height = "20px";
  74630. this._loadingTextDiv.style.fontFamily = "Arial";
  74631. this._loadingTextDiv.style.fontSize = "14px";
  74632. this._loadingTextDiv.style.color = "white";
  74633. this._loadingTextDiv.style.textAlign = "center";
  74634. this._loadingTextDiv.innerHTML = "Loading";
  74635. this._loadingDiv.appendChild(this._loadingTextDiv);
  74636. //set the predefined text
  74637. this._loadingTextDiv.innerHTML = this._loadingText;
  74638. // Generating keyframes
  74639. var style = document.createElement('style');
  74640. style.type = 'text/css';
  74641. 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 }";
  74642. style.innerHTML = keyFrames;
  74643. document.getElementsByTagName('head')[0].appendChild(style);
  74644. // Loading img
  74645. var imgBack = new Image();
  74646. 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";
  74647. imgBack.style.position = "absolute";
  74648. imgBack.style.left = "50%";
  74649. imgBack.style.top = "50%";
  74650. imgBack.style.marginLeft = "-60px";
  74651. imgBack.style.marginTop = "-60px";
  74652. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  74653. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  74654. imgBack.style.transformOrigin = "50% 50%";
  74655. imgBack.style.webkitTransformOrigin = "50% 50%";
  74656. this._loadingDiv.appendChild(imgBack);
  74657. this._resizeLoadingUI();
  74658. window.addEventListener("resize", this._resizeLoadingUI);
  74659. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  74660. document.body.appendChild(this._loadingDiv);
  74661. this._loadingDiv.style.opacity = "1";
  74662. };
  74663. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  74664. var _this = this;
  74665. if (!this._loadingDiv) {
  74666. return;
  74667. }
  74668. var onTransitionEnd = function () {
  74669. if (!_this._loadingDiv) {
  74670. return;
  74671. }
  74672. document.body.removeChild(_this._loadingDiv);
  74673. window.removeEventListener("resize", _this._resizeLoadingUI);
  74674. _this._loadingDiv = null;
  74675. };
  74676. this._loadingDiv.style.opacity = "0";
  74677. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  74678. };
  74679. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  74680. set: function (text) {
  74681. this._loadingText = text;
  74682. if (this._loadingTextDiv) {
  74683. this._loadingTextDiv.innerHTML = this._loadingText;
  74684. }
  74685. },
  74686. enumerable: true,
  74687. configurable: true
  74688. });
  74689. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  74690. get: function () {
  74691. return this._loadingDivBackgroundColor;
  74692. },
  74693. set: function (color) {
  74694. this._loadingDivBackgroundColor = color;
  74695. if (!this._loadingDiv) {
  74696. return;
  74697. }
  74698. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  74699. },
  74700. enumerable: true,
  74701. configurable: true
  74702. });
  74703. return DefaultLoadingScreen;
  74704. }());
  74705. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  74706. })(BABYLON || (BABYLON = {}));
  74707. //# sourceMappingURL=babylon.loadingScreen.js.map
  74708. var BABYLON;
  74709. (function (BABYLON) {
  74710. var SceneLoaderProgressEvent = /** @class */ (function () {
  74711. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  74712. this.lengthComputable = lengthComputable;
  74713. this.loaded = loaded;
  74714. this.total = total;
  74715. }
  74716. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  74717. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  74718. };
  74719. return SceneLoaderProgressEvent;
  74720. }());
  74721. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  74722. var SceneLoader = /** @class */ (function () {
  74723. function SceneLoader() {
  74724. }
  74725. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  74726. get: function () {
  74727. return 0;
  74728. },
  74729. enumerable: true,
  74730. configurable: true
  74731. });
  74732. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  74733. get: function () {
  74734. return 1;
  74735. },
  74736. enumerable: true,
  74737. configurable: true
  74738. });
  74739. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  74740. get: function () {
  74741. return 2;
  74742. },
  74743. enumerable: true,
  74744. configurable: true
  74745. });
  74746. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  74747. get: function () {
  74748. return 3;
  74749. },
  74750. enumerable: true,
  74751. configurable: true
  74752. });
  74753. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  74754. get: function () {
  74755. return SceneLoader._ForceFullSceneLoadingForIncremental;
  74756. },
  74757. set: function (value) {
  74758. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  74759. },
  74760. enumerable: true,
  74761. configurable: true
  74762. });
  74763. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  74764. get: function () {
  74765. return SceneLoader._ShowLoadingScreen;
  74766. },
  74767. set: function (value) {
  74768. SceneLoader._ShowLoadingScreen = value;
  74769. },
  74770. enumerable: true,
  74771. configurable: true
  74772. });
  74773. Object.defineProperty(SceneLoader, "loggingLevel", {
  74774. get: function () {
  74775. return SceneLoader._loggingLevel;
  74776. },
  74777. set: function (value) {
  74778. SceneLoader._loggingLevel = value;
  74779. },
  74780. enumerable: true,
  74781. configurable: true
  74782. });
  74783. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  74784. get: function () {
  74785. return SceneLoader._CleanBoneMatrixWeights;
  74786. },
  74787. set: function (value) {
  74788. SceneLoader._CleanBoneMatrixWeights = value;
  74789. },
  74790. enumerable: true,
  74791. configurable: true
  74792. });
  74793. SceneLoader._getDefaultPlugin = function () {
  74794. return SceneLoader._registeredPlugins[".babylon"];
  74795. };
  74796. SceneLoader._getPluginForExtension = function (extension) {
  74797. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  74798. if (registeredPlugin) {
  74799. return registeredPlugin;
  74800. }
  74801. 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");
  74802. return SceneLoader._getDefaultPlugin();
  74803. };
  74804. SceneLoader._getPluginForDirectLoad = function (data) {
  74805. for (var extension in SceneLoader._registeredPlugins) {
  74806. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  74807. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  74808. return SceneLoader._registeredPlugins[extension];
  74809. }
  74810. }
  74811. return SceneLoader._getDefaultPlugin();
  74812. };
  74813. SceneLoader._getPluginForFilename = function (sceneFilename) {
  74814. var queryStringPosition = sceneFilename.indexOf("?");
  74815. if (queryStringPosition !== -1) {
  74816. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  74817. }
  74818. var dotPosition = sceneFilename.lastIndexOf(".");
  74819. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  74820. return SceneLoader._getPluginForExtension(extension);
  74821. };
  74822. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  74823. SceneLoader._getDirectLoad = function (sceneFilename) {
  74824. if (sceneFilename.substr(0, 5) === "data:") {
  74825. return sceneFilename.substr(5);
  74826. }
  74827. return null;
  74828. };
  74829. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  74830. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  74831. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  74832. var plugin;
  74833. if (registeredPlugin.plugin.createPlugin) {
  74834. plugin = registeredPlugin.plugin.createPlugin();
  74835. }
  74836. else {
  74837. plugin = registeredPlugin.plugin;
  74838. }
  74839. var useArrayBuffer = registeredPlugin.isBinary;
  74840. var database;
  74841. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  74842. var dataCallback = function (data, responseURL) {
  74843. if (scene.isDisposed) {
  74844. onError("Scene has been disposed");
  74845. return;
  74846. }
  74847. scene.database = database;
  74848. onSuccess(plugin, data, responseURL);
  74849. };
  74850. var request = null;
  74851. var pluginDisposed = false;
  74852. var onDisposeObservable = plugin.onDisposeObservable;
  74853. if (onDisposeObservable) {
  74854. onDisposeObservable.add(function () {
  74855. pluginDisposed = true;
  74856. if (request) {
  74857. request.abort();
  74858. request = null;
  74859. }
  74860. onDispose();
  74861. });
  74862. }
  74863. var manifestChecked = function () {
  74864. if (pluginDisposed) {
  74865. return;
  74866. }
  74867. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  74868. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  74869. } : undefined, database, useArrayBuffer, function (request, exception) {
  74870. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  74871. });
  74872. };
  74873. if (directLoad) {
  74874. dataCallback(directLoad);
  74875. return plugin;
  74876. }
  74877. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  74878. var engine = scene.getEngine();
  74879. var canUseOfflineSupport = engine.enableOfflineSupport;
  74880. if (canUseOfflineSupport) {
  74881. // Also check for exceptions
  74882. var exceptionFound = false;
  74883. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  74884. var regex = _a[_i];
  74885. if (regex.test(fileInfo.url)) {
  74886. exceptionFound = true;
  74887. break;
  74888. }
  74889. }
  74890. canUseOfflineSupport = !exceptionFound;
  74891. }
  74892. if (canUseOfflineSupport) {
  74893. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  74894. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  74895. }
  74896. else {
  74897. manifestChecked();
  74898. }
  74899. }
  74900. // Loading file from disk via input file or drag'n'drop
  74901. else {
  74902. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  74903. if (file) {
  74904. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  74905. }
  74906. else {
  74907. onError("Unable to find file named " + fileInfo.name);
  74908. }
  74909. }
  74910. return plugin;
  74911. };
  74912. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  74913. var url;
  74914. var name;
  74915. if (!sceneFilename) {
  74916. url = rootUrl;
  74917. name = BABYLON.Tools.GetFilename(rootUrl);
  74918. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  74919. }
  74920. else {
  74921. if (sceneFilename.substr(0, 1) === "/") {
  74922. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  74923. return null;
  74924. }
  74925. url = rootUrl + sceneFilename;
  74926. name = sceneFilename;
  74927. }
  74928. ;
  74929. return {
  74930. url: url,
  74931. rootUrl: rootUrl,
  74932. name: name
  74933. };
  74934. };
  74935. // Public functions
  74936. SceneLoader.GetPluginForExtension = function (extension) {
  74937. return SceneLoader._getPluginForExtension(extension).plugin;
  74938. };
  74939. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  74940. return !!SceneLoader._registeredPlugins[extension];
  74941. };
  74942. SceneLoader.RegisterPlugin = function (plugin) {
  74943. if (typeof plugin.extensions === "string") {
  74944. var extension = plugin.extensions;
  74945. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74946. plugin: plugin,
  74947. isBinary: false
  74948. };
  74949. }
  74950. else {
  74951. var extensions = plugin.extensions;
  74952. Object.keys(extensions).forEach(function (extension) {
  74953. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74954. plugin: plugin,
  74955. isBinary: extensions[extension].isBinary
  74956. };
  74957. });
  74958. }
  74959. };
  74960. /**
  74961. * Import meshes into a scene
  74962. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74963. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74964. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74965. * @param scene the instance of BABYLON.Scene to append to
  74966. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  74967. * @param onProgress a callback with a progress event for each file being loaded
  74968. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74969. * @param pluginExtension the extension used to determine the plugin
  74970. * @returns The loaded plugin
  74971. */
  74972. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74973. if (sceneFilename === void 0) { sceneFilename = ""; }
  74974. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74975. if (onSuccess === void 0) { onSuccess = null; }
  74976. if (onProgress === void 0) { onProgress = null; }
  74977. if (onError === void 0) { onError = null; }
  74978. if (pluginExtension === void 0) { pluginExtension = null; }
  74979. if (!scene) {
  74980. BABYLON.Tools.Error("No scene available to import mesh to");
  74981. return null;
  74982. }
  74983. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74984. if (!fileInfo) {
  74985. return null;
  74986. }
  74987. var loadingToken = {};
  74988. scene._addPendingData(loadingToken);
  74989. var disposeHandler = function () {
  74990. scene._removePendingData(loadingToken);
  74991. };
  74992. var errorHandler = function (message, exception) {
  74993. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74994. if (onError) {
  74995. onError(scene, errorMessage, exception);
  74996. }
  74997. else {
  74998. BABYLON.Tools.Error(errorMessage);
  74999. // should the exception be thrown?
  75000. }
  75001. disposeHandler();
  75002. };
  75003. var progressHandler = onProgress ? function (event) {
  75004. try {
  75005. onProgress(event);
  75006. }
  75007. catch (e) {
  75008. errorHandler("Error in onProgress callback", e);
  75009. }
  75010. } : undefined;
  75011. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  75012. scene.importedMeshesFiles.push(fileInfo.url);
  75013. if (onSuccess) {
  75014. try {
  75015. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  75016. }
  75017. catch (e) {
  75018. errorHandler("Error in onSuccess callback", e);
  75019. }
  75020. }
  75021. scene._removePendingData(loadingToken);
  75022. };
  75023. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75024. if (plugin.rewriteRootURL) {
  75025. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  75026. }
  75027. if (plugin.importMesh) {
  75028. var syncedPlugin = plugin;
  75029. var meshes = new Array();
  75030. var particleSystems = new Array();
  75031. var skeletons = new Array();
  75032. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75033. return;
  75034. }
  75035. scene.loadingPluginName = plugin.name;
  75036. successHandler(meshes, particleSystems, skeletons, []);
  75037. }
  75038. else {
  75039. var asyncedPlugin = plugin;
  75040. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75041. scene.loadingPluginName = plugin.name;
  75042. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75043. }).catch(function (error) {
  75044. errorHandler(error.message, error);
  75045. });
  75046. }
  75047. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75048. };
  75049. /**
  75050. * Import meshes into a scene
  75051. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75052. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75053. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75054. * @param scene the instance of BABYLON.Scene to append to
  75055. * @param onProgress a callback with a progress event for each file being loaded
  75056. * @param pluginExtension the extension used to determine the plugin
  75057. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75058. */
  75059. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75060. if (sceneFilename === void 0) { sceneFilename = ""; }
  75061. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75062. if (onProgress === void 0) { onProgress = null; }
  75063. if (pluginExtension === void 0) { pluginExtension = null; }
  75064. return new Promise(function (resolve, reject) {
  75065. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75066. resolve({
  75067. meshes: meshes,
  75068. particleSystems: particleSystems,
  75069. skeletons: skeletons,
  75070. animationGroups: animationGroups
  75071. });
  75072. }, onProgress, function (scene, message, exception) {
  75073. reject(exception || new Error(message));
  75074. }, pluginExtension);
  75075. });
  75076. };
  75077. /**
  75078. * Load a scene
  75079. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75080. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75081. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75082. * @param onSuccess a callback with the scene when import succeeds
  75083. * @param onProgress a callback with a progress event for each file being loaded
  75084. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75085. * @param pluginExtension the extension used to determine the plugin
  75086. * @returns The loaded plugin
  75087. */
  75088. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75089. if (onSuccess === void 0) { onSuccess = null; }
  75090. if (onProgress === void 0) { onProgress = null; }
  75091. if (onError === void 0) { onError = null; }
  75092. if (pluginExtension === void 0) { pluginExtension = null; }
  75093. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75094. };
  75095. /**
  75096. * Load a scene
  75097. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75098. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75099. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75100. * @param onProgress a callback with a progress event for each file being loaded
  75101. * @param pluginExtension the extension used to determine the plugin
  75102. * @returns The loaded scene
  75103. */
  75104. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75105. if (onProgress === void 0) { onProgress = null; }
  75106. if (pluginExtension === void 0) { pluginExtension = null; }
  75107. return new Promise(function (resolve, reject) {
  75108. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75109. resolve(scene);
  75110. }, onProgress, function (scene, message, exception) {
  75111. reject(exception || new Error(message));
  75112. }, pluginExtension);
  75113. });
  75114. };
  75115. /**
  75116. * Append a scene
  75117. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75118. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75119. * @param scene is the instance of BABYLON.Scene to append to
  75120. * @param onSuccess a callback with the scene when import succeeds
  75121. * @param onProgress a callback with a progress event for each file being loaded
  75122. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75123. * @param pluginExtension the extension used to determine the plugin
  75124. * @returns The loaded plugin
  75125. */
  75126. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75127. if (sceneFilename === void 0) { sceneFilename = ""; }
  75128. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75129. if (onSuccess === void 0) { onSuccess = null; }
  75130. if (onProgress === void 0) { onProgress = null; }
  75131. if (onError === void 0) { onError = null; }
  75132. if (pluginExtension === void 0) { pluginExtension = null; }
  75133. if (!scene) {
  75134. BABYLON.Tools.Error("No scene available to append to");
  75135. return null;
  75136. }
  75137. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75138. if (!fileInfo) {
  75139. return null;
  75140. }
  75141. if (SceneLoader.ShowLoadingScreen) {
  75142. scene.getEngine().displayLoadingUI();
  75143. }
  75144. var loadingToken = {};
  75145. scene._addPendingData(loadingToken);
  75146. var disposeHandler = function () {
  75147. scene._removePendingData(loadingToken);
  75148. scene.getEngine().hideLoadingUI();
  75149. };
  75150. var errorHandler = function (message, exception) {
  75151. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75152. if (onError) {
  75153. onError(scene, errorMessage, exception);
  75154. }
  75155. else {
  75156. BABYLON.Tools.Error(errorMessage);
  75157. // should the exception be thrown?
  75158. }
  75159. disposeHandler();
  75160. };
  75161. var progressHandler = onProgress ? function (event) {
  75162. try {
  75163. onProgress(event);
  75164. }
  75165. catch (e) {
  75166. errorHandler("Error in onProgress callback", e);
  75167. }
  75168. } : undefined;
  75169. var successHandler = function () {
  75170. if (onSuccess) {
  75171. try {
  75172. onSuccess(scene);
  75173. }
  75174. catch (e) {
  75175. errorHandler("Error in onSuccess callback", e);
  75176. }
  75177. }
  75178. scene._removePendingData(loadingToken);
  75179. };
  75180. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75181. if (plugin.load) {
  75182. var syncedPlugin = plugin;
  75183. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75184. return;
  75185. }
  75186. scene.loadingPluginName = plugin.name;
  75187. successHandler();
  75188. }
  75189. else {
  75190. var asyncedPlugin = plugin;
  75191. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75192. scene.loadingPluginName = plugin.name;
  75193. successHandler();
  75194. }).catch(function (error) {
  75195. errorHandler(error.message, error);
  75196. });
  75197. }
  75198. if (SceneLoader.ShowLoadingScreen) {
  75199. scene.executeWhenReady(function () {
  75200. scene.getEngine().hideLoadingUI();
  75201. });
  75202. }
  75203. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75204. };
  75205. /**
  75206. * Append a scene
  75207. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75208. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75209. * @param scene is the instance of BABYLON.Scene to append to
  75210. * @param onProgress a callback with a progress event for each file being loaded
  75211. * @param pluginExtension the extension used to determine the plugin
  75212. * @returns The given scene
  75213. */
  75214. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75215. if (sceneFilename === void 0) { sceneFilename = ""; }
  75216. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75217. if (onProgress === void 0) { onProgress = null; }
  75218. if (pluginExtension === void 0) { pluginExtension = null; }
  75219. return new Promise(function (resolve, reject) {
  75220. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75221. resolve(scene);
  75222. }, onProgress, function (scene, message, exception) {
  75223. reject(exception || new Error(message));
  75224. }, pluginExtension);
  75225. });
  75226. };
  75227. /**
  75228. * Load a scene into an asset container
  75229. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75230. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75231. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75232. * @param onSuccess a callback with the scene when import succeeds
  75233. * @param onProgress a callback with a progress event for each file being loaded
  75234. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75235. * @param pluginExtension the extension used to determine the plugin
  75236. * @returns The loaded plugin
  75237. */
  75238. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75239. if (sceneFilename === void 0) { sceneFilename = ""; }
  75240. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75241. if (onSuccess === void 0) { onSuccess = null; }
  75242. if (onProgress === void 0) { onProgress = null; }
  75243. if (onError === void 0) { onError = null; }
  75244. if (pluginExtension === void 0) { pluginExtension = null; }
  75245. if (!scene) {
  75246. BABYLON.Tools.Error("No scene available to load asset container to");
  75247. return null;
  75248. }
  75249. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75250. if (!fileInfo) {
  75251. return null;
  75252. }
  75253. var loadingToken = {};
  75254. scene._addPendingData(loadingToken);
  75255. var disposeHandler = function () {
  75256. scene._removePendingData(loadingToken);
  75257. };
  75258. var errorHandler = function (message, exception) {
  75259. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75260. if (onError) {
  75261. onError(scene, errorMessage, exception);
  75262. }
  75263. else {
  75264. BABYLON.Tools.Error(errorMessage);
  75265. // should the exception be thrown?
  75266. }
  75267. disposeHandler();
  75268. };
  75269. var progressHandler = onProgress ? function (event) {
  75270. try {
  75271. onProgress(event);
  75272. }
  75273. catch (e) {
  75274. errorHandler("Error in onProgress callback", e);
  75275. }
  75276. } : undefined;
  75277. var successHandler = function (assets) {
  75278. if (onSuccess) {
  75279. try {
  75280. onSuccess(assets);
  75281. }
  75282. catch (e) {
  75283. errorHandler("Error in onSuccess callback", e);
  75284. }
  75285. }
  75286. scene._removePendingData(loadingToken);
  75287. };
  75288. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75289. if (plugin.loadAssetContainer) {
  75290. var syncedPlugin = plugin;
  75291. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75292. if (!assetContainer) {
  75293. return;
  75294. }
  75295. scene.loadingPluginName = plugin.name;
  75296. successHandler(assetContainer);
  75297. }
  75298. else if (plugin.loadAssetContainerAsync) {
  75299. var asyncedPlugin = plugin;
  75300. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75301. scene.loadingPluginName = plugin.name;
  75302. successHandler(assetContainer);
  75303. }).catch(function (error) {
  75304. errorHandler(error.message, error);
  75305. });
  75306. }
  75307. else {
  75308. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75309. }
  75310. if (SceneLoader.ShowLoadingScreen) {
  75311. scene.executeWhenReady(function () {
  75312. scene.getEngine().hideLoadingUI();
  75313. });
  75314. }
  75315. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75316. };
  75317. /**
  75318. * Load a scene into an asset container
  75319. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  75320. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  75321. * @param scene is the instance of BABYLON.Scene to append to
  75322. * @param onProgress a callback with a progress event for each file being loaded
  75323. * @param pluginExtension the extension used to determine the plugin
  75324. * @returns The loaded asset container
  75325. */
  75326. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75327. if (sceneFilename === void 0) { sceneFilename = ""; }
  75328. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75329. if (onProgress === void 0) { onProgress = null; }
  75330. if (pluginExtension === void 0) { pluginExtension = null; }
  75331. return new Promise(function (resolve, reject) {
  75332. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75333. resolve(assetContainer);
  75334. }, onProgress, function (scene, message, exception) {
  75335. reject(exception || new Error(message));
  75336. }, pluginExtension);
  75337. });
  75338. };
  75339. // Flags
  75340. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75341. SceneLoader._ShowLoadingScreen = true;
  75342. SceneLoader._CleanBoneMatrixWeights = false;
  75343. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75344. // Members
  75345. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75346. SceneLoader._registeredPlugins = {};
  75347. return SceneLoader;
  75348. }());
  75349. BABYLON.SceneLoader = SceneLoader;
  75350. ;
  75351. })(BABYLON || (BABYLON = {}));
  75352. //# sourceMappingURL=babylon.sceneLoader.js.map
  75353. var BABYLON;
  75354. (function (BABYLON) {
  75355. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75356. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75357. var parsedMaterial = parsedData.materials[index];
  75358. if (parsedMaterial.id === id) {
  75359. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75360. }
  75361. }
  75362. return null;
  75363. };
  75364. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75365. for (var i in names) {
  75366. if (mesh.name === names[i]) {
  75367. hierarchyIds.push(mesh.id);
  75368. return true;
  75369. }
  75370. }
  75371. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75372. hierarchyIds.push(mesh.id);
  75373. return true;
  75374. }
  75375. return false;
  75376. };
  75377. var logOperation = function (operation, producer) {
  75378. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75379. };
  75380. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75381. if (addToScene === void 0) { addToScene = false; }
  75382. var container = new BABYLON.AssetContainer(scene);
  75383. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75384. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75385. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75386. // and avoid problems with multiple concurrent .babylon loads.
  75387. var log = "importScene has failed JSON parse";
  75388. try {
  75389. var parsedData = JSON.parse(data);
  75390. log = "";
  75391. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75392. var index;
  75393. var cache;
  75394. // Lights
  75395. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75396. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75397. var parsedLight = parsedData.lights[index];
  75398. var light = BABYLON.Light.Parse(parsedLight, scene);
  75399. if (light) {
  75400. container.lights.push(light);
  75401. log += (index === 0 ? "\n\tLights:" : "");
  75402. log += "\n\t\t" + light.toString(fullDetails);
  75403. }
  75404. }
  75405. }
  75406. // Animations
  75407. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75408. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75409. var parsedAnimation = parsedData.animations[index];
  75410. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75411. scene.animations.push(animation);
  75412. container.animations.push(animation);
  75413. log += (index === 0 ? "\n\tAnimations:" : "");
  75414. log += "\n\t\t" + animation.toString(fullDetails);
  75415. }
  75416. }
  75417. // Materials
  75418. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75419. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75420. var parsedMaterial = parsedData.materials[index];
  75421. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75422. container.materials.push(mat);
  75423. log += (index === 0 ? "\n\tMaterials:" : "");
  75424. log += "\n\t\t" + mat.toString(fullDetails);
  75425. }
  75426. }
  75427. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75428. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75429. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75430. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75431. container.multiMaterials.push(mmat);
  75432. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75433. log += "\n\t\t" + mmat.toString(fullDetails);
  75434. }
  75435. }
  75436. // Morph targets
  75437. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75438. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75439. var managerData = _a[_i];
  75440. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75441. }
  75442. }
  75443. // Skeletons
  75444. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75445. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75446. var parsedSkeleton = parsedData.skeletons[index];
  75447. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75448. container.skeletons.push(skeleton);
  75449. log += (index === 0 ? "\n\tSkeletons:" : "");
  75450. log += "\n\t\t" + skeleton.toString(fullDetails);
  75451. }
  75452. }
  75453. // Geometries
  75454. var geometries = parsedData.geometries;
  75455. if (geometries !== undefined && geometries !== null) {
  75456. var addedGeometry = new Array();
  75457. // Boxes
  75458. var boxes = geometries.boxes;
  75459. if (boxes !== undefined && boxes !== null) {
  75460. for (index = 0, cache = boxes.length; index < cache; index++) {
  75461. var parsedBox = boxes[index];
  75462. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75463. }
  75464. }
  75465. // Spheres
  75466. var spheres = geometries.spheres;
  75467. if (spheres !== undefined && spheres !== null) {
  75468. for (index = 0, cache = spheres.length; index < cache; index++) {
  75469. var parsedSphere = spheres[index];
  75470. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75471. }
  75472. }
  75473. // Cylinders
  75474. var cylinders = geometries.cylinders;
  75475. if (cylinders !== undefined && cylinders !== null) {
  75476. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75477. var parsedCylinder = cylinders[index];
  75478. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75479. }
  75480. }
  75481. // Toruses
  75482. var toruses = geometries.toruses;
  75483. if (toruses !== undefined && toruses !== null) {
  75484. for (index = 0, cache = toruses.length; index < cache; index++) {
  75485. var parsedTorus = toruses[index];
  75486. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75487. }
  75488. }
  75489. // Grounds
  75490. var grounds = geometries.grounds;
  75491. if (grounds !== undefined && grounds !== null) {
  75492. for (index = 0, cache = grounds.length; index < cache; index++) {
  75493. var parsedGround = grounds[index];
  75494. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  75495. }
  75496. }
  75497. // Planes
  75498. var planes = geometries.planes;
  75499. if (planes !== undefined && planes !== null) {
  75500. for (index = 0, cache = planes.length; index < cache; index++) {
  75501. var parsedPlane = planes[index];
  75502. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  75503. }
  75504. }
  75505. // TorusKnots
  75506. var torusKnots = geometries.torusKnots;
  75507. if (torusKnots !== undefined && torusKnots !== null) {
  75508. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  75509. var parsedTorusKnot = torusKnots[index];
  75510. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  75511. }
  75512. }
  75513. // VertexData
  75514. var vertexData = geometries.vertexData;
  75515. if (vertexData !== undefined && vertexData !== null) {
  75516. for (index = 0, cache = vertexData.length; index < cache; index++) {
  75517. var parsedVertexData = vertexData[index];
  75518. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  75519. }
  75520. }
  75521. addedGeometry.forEach(function (g) {
  75522. if (g) {
  75523. container.geometries.push(g);
  75524. }
  75525. });
  75526. }
  75527. // Transform nodes
  75528. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  75529. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  75530. var parsedTransformNode = parsedData.transformNodes[index];
  75531. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  75532. container.transformNodes.push(node);
  75533. }
  75534. }
  75535. // Meshes
  75536. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75537. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75538. var parsedMesh = parsedData.meshes[index];
  75539. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75540. container.meshes.push(mesh);
  75541. log += (index === 0 ? "\n\tMeshes:" : "");
  75542. log += "\n\t\t" + mesh.toString(fullDetails);
  75543. }
  75544. }
  75545. // Cameras
  75546. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  75547. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  75548. var parsedCamera = parsedData.cameras[index];
  75549. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  75550. container.cameras.push(camera);
  75551. log += (index === 0 ? "\n\tCameras:" : "");
  75552. log += "\n\t\t" + camera.toString(fullDetails);
  75553. }
  75554. }
  75555. // Animation Groups
  75556. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  75557. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  75558. var parsedAnimationGroup = parsedData.animationGroups[index];
  75559. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  75560. container.animationGroups.push(animationGroup);
  75561. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  75562. log += "\n\t\t" + animationGroup.toString(fullDetails);
  75563. }
  75564. }
  75565. // Browsing all the graph to connect the dots
  75566. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  75567. var camera = scene.cameras[index];
  75568. if (camera._waitingParentId) {
  75569. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  75570. camera._waitingParentId = null;
  75571. }
  75572. }
  75573. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  75574. var light_1 = scene.lights[index];
  75575. if (light_1 && light_1._waitingParentId) {
  75576. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  75577. light_1._waitingParentId = null;
  75578. }
  75579. }
  75580. // Connect parents & children and parse actions
  75581. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  75582. var transformNode = scene.transformNodes[index];
  75583. if (transformNode._waitingParentId) {
  75584. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  75585. transformNode._waitingParentId = null;
  75586. }
  75587. }
  75588. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75589. var mesh = scene.meshes[index];
  75590. if (mesh._waitingParentId) {
  75591. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  75592. mesh._waitingParentId = null;
  75593. }
  75594. }
  75595. // freeze world matrix application
  75596. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75597. var currentMesh = scene.meshes[index];
  75598. if (currentMesh._waitingFreezeWorldMatrix) {
  75599. currentMesh.freezeWorldMatrix();
  75600. currentMesh._waitingFreezeWorldMatrix = null;
  75601. }
  75602. else {
  75603. currentMesh.computeWorldMatrix(true);
  75604. }
  75605. }
  75606. // Lights exclusions / inclusions
  75607. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  75608. var light_2 = scene.lights[index];
  75609. // Excluded check
  75610. if (light_2._excludedMeshesIds.length > 0) {
  75611. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  75612. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  75613. if (excludedMesh) {
  75614. light_2.excludedMeshes.push(excludedMesh);
  75615. }
  75616. }
  75617. light_2._excludedMeshesIds = [];
  75618. }
  75619. // Included check
  75620. if (light_2._includedOnlyMeshesIds.length > 0) {
  75621. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  75622. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  75623. if (includedOnlyMesh) {
  75624. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  75625. }
  75626. }
  75627. light_2._includedOnlyMeshesIds = [];
  75628. }
  75629. }
  75630. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  75631. // Actions (scene) Done last as it can access other objects.
  75632. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75633. var mesh = scene.meshes[index];
  75634. if (mesh._waitingActions) {
  75635. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  75636. mesh._waitingActions = null;
  75637. }
  75638. }
  75639. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  75640. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  75641. }
  75642. if (!addToScene) {
  75643. container.removeAllFromScene();
  75644. }
  75645. }
  75646. catch (err) {
  75647. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  75648. if (onError) {
  75649. onError(msg, err);
  75650. }
  75651. else {
  75652. BABYLON.Tools.Log(msg);
  75653. throw err;
  75654. }
  75655. }
  75656. finally {
  75657. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75658. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75659. }
  75660. }
  75661. return container;
  75662. };
  75663. BABYLON.SceneLoader.RegisterPlugin({
  75664. name: "babylon.js",
  75665. extensions: ".babylon",
  75666. canDirectLoad: function (data) {
  75667. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  75668. return true;
  75669. }
  75670. return false;
  75671. },
  75672. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  75673. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75674. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75675. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75676. // and avoid problems with multiple concurrent .babylon loads.
  75677. var log = "importMesh has failed JSON parse";
  75678. try {
  75679. var parsedData = JSON.parse(data);
  75680. log = "";
  75681. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75682. if (!meshesNames) {
  75683. meshesNames = null;
  75684. }
  75685. else if (!Array.isArray(meshesNames)) {
  75686. meshesNames = [meshesNames];
  75687. }
  75688. var hierarchyIds = new Array();
  75689. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  75690. var loadedSkeletonsIds = [];
  75691. var loadedMaterialsIds = [];
  75692. var index;
  75693. var cache;
  75694. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  75695. var parsedMesh = parsedData.meshes[index];
  75696. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  75697. if (meshesNames !== null) {
  75698. // Remove found mesh name from list.
  75699. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  75700. }
  75701. //Geometry?
  75702. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  75703. //does the file contain geometries?
  75704. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  75705. //find the correct geometry and add it to the scene
  75706. var found = false;
  75707. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  75708. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  75709. return;
  75710. }
  75711. else {
  75712. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  75713. if (parsedGeometryData.id === parsedMesh.geometryId) {
  75714. switch (geometryType) {
  75715. case "boxes":
  75716. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  75717. break;
  75718. case "spheres":
  75719. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  75720. break;
  75721. case "cylinders":
  75722. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  75723. break;
  75724. case "toruses":
  75725. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  75726. break;
  75727. case "grounds":
  75728. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  75729. break;
  75730. case "planes":
  75731. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  75732. break;
  75733. case "torusKnots":
  75734. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  75735. break;
  75736. case "vertexData":
  75737. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  75738. break;
  75739. }
  75740. found = true;
  75741. }
  75742. });
  75743. }
  75744. });
  75745. if (found === false) {
  75746. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  75747. }
  75748. }
  75749. }
  75750. // Material ?
  75751. if (parsedMesh.materialId) {
  75752. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  75753. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75754. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  75755. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  75756. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  75757. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  75758. var subMatId = parsedMultiMaterial.materials[matIndex];
  75759. loadedMaterialsIds.push(subMatId);
  75760. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  75761. if (mat) {
  75762. log += "\n\tMaterial " + mat.toString(fullDetails);
  75763. }
  75764. }
  75765. loadedMaterialsIds.push(parsedMultiMaterial.id);
  75766. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75767. if (mmat) {
  75768. materialFound = true;
  75769. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  75770. }
  75771. break;
  75772. }
  75773. }
  75774. }
  75775. if (materialFound === false) {
  75776. loadedMaterialsIds.push(parsedMesh.materialId);
  75777. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  75778. if (!mat) {
  75779. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  75780. }
  75781. else {
  75782. log += "\n\tMaterial " + mat.toString(fullDetails);
  75783. }
  75784. }
  75785. }
  75786. // Skeleton ?
  75787. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75788. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  75789. if (skeletonAlreadyLoaded === false) {
  75790. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  75791. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  75792. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  75793. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75794. skeletons.push(skeleton);
  75795. loadedSkeletonsIds.push(parsedSkeleton.id);
  75796. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  75797. }
  75798. }
  75799. }
  75800. }
  75801. // Morph targets ?
  75802. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75803. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75804. var managerData = _a[_i];
  75805. BABYLON.MorphTargetManager.Parse(managerData, scene);
  75806. }
  75807. }
  75808. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75809. meshes.push(mesh);
  75810. log += "\n\tMesh " + mesh.toString(fullDetails);
  75811. }
  75812. }
  75813. // Connecting parents
  75814. var currentMesh;
  75815. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75816. currentMesh = scene.meshes[index];
  75817. if (currentMesh._waitingParentId) {
  75818. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  75819. currentMesh._waitingParentId = null;
  75820. }
  75821. }
  75822. // freeze and compute world matrix application
  75823. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75824. currentMesh = scene.meshes[index];
  75825. if (currentMesh._waitingFreezeWorldMatrix) {
  75826. currentMesh.freezeWorldMatrix();
  75827. currentMesh._waitingFreezeWorldMatrix = null;
  75828. }
  75829. else {
  75830. currentMesh.computeWorldMatrix(true);
  75831. }
  75832. }
  75833. }
  75834. // Particles
  75835. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  75836. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  75837. if (parser) {
  75838. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  75839. var parsedParticleSystem = parsedData.particleSystems[index];
  75840. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  75841. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  75842. }
  75843. }
  75844. }
  75845. }
  75846. return true;
  75847. }
  75848. catch (err) {
  75849. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  75850. if (onError) {
  75851. onError(msg, err);
  75852. }
  75853. else {
  75854. BABYLON.Tools.Log(msg);
  75855. throw err;
  75856. }
  75857. }
  75858. finally {
  75859. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75860. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75861. }
  75862. }
  75863. return false;
  75864. },
  75865. load: function (scene, data, rootUrl, onError) {
  75866. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75867. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75868. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75869. // and avoid problems with multiple concurrent .babylon loads.
  75870. var log = "importScene has failed JSON parse";
  75871. try {
  75872. var parsedData = JSON.parse(data);
  75873. log = "";
  75874. // Scene
  75875. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  75876. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  75877. }
  75878. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  75879. scene.autoClear = parsedData.autoClear;
  75880. }
  75881. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  75882. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  75883. }
  75884. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  75885. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  75886. }
  75887. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  75888. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  75889. }
  75890. // Fog
  75891. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  75892. scene.fogMode = parsedData.fogMode;
  75893. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  75894. scene.fogStart = parsedData.fogStart;
  75895. scene.fogEnd = parsedData.fogEnd;
  75896. scene.fogDensity = parsedData.fogDensity;
  75897. log += "\tFog mode for scene: ";
  75898. switch (scene.fogMode) {
  75899. // getters not compiling, so using hardcoded
  75900. case 1:
  75901. log += "exp\n";
  75902. break;
  75903. case 2:
  75904. log += "exp2\n";
  75905. break;
  75906. case 3:
  75907. log += "linear\n";
  75908. break;
  75909. }
  75910. }
  75911. //Physics
  75912. if (parsedData.physicsEnabled) {
  75913. var physicsPlugin;
  75914. if (parsedData.physicsEngine === "cannon") {
  75915. physicsPlugin = new BABYLON.CannonJSPlugin();
  75916. }
  75917. else if (parsedData.physicsEngine === "oimo") {
  75918. physicsPlugin = new BABYLON.OimoJSPlugin();
  75919. }
  75920. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  75921. //else - default engine, which is currently oimo
  75922. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  75923. scene.enablePhysics(physicsGravity, physicsPlugin);
  75924. }
  75925. // Metadata
  75926. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  75927. scene.metadata = parsedData.metadata;
  75928. }
  75929. //collisions, if defined. otherwise, default is true
  75930. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  75931. scene.collisionsEnabled = parsedData.collisionsEnabled;
  75932. }
  75933. scene.workerCollisions = !!parsedData.workerCollisions;
  75934. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  75935. if (!container) {
  75936. return false;
  75937. }
  75938. if (parsedData.autoAnimate) {
  75939. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  75940. }
  75941. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  75942. scene.setActiveCameraByID(parsedData.activeCameraID);
  75943. }
  75944. // Environment texture
  75945. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  75946. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  75947. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  75948. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  75949. if (parsedData.environmentTextureRotationY) {
  75950. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  75951. }
  75952. scene.environmentTexture = hdrTexture;
  75953. }
  75954. else {
  75955. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  75956. if (parsedData.environmentTextureRotationY) {
  75957. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  75958. }
  75959. scene.environmentTexture = cubeTexture;
  75960. }
  75961. if (parsedData.createDefaultSkybox === true) {
  75962. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  75963. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  75964. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  75965. }
  75966. }
  75967. // Finish
  75968. return true;
  75969. }
  75970. catch (err) {
  75971. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75972. if (onError) {
  75973. onError(msg, err);
  75974. }
  75975. else {
  75976. BABYLON.Tools.Log(msg);
  75977. throw err;
  75978. }
  75979. }
  75980. finally {
  75981. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75982. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75983. }
  75984. }
  75985. return false;
  75986. },
  75987. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75988. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75989. return container;
  75990. }
  75991. });
  75992. })(BABYLON || (BABYLON = {}));
  75993. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75994. var BABYLON;
  75995. (function (BABYLON) {
  75996. /**
  75997. * Class used to help managing file picking and drag'n'drop
  75998. */
  75999. var FilesInput = /** @class */ (function () {
  76000. /**
  76001. * Creates a new FilesInput
  76002. * @param engine defines the rendering engine
  76003. * @param scene defines the hosting scene
  76004. * @param sceneLoadedCallback callback called when scene is loaded
  76005. * @param progressCallback callback called to track progress
  76006. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  76007. * @param textureLoadingCallback callback called when a texture is loading
  76008. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  76009. * @param onReloadCallback callback called when a reload is requested
  76010. * @param errorCallback callback call if an error occurs
  76011. */
  76012. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  76013. /**
  76014. * Callback called when a file is processed
  76015. */
  76016. this.onProcessFileCallback = function () { return true; };
  76017. this._engine = engine;
  76018. this._currentScene = scene;
  76019. this._sceneLoadedCallback = sceneLoadedCallback;
  76020. this._progressCallback = progressCallback;
  76021. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  76022. this._textureLoadingCallback = textureLoadingCallback;
  76023. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  76024. this._onReloadCallback = onReloadCallback;
  76025. this._errorCallback = errorCallback;
  76026. }
  76027. /**
  76028. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76029. * @param elementToMonitor defines the DOM element to track
  76030. */
  76031. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76032. var _this = this;
  76033. if (elementToMonitor) {
  76034. this._elementToMonitor = elementToMonitor;
  76035. this._dragEnterHandler = function (e) { _this.drag(e); };
  76036. this._dragOverHandler = function (e) { _this.drag(e); };
  76037. this._dropHandler = function (e) { _this.drop(e); };
  76038. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76039. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76040. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76041. }
  76042. };
  76043. /**
  76044. * Release all associated resources
  76045. */
  76046. FilesInput.prototype.dispose = function () {
  76047. if (!this._elementToMonitor) {
  76048. return;
  76049. }
  76050. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76051. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76052. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76053. };
  76054. FilesInput.prototype.renderFunction = function () {
  76055. if (this._additionalRenderLoopLogicCallback) {
  76056. this._additionalRenderLoopLogicCallback();
  76057. }
  76058. if (this._currentScene) {
  76059. if (this._textureLoadingCallback) {
  76060. var remaining = this._currentScene.getWaitingItemsCount();
  76061. if (remaining > 0) {
  76062. this._textureLoadingCallback(remaining);
  76063. }
  76064. }
  76065. this._currentScene.render();
  76066. }
  76067. };
  76068. FilesInput.prototype.drag = function (e) {
  76069. e.stopPropagation();
  76070. e.preventDefault();
  76071. };
  76072. FilesInput.prototype.drop = function (eventDrop) {
  76073. eventDrop.stopPropagation();
  76074. eventDrop.preventDefault();
  76075. this.loadFiles(eventDrop);
  76076. };
  76077. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76078. var _this = this;
  76079. var reader = folder.createReader();
  76080. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76081. reader.readEntries(function (entries) {
  76082. remaining.count += entries.length;
  76083. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76084. var entry = entries_1[_i];
  76085. if (entry.isFile) {
  76086. entry.file(function (file) {
  76087. file.correctName = relativePath + file.name;
  76088. files.push(file);
  76089. if (--remaining.count === 0) {
  76090. callback();
  76091. }
  76092. });
  76093. }
  76094. else if (entry.isDirectory) {
  76095. _this._traverseFolder(entry, files, remaining, callback);
  76096. }
  76097. }
  76098. if (--remaining.count) {
  76099. callback();
  76100. }
  76101. });
  76102. };
  76103. FilesInput.prototype._processFiles = function (files) {
  76104. for (var i = 0; i < files.length; i++) {
  76105. var name = files[i].correctName.toLowerCase();
  76106. var extension = name.split('.').pop();
  76107. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76108. continue;
  76109. }
  76110. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76111. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76112. this._sceneFileToLoad = files[i];
  76113. }
  76114. FilesInput.FilesToLoad[name] = files[i];
  76115. }
  76116. };
  76117. /**
  76118. * Load files from a drop event
  76119. * @param event defines the drop event to use as source
  76120. */
  76121. FilesInput.prototype.loadFiles = function (event) {
  76122. var _this = this;
  76123. // Handling data transfer via drag'n'drop
  76124. if (event && event.dataTransfer && event.dataTransfer.files) {
  76125. this._filesToLoad = event.dataTransfer.files;
  76126. }
  76127. // Handling files from input files
  76128. if (event && event.target && event.target.files) {
  76129. this._filesToLoad = event.target.files;
  76130. }
  76131. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76132. return;
  76133. }
  76134. if (this._startingProcessingFilesCallback) {
  76135. this._startingProcessingFilesCallback(this._filesToLoad);
  76136. }
  76137. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76138. var files_1 = new Array();
  76139. var folders = [];
  76140. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76141. for (var i = 0; i < this._filesToLoad.length; i++) {
  76142. var fileToLoad = this._filesToLoad[i];
  76143. var name_1 = fileToLoad.name.toLowerCase();
  76144. var entry = void 0;
  76145. fileToLoad.correctName = name_1;
  76146. if (items) {
  76147. var item = items[i];
  76148. if (item.getAsEntry) {
  76149. entry = item.getAsEntry();
  76150. }
  76151. else if (item.webkitGetAsEntry) {
  76152. entry = item.webkitGetAsEntry();
  76153. }
  76154. }
  76155. if (!entry) {
  76156. files_1.push(fileToLoad);
  76157. }
  76158. else {
  76159. if (entry.isDirectory) {
  76160. folders.push(entry);
  76161. }
  76162. else {
  76163. files_1.push(fileToLoad);
  76164. }
  76165. }
  76166. }
  76167. if (folders.length === 0) {
  76168. this._processFiles(files_1);
  76169. this._processReload();
  76170. }
  76171. else {
  76172. var remaining = { count: folders.length };
  76173. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76174. var folder = folders_1[_i];
  76175. this._traverseFolder(folder, files_1, remaining, function () {
  76176. _this._processFiles(files_1);
  76177. if (remaining.count === 0) {
  76178. _this._processReload();
  76179. }
  76180. });
  76181. }
  76182. }
  76183. }
  76184. };
  76185. FilesInput.prototype._processReload = function () {
  76186. if (this._onReloadCallback) {
  76187. this._onReloadCallback(this._sceneFileToLoad);
  76188. }
  76189. else {
  76190. this.reload();
  76191. }
  76192. };
  76193. /**
  76194. * Reload the current scene from the loaded files
  76195. */
  76196. FilesInput.prototype.reload = function () {
  76197. var _this = this;
  76198. // If a scene file has been provided
  76199. if (this._sceneFileToLoad) {
  76200. if (this._currentScene) {
  76201. if (BABYLON.Tools.errorsCount > 0) {
  76202. BABYLON.Tools.ClearLogCache();
  76203. }
  76204. this._engine.stopRenderLoop();
  76205. }
  76206. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76207. if (_this._progressCallback) {
  76208. _this._progressCallback(progress);
  76209. }
  76210. }).then(function (scene) {
  76211. if (_this._currentScene) {
  76212. _this._currentScene.dispose();
  76213. }
  76214. _this._currentScene = scene;
  76215. if (_this._sceneLoadedCallback) {
  76216. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76217. }
  76218. // Wait for textures and shaders to be ready
  76219. _this._currentScene.executeWhenReady(function () {
  76220. _this._engine.runRenderLoop(function () {
  76221. _this.renderFunction();
  76222. });
  76223. });
  76224. }).catch(function (error) {
  76225. if (_this._errorCallback) {
  76226. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76227. }
  76228. });
  76229. }
  76230. else {
  76231. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76232. }
  76233. };
  76234. /**
  76235. * List of files ready to be loaded
  76236. */
  76237. FilesInput.FilesToLoad = {};
  76238. return FilesInput;
  76239. }());
  76240. BABYLON.FilesInput = FilesInput;
  76241. })(BABYLON || (BABYLON = {}));
  76242. //# sourceMappingURL=babylon.filesInput.js.map
  76243. var BABYLON;
  76244. (function (BABYLON) {
  76245. /**
  76246. * Class used to store custom tags
  76247. */
  76248. var Tags = /** @class */ (function () {
  76249. function Tags() {
  76250. }
  76251. /**
  76252. * Adds support for tags on the given object
  76253. * @param obj defines the object to use
  76254. */
  76255. Tags.EnableFor = function (obj) {
  76256. obj._tags = obj._tags || {};
  76257. obj.hasTags = function () {
  76258. return Tags.HasTags(obj);
  76259. };
  76260. obj.addTags = function (tagsString) {
  76261. return Tags.AddTagsTo(obj, tagsString);
  76262. };
  76263. obj.removeTags = function (tagsString) {
  76264. return Tags.RemoveTagsFrom(obj, tagsString);
  76265. };
  76266. obj.matchesTagsQuery = function (tagsQuery) {
  76267. return Tags.MatchesQuery(obj, tagsQuery);
  76268. };
  76269. };
  76270. /**
  76271. * Removes tags support
  76272. * @param obj defines the object to use
  76273. */
  76274. Tags.DisableFor = function (obj) {
  76275. delete obj._tags;
  76276. delete obj.hasTags;
  76277. delete obj.addTags;
  76278. delete obj.removeTags;
  76279. delete obj.matchesTagsQuery;
  76280. };
  76281. /**
  76282. * Gets a boolean indicating if the given object has tags
  76283. * @param obj defines the object to use
  76284. * @returns a boolean
  76285. */
  76286. Tags.HasTags = function (obj) {
  76287. if (!obj._tags) {
  76288. return false;
  76289. }
  76290. return !BABYLON.Tools.IsEmpty(obj._tags);
  76291. };
  76292. /**
  76293. * Gets the tags available on a given object
  76294. * @param obj defines the object to use
  76295. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76296. * @returns the tags
  76297. */
  76298. Tags.GetTags = function (obj, asString) {
  76299. if (asString === void 0) { asString = true; }
  76300. if (!obj._tags) {
  76301. return null;
  76302. }
  76303. if (asString) {
  76304. var tagsArray = [];
  76305. for (var tag in obj._tags) {
  76306. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76307. tagsArray.push(tag);
  76308. }
  76309. }
  76310. return tagsArray.join(" ");
  76311. }
  76312. else {
  76313. return obj._tags;
  76314. }
  76315. };
  76316. /**
  76317. * Adds tags to an object
  76318. * @param obj defines the object to use
  76319. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76320. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76321. */
  76322. Tags.AddTagsTo = function (obj, tagsString) {
  76323. if (!tagsString) {
  76324. return;
  76325. }
  76326. if (typeof tagsString !== "string") {
  76327. return;
  76328. }
  76329. var tags = tagsString.split(" ");
  76330. tags.forEach(function (tag, index, array) {
  76331. Tags._AddTagTo(obj, tag);
  76332. });
  76333. };
  76334. /**
  76335. * @hidden
  76336. */
  76337. Tags._AddTagTo = function (obj, tag) {
  76338. tag = tag.trim();
  76339. if (tag === "" || tag === "true" || tag === "false") {
  76340. return;
  76341. }
  76342. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76343. return;
  76344. }
  76345. Tags.EnableFor(obj);
  76346. obj._tags[tag] = true;
  76347. };
  76348. /**
  76349. * Removes specific tags from a specific object
  76350. * @param obj defines the object to use
  76351. * @param tagsString defines the tags to remove
  76352. */
  76353. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76354. if (!Tags.HasTags(obj)) {
  76355. return;
  76356. }
  76357. var tags = tagsString.split(" ");
  76358. for (var t in tags) {
  76359. Tags._RemoveTagFrom(obj, tags[t]);
  76360. }
  76361. };
  76362. /**
  76363. * @hidden
  76364. */
  76365. Tags._RemoveTagFrom = function (obj, tag) {
  76366. delete obj._tags[tag];
  76367. };
  76368. /**
  76369. * Defines if tags hosted on an object match a given query
  76370. * @param obj defines the object to use
  76371. * @param tagsQuery defines the tag query
  76372. * @returns a boolean
  76373. */
  76374. Tags.MatchesQuery = function (obj, tagsQuery) {
  76375. if (tagsQuery === undefined) {
  76376. return true;
  76377. }
  76378. if (tagsQuery === "") {
  76379. return Tags.HasTags(obj);
  76380. }
  76381. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76382. };
  76383. return Tags;
  76384. }());
  76385. BABYLON.Tags = Tags;
  76386. })(BABYLON || (BABYLON = {}));
  76387. //# sourceMappingURL=babylon.tags.js.map
  76388. var BABYLON;
  76389. (function (BABYLON) {
  76390. /**
  76391. * Class used to evalaute queries containing `and` and `or` operators
  76392. */
  76393. var AndOrNotEvaluator = /** @class */ (function () {
  76394. function AndOrNotEvaluator() {
  76395. }
  76396. /**
  76397. * Evaluate a query
  76398. * @param query defines the query to evaluate
  76399. * @param evaluateCallback defines the callback used to filter result
  76400. * @returns true if the query matches
  76401. */
  76402. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76403. if (!query.match(/\([^\(\)]*\)/g)) {
  76404. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76405. }
  76406. else {
  76407. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76408. // remove parenthesis
  76409. r = r.slice(1, r.length - 1);
  76410. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76411. });
  76412. }
  76413. if (query === "true") {
  76414. return true;
  76415. }
  76416. if (query === "false") {
  76417. return false;
  76418. }
  76419. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76420. };
  76421. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76422. evaluateCallback = evaluateCallback || (function (r) {
  76423. return r === "true" ? true : false;
  76424. });
  76425. var result;
  76426. var or = parenthesisContent.split("||");
  76427. for (var i in or) {
  76428. if (or.hasOwnProperty(i)) {
  76429. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76430. var and = ori.split("&&");
  76431. if (and.length > 1) {
  76432. for (var j = 0; j < and.length; ++j) {
  76433. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76434. if (andj !== "true" && andj !== "false") {
  76435. if (andj[0] === "!") {
  76436. result = !evaluateCallback(andj.substring(1));
  76437. }
  76438. else {
  76439. result = evaluateCallback(andj);
  76440. }
  76441. }
  76442. else {
  76443. result = andj === "true" ? true : false;
  76444. }
  76445. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76446. ori = "false";
  76447. break;
  76448. }
  76449. }
  76450. }
  76451. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76452. result = true;
  76453. break;
  76454. }
  76455. // result equals false (or undefined)
  76456. if (ori !== "true" && ori !== "false") {
  76457. if (ori[0] === "!") {
  76458. result = !evaluateCallback(ori.substring(1));
  76459. }
  76460. else {
  76461. result = evaluateCallback(ori);
  76462. }
  76463. }
  76464. else {
  76465. result = ori === "true" ? true : false;
  76466. }
  76467. }
  76468. }
  76469. // the whole parenthesis scope is replaced by 'true' or 'false'
  76470. return result ? "true" : "false";
  76471. };
  76472. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76473. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76474. // remove whitespaces
  76475. r = r.replace(/[\s]/g, function () { return ""; });
  76476. return r.length % 2 ? "!" : "";
  76477. });
  76478. booleanString = booleanString.trim();
  76479. if (booleanString === "!true") {
  76480. booleanString = "false";
  76481. }
  76482. else if (booleanString === "!false") {
  76483. booleanString = "true";
  76484. }
  76485. return booleanString;
  76486. };
  76487. return AndOrNotEvaluator;
  76488. }());
  76489. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76490. })(BABYLON || (BABYLON = {}));
  76491. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76492. var BABYLON;
  76493. (function (BABYLON) {
  76494. /**
  76495. * Class used to enable access to IndexedDB
  76496. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  76497. */
  76498. var Database = /** @class */ (function () {
  76499. /**
  76500. * Creates a new Database
  76501. * @param urlToScene defines the url to load the scene
  76502. * @param callbackManifestChecked defines the callback to use when manifest is checked
  76503. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  76504. */
  76505. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  76506. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  76507. var _this = this;
  76508. // Handling various flavors of prefixed version of IndexedDB
  76509. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  76510. this.callbackManifestChecked = callbackManifestChecked;
  76511. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  76512. this.db = null;
  76513. this._enableSceneOffline = false;
  76514. this._enableTexturesOffline = false;
  76515. this.manifestVersionFound = 0;
  76516. this.mustUpdateRessources = false;
  76517. this.hasReachedQuota = false;
  76518. if (!Database.IDBStorageEnabled) {
  76519. this.callbackManifestChecked(true);
  76520. }
  76521. else {
  76522. if (disableManifestCheck) {
  76523. this._enableSceneOffline = true;
  76524. this._enableTexturesOffline = true;
  76525. this.manifestVersionFound = 1;
  76526. BABYLON.Tools.SetImmediate(function () {
  76527. _this.callbackManifestChecked(true);
  76528. });
  76529. }
  76530. else {
  76531. this._checkManifestFile();
  76532. }
  76533. }
  76534. }
  76535. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  76536. /**
  76537. * Gets a boolean indicating if scene must be saved in the database
  76538. */
  76539. get: function () {
  76540. return this._enableSceneOffline;
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  76546. /**
  76547. * Gets a boolean indicating if textures must be saved in the database
  76548. */
  76549. get: function () {
  76550. return this._enableTexturesOffline;
  76551. },
  76552. enumerable: true,
  76553. configurable: true
  76554. });
  76555. Database.prototype._checkManifestFile = function () {
  76556. var _this = this;
  76557. var noManifestFile = function () {
  76558. _this._enableSceneOffline = false;
  76559. _this._enableTexturesOffline = false;
  76560. _this.callbackManifestChecked(false);
  76561. };
  76562. var timeStampUsed = false;
  76563. var manifestURL = this.currentSceneUrl + ".manifest";
  76564. var xhr = new XMLHttpRequest();
  76565. if (navigator.onLine) {
  76566. // Adding a timestamp to by-pass browsers' cache
  76567. timeStampUsed = true;
  76568. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  76569. }
  76570. xhr.open("GET", manifestURL, true);
  76571. xhr.addEventListener("load", function () {
  76572. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76573. try {
  76574. var manifestFile = JSON.parse(xhr.response);
  76575. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  76576. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  76577. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  76578. _this.manifestVersionFound = manifestFile.version;
  76579. }
  76580. if (_this.callbackManifestChecked) {
  76581. _this.callbackManifestChecked(true);
  76582. }
  76583. }
  76584. catch (ex) {
  76585. noManifestFile();
  76586. }
  76587. }
  76588. else {
  76589. noManifestFile();
  76590. }
  76591. }, false);
  76592. xhr.addEventListener("error", function (event) {
  76593. if (timeStampUsed) {
  76594. timeStampUsed = false;
  76595. // Let's retry without the timeStamp
  76596. // It could fail when coupled with HTML5 Offline API
  76597. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  76598. xhr.open("GET", retryManifestURL, true);
  76599. xhr.send();
  76600. }
  76601. else {
  76602. noManifestFile();
  76603. }
  76604. }, false);
  76605. try {
  76606. xhr.send();
  76607. }
  76608. catch (ex) {
  76609. BABYLON.Tools.Error("Error on XHR send request.");
  76610. this.callbackManifestChecked(false);
  76611. }
  76612. };
  76613. /**
  76614. * Open the database and make it available
  76615. * @param successCallback defines the callback to call on success
  76616. * @param errorCallback defines the callback to call on error
  76617. */
  76618. Database.prototype.openAsync = function (successCallback, errorCallback) {
  76619. var _this = this;
  76620. var handleError = function () {
  76621. _this.isSupported = false;
  76622. if (errorCallback)
  76623. errorCallback();
  76624. };
  76625. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  76626. // Your browser doesn't support IndexedDB
  76627. this.isSupported = false;
  76628. if (errorCallback)
  76629. errorCallback();
  76630. }
  76631. else {
  76632. // If the DB hasn't been opened or created yet
  76633. if (!this.db) {
  76634. this.hasReachedQuota = false;
  76635. this.isSupported = true;
  76636. var request = this.idbFactory.open("babylonjs", 1);
  76637. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  76638. request.onerror = function (event) {
  76639. handleError();
  76640. };
  76641. // executes when a version change transaction cannot complete due to other active transactions
  76642. request.onblocked = function (event) {
  76643. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  76644. handleError();
  76645. };
  76646. // DB has been opened successfully
  76647. request.onsuccess = function (event) {
  76648. _this.db = request.result;
  76649. successCallback();
  76650. };
  76651. // Initialization of the DB. Creating Scenes & Textures stores
  76652. request.onupgradeneeded = function (event) {
  76653. _this.db = (event.target).result;
  76654. if (_this.db) {
  76655. try {
  76656. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  76657. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  76658. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  76659. }
  76660. catch (ex) {
  76661. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  76662. handleError();
  76663. }
  76664. }
  76665. };
  76666. }
  76667. // DB has already been created and opened
  76668. else {
  76669. if (successCallback)
  76670. successCallback();
  76671. }
  76672. }
  76673. };
  76674. /**
  76675. * Loads an image from the database
  76676. * @param url defines the url to load from
  76677. * @param image defines the target DOM image
  76678. */
  76679. Database.prototype.loadImageFromDB = function (url, image) {
  76680. var _this = this;
  76681. var completeURL = Database._ReturnFullUrlLocation(url);
  76682. var saveAndLoadImage = function () {
  76683. if (!_this.hasReachedQuota && _this.db !== null) {
  76684. // the texture is not yet in the DB, let's try to save it
  76685. _this._saveImageIntoDBAsync(completeURL, image);
  76686. }
  76687. // If the texture is not in the DB and we've reached the DB quota limit
  76688. // let's load it directly from the web
  76689. else {
  76690. image.src = url;
  76691. }
  76692. };
  76693. if (!this.mustUpdateRessources) {
  76694. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  76695. }
  76696. // First time we're download the images or update requested in the manifest file by a version change
  76697. else {
  76698. saveAndLoadImage();
  76699. }
  76700. };
  76701. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  76702. if (this.isSupported && this.db !== null) {
  76703. var texture;
  76704. var transaction = this.db.transaction(["textures"]);
  76705. transaction.onabort = function (event) {
  76706. image.src = url;
  76707. };
  76708. transaction.oncomplete = function (event) {
  76709. var blobTextureURL;
  76710. if (texture) {
  76711. var URL = window.URL || window.webkitURL;
  76712. blobTextureURL = URL.createObjectURL(texture.data);
  76713. image.onerror = function () {
  76714. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  76715. image.src = url;
  76716. };
  76717. image.src = blobTextureURL;
  76718. }
  76719. else {
  76720. notInDBCallback();
  76721. }
  76722. };
  76723. var getRequest = transaction.objectStore("textures").get(url);
  76724. getRequest.onsuccess = function (event) {
  76725. texture = (event.target).result;
  76726. };
  76727. getRequest.onerror = function (event) {
  76728. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  76729. image.src = url;
  76730. };
  76731. }
  76732. else {
  76733. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76734. image.src = url;
  76735. }
  76736. };
  76737. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  76738. var _this = this;
  76739. if (this.isSupported) {
  76740. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  76741. var generateBlobUrl = function () {
  76742. var blobTextureURL;
  76743. if (blob) {
  76744. var URL = window.URL || window.webkitURL;
  76745. try {
  76746. blobTextureURL = URL.createObjectURL(blob);
  76747. }
  76748. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  76749. catch (ex) {
  76750. blobTextureURL = URL.createObjectURL(blob);
  76751. }
  76752. }
  76753. if (blobTextureURL) {
  76754. image.src = blobTextureURL;
  76755. }
  76756. };
  76757. if (Database.IsUASupportingBlobStorage) { // Create XHR
  76758. var xhr = new XMLHttpRequest(), blob;
  76759. xhr.open("GET", url, true);
  76760. xhr.responseType = "blob";
  76761. xhr.addEventListener("load", function () {
  76762. if (xhr.status === 200 && _this.db) {
  76763. // Blob as response (XHR2)
  76764. blob = xhr.response;
  76765. var transaction = _this.db.transaction(["textures"], "readwrite");
  76766. // the transaction could abort because of a QuotaExceededError error
  76767. transaction.onabort = function (event) {
  76768. try {
  76769. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76770. var srcElement = (event.srcElement || event.target);
  76771. var error = srcElement.error;
  76772. if (error && error.name === "QuotaExceededError") {
  76773. _this.hasReachedQuota = true;
  76774. }
  76775. }
  76776. catch (ex) { }
  76777. generateBlobUrl();
  76778. };
  76779. transaction.oncomplete = function (event) {
  76780. generateBlobUrl();
  76781. };
  76782. var newTexture = { textureUrl: url, data: blob };
  76783. try {
  76784. // Put the blob into the dabase
  76785. var addRequest = transaction.objectStore("textures").put(newTexture);
  76786. addRequest.onsuccess = function (event) {
  76787. };
  76788. addRequest.onerror = function (event) {
  76789. generateBlobUrl();
  76790. };
  76791. }
  76792. catch (ex) {
  76793. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  76794. if (ex.code === 25) {
  76795. Database.IsUASupportingBlobStorage = false;
  76796. }
  76797. image.src = url;
  76798. }
  76799. }
  76800. else {
  76801. image.src = url;
  76802. }
  76803. }, false);
  76804. xhr.addEventListener("error", function (event) {
  76805. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  76806. image.src = url;
  76807. }, false);
  76808. xhr.send();
  76809. }
  76810. else {
  76811. image.src = url;
  76812. }
  76813. }
  76814. else {
  76815. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76816. image.src = url;
  76817. }
  76818. };
  76819. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  76820. var _this = this;
  76821. var updateVersion = function () {
  76822. // the version is not yet in the DB or we need to update it
  76823. _this._saveVersionIntoDBAsync(url, versionLoaded);
  76824. };
  76825. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  76826. };
  76827. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  76828. var _this = this;
  76829. if (this.isSupported && this.db) {
  76830. var version;
  76831. try {
  76832. var transaction = this.db.transaction(["versions"]);
  76833. transaction.oncomplete = function (event) {
  76834. if (version) {
  76835. // If the version in the JSON file is different from the version in DB
  76836. if (_this.manifestVersionFound !== version.data) {
  76837. _this.mustUpdateRessources = true;
  76838. updateInDBCallback();
  76839. }
  76840. else {
  76841. callback(version.data);
  76842. }
  76843. }
  76844. // version was not found in DB
  76845. else {
  76846. _this.mustUpdateRessources = true;
  76847. updateInDBCallback();
  76848. }
  76849. };
  76850. transaction.onabort = function (event) {
  76851. callback(-1);
  76852. };
  76853. var getRequest = transaction.objectStore("versions").get(url);
  76854. getRequest.onsuccess = function (event) {
  76855. version = (event.target).result;
  76856. };
  76857. getRequest.onerror = function (event) {
  76858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  76859. callback(-1);
  76860. };
  76861. }
  76862. catch (ex) {
  76863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  76864. callback(-1);
  76865. }
  76866. }
  76867. else {
  76868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76869. callback(-1);
  76870. }
  76871. };
  76872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  76873. var _this = this;
  76874. if (this.isSupported && !this.hasReachedQuota && this.db) {
  76875. try {
  76876. // Open a transaction to the database
  76877. var transaction = this.db.transaction(["versions"], "readwrite");
  76878. // the transaction could abort because of a QuotaExceededError error
  76879. transaction.onabort = function (event) {
  76880. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76881. var error = event.srcElement['error'];
  76882. if (error && error.name === "QuotaExceededError") {
  76883. _this.hasReachedQuota = true;
  76884. }
  76885. }
  76886. catch (ex) { }
  76887. callback(-1);
  76888. };
  76889. transaction.oncomplete = function (event) {
  76890. callback(_this.manifestVersionFound);
  76891. };
  76892. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  76893. // Put the scene into the database
  76894. var addRequest = transaction.objectStore("versions").put(newVersion);
  76895. addRequest.onsuccess = function (event) {
  76896. };
  76897. addRequest.onerror = function (event) {
  76898. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  76899. };
  76900. }
  76901. catch (ex) {
  76902. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  76903. callback(-1);
  76904. }
  76905. }
  76906. else {
  76907. callback(-1);
  76908. }
  76909. };
  76910. /**
  76911. * Loads a file from database
  76912. * @param url defines the URL to load from
  76913. * @param sceneLoaded defines a callback to call on success
  76914. * @param progressCallBack defines a callback to call when progress changed
  76915. * @param errorCallback defines a callback to call on error
  76916. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  76917. */
  76918. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  76919. var _this = this;
  76920. var completeUrl = Database._ReturnFullUrlLocation(url);
  76921. var saveAndLoadFile = function () {
  76922. // the scene is not yet in the DB, let's try to save it
  76923. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76924. };
  76925. this._checkVersionFromDB(completeUrl, function (version) {
  76926. if (version !== -1) {
  76927. if (!_this.mustUpdateRessources) {
  76928. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  76929. }
  76930. else {
  76931. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76932. }
  76933. }
  76934. else {
  76935. if (errorCallback) {
  76936. errorCallback();
  76937. }
  76938. }
  76939. });
  76940. };
  76941. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  76942. if (this.isSupported && this.db) {
  76943. var targetStore;
  76944. if (url.indexOf(".babylon") !== -1) {
  76945. targetStore = "scenes";
  76946. }
  76947. else {
  76948. targetStore = "textures";
  76949. }
  76950. var file;
  76951. var transaction = this.db.transaction([targetStore]);
  76952. transaction.oncomplete = function (event) {
  76953. if (file) {
  76954. callback(file.data);
  76955. }
  76956. // file was not found in DB
  76957. else {
  76958. notInDBCallback();
  76959. }
  76960. };
  76961. transaction.onabort = function (event) {
  76962. notInDBCallback();
  76963. };
  76964. var getRequest = transaction.objectStore(targetStore).get(url);
  76965. getRequest.onsuccess = function (event) {
  76966. file = (event.target).result;
  76967. };
  76968. getRequest.onerror = function (event) {
  76969. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  76970. notInDBCallback();
  76971. };
  76972. }
  76973. else {
  76974. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76975. callback();
  76976. }
  76977. };
  76978. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  76979. var _this = this;
  76980. if (this.isSupported) {
  76981. var targetStore;
  76982. if (url.indexOf(".babylon") !== -1) {
  76983. targetStore = "scenes";
  76984. }
  76985. else {
  76986. targetStore = "textures";
  76987. }
  76988. // Create XHR
  76989. var xhr = new XMLHttpRequest();
  76990. var fileData;
  76991. xhr.open("GET", url + "?" + Date.now(), true);
  76992. if (useArrayBuffer) {
  76993. xhr.responseType = "arraybuffer";
  76994. }
  76995. if (progressCallback) {
  76996. xhr.onprogress = progressCallback;
  76997. }
  76998. xhr.addEventListener("load", function () {
  76999. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  77000. // Blob as response (XHR2)
  77001. //fileData = xhr.responseText;
  77002. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  77003. if (!_this.hasReachedQuota && _this.db) {
  77004. // Open a transaction to the database
  77005. var transaction = _this.db.transaction([targetStore], "readwrite");
  77006. // the transaction could abort because of a QuotaExceededError error
  77007. transaction.onabort = function (event) {
  77008. try {
  77009. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77010. var error = event.srcElement['error'];
  77011. if (error && error.name === "QuotaExceededError") {
  77012. _this.hasReachedQuota = true;
  77013. }
  77014. }
  77015. catch (ex) { }
  77016. callback(fileData);
  77017. };
  77018. transaction.oncomplete = function (event) {
  77019. callback(fileData);
  77020. };
  77021. var newFile;
  77022. if (targetStore === "scenes") {
  77023. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  77024. }
  77025. else {
  77026. newFile = { textureUrl: url, data: fileData };
  77027. }
  77028. try {
  77029. // Put the scene into the database
  77030. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77031. addRequest.onsuccess = function (event) {
  77032. };
  77033. addRequest.onerror = function (event) {
  77034. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77035. };
  77036. }
  77037. catch (ex) {
  77038. callback(fileData);
  77039. }
  77040. }
  77041. else {
  77042. callback(fileData);
  77043. }
  77044. }
  77045. else {
  77046. if (xhr.status >= 400 && errorCallback) {
  77047. errorCallback(xhr);
  77048. }
  77049. else {
  77050. callback();
  77051. }
  77052. }
  77053. }, false);
  77054. xhr.addEventListener("error", function (event) {
  77055. BABYLON.Tools.Error("error on XHR request.");
  77056. callback();
  77057. }, false);
  77058. xhr.send();
  77059. }
  77060. else {
  77061. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77062. callback();
  77063. }
  77064. };
  77065. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77066. Database.IsUASupportingBlobStorage = true;
  77067. /** Gets a boolean indicating if Database storate is enabled */
  77068. Database.IDBStorageEnabled = true;
  77069. Database._ParseURL = function (url) {
  77070. var a = document.createElement('a');
  77071. a.href = url;
  77072. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77073. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77074. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77075. return absLocation;
  77076. };
  77077. Database._ReturnFullUrlLocation = function (url) {
  77078. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77079. return (Database._ParseURL(window.location.href) + url);
  77080. }
  77081. else {
  77082. return url;
  77083. }
  77084. };
  77085. return Database;
  77086. }());
  77087. BABYLON.Database = Database;
  77088. })(BABYLON || (BABYLON = {}));
  77089. //# sourceMappingURL=babylon.database.js.map
  77090. var BABYLON;
  77091. (function (BABYLON) {
  77092. /**
  77093. * This represents all the required information to add a fresnel effect on a material:
  77094. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77095. */
  77096. var FresnelParameters = /** @class */ (function () {
  77097. function FresnelParameters() {
  77098. this._isEnabled = true;
  77099. /**
  77100. * Define the color used on edges (grazing angle)
  77101. */
  77102. this.leftColor = BABYLON.Color3.White();
  77103. /**
  77104. * Define the color used on center
  77105. */
  77106. this.rightColor = BABYLON.Color3.Black();
  77107. /**
  77108. * Define bias applied to computed fresnel term
  77109. */
  77110. this.bias = 0;
  77111. /**
  77112. * Defined the power exponent applied to fresnel term
  77113. */
  77114. this.power = 1;
  77115. }
  77116. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77117. /**
  77118. * Define if the fresnel effect is enable or not.
  77119. */
  77120. get: function () {
  77121. return this._isEnabled;
  77122. },
  77123. set: function (value) {
  77124. if (this._isEnabled === value) {
  77125. return;
  77126. }
  77127. this._isEnabled = value;
  77128. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77129. },
  77130. enumerable: true,
  77131. configurable: true
  77132. });
  77133. /**
  77134. * Clones the current fresnel and its valuues
  77135. * @returns a clone fresnel configuration
  77136. */
  77137. FresnelParameters.prototype.clone = function () {
  77138. var newFresnelParameters = new FresnelParameters();
  77139. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77140. return newFresnelParameters;
  77141. };
  77142. /**
  77143. * Serializes the current fresnel parameters to a JSON representation.
  77144. * @return the JSON serialization
  77145. */
  77146. FresnelParameters.prototype.serialize = function () {
  77147. var serializationObject = {};
  77148. serializationObject.isEnabled = this.isEnabled;
  77149. serializationObject.leftColor = this.leftColor.asArray();
  77150. serializationObject.rightColor = this.rightColor.asArray();
  77151. serializationObject.bias = this.bias;
  77152. serializationObject.power = this.power;
  77153. return serializationObject;
  77154. };
  77155. /**
  77156. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77157. * @param parsedFresnelParameters Define the JSON representation
  77158. * @returns the parsed parameters
  77159. */
  77160. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77161. var fresnelParameters = new FresnelParameters();
  77162. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77163. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77164. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77165. fresnelParameters.bias = parsedFresnelParameters.bias;
  77166. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77167. return fresnelParameters;
  77168. };
  77169. return FresnelParameters;
  77170. }());
  77171. BABYLON.FresnelParameters = FresnelParameters;
  77172. })(BABYLON || (BABYLON = {}));
  77173. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77174. var BABYLON;
  77175. (function (BABYLON) {
  77176. /**
  77177. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77178. * separate meshes. This can be use to improve performances.
  77179. * @see http://doc.babylonjs.com/how_to/multi_materials
  77180. */
  77181. var MultiMaterial = /** @class */ (function (_super) {
  77182. __extends(MultiMaterial, _super);
  77183. /**
  77184. * Instantiates a new Multi Material
  77185. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77186. * separate meshes. This can be use to improve performances.
  77187. * @see http://doc.babylonjs.com/how_to/multi_materials
  77188. * @param name Define the name in the scene
  77189. * @param scene Define the scene the material belongs to
  77190. */
  77191. function MultiMaterial(name, scene) {
  77192. var _this = _super.call(this, name, scene, true) || this;
  77193. scene.multiMaterials.push(_this);
  77194. _this.subMaterials = new Array();
  77195. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77196. return _this;
  77197. }
  77198. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77199. /**
  77200. * Gets or Sets the list of Materials used within the multi material.
  77201. * They need to be ordered according to the submeshes order in the associated mesh
  77202. */
  77203. get: function () {
  77204. return this._subMaterials;
  77205. },
  77206. set: function (value) {
  77207. this._subMaterials = value;
  77208. this._hookArray(value);
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. MultiMaterial.prototype._hookArray = function (array) {
  77214. var _this = this;
  77215. var oldPush = array.push;
  77216. array.push = function () {
  77217. var items = [];
  77218. for (var _i = 0; _i < arguments.length; _i++) {
  77219. items[_i] = arguments[_i];
  77220. }
  77221. var result = oldPush.apply(array, items);
  77222. _this._markAllSubMeshesAsTexturesDirty();
  77223. return result;
  77224. };
  77225. var oldSplice = array.splice;
  77226. array.splice = function (index, deleteCount) {
  77227. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77228. _this._markAllSubMeshesAsTexturesDirty();
  77229. return deleted;
  77230. };
  77231. };
  77232. /**
  77233. * Get one of the submaterial by its index in the submaterials array
  77234. * @param index The index to look the sub material at
  77235. * @returns The Material if the index has been defined
  77236. */
  77237. MultiMaterial.prototype.getSubMaterial = function (index) {
  77238. if (index < 0 || index >= this.subMaterials.length) {
  77239. return this.getScene().defaultMaterial;
  77240. }
  77241. return this.subMaterials[index];
  77242. };
  77243. /**
  77244. * Get the list of active textures for the whole sub materials list.
  77245. * @returns All the textures that will be used during the rendering
  77246. */
  77247. MultiMaterial.prototype.getActiveTextures = function () {
  77248. var _a;
  77249. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77250. if (subMaterial) {
  77251. return subMaterial.getActiveTextures();
  77252. }
  77253. else {
  77254. return [];
  77255. }
  77256. }));
  77257. };
  77258. /**
  77259. * Gets the current class name of the material e.g. "MultiMaterial"
  77260. * Mainly use in serialization.
  77261. * @returns the class name
  77262. */
  77263. MultiMaterial.prototype.getClassName = function () {
  77264. return "MultiMaterial";
  77265. };
  77266. /**
  77267. * Checks if the material is ready to render the requested sub mesh
  77268. * @param mesh Define the mesh the submesh belongs to
  77269. * @param subMesh Define the sub mesh to look readyness for
  77270. * @param useInstances Define whether or not the material is used with instances
  77271. * @returns true if ready, otherwise false
  77272. */
  77273. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77274. for (var index = 0; index < this.subMaterials.length; index++) {
  77275. var subMaterial = this.subMaterials[index];
  77276. if (subMaterial) {
  77277. if (subMaterial.storeEffectOnSubMeshes) {
  77278. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77279. return false;
  77280. }
  77281. continue;
  77282. }
  77283. if (!subMaterial.isReady(mesh)) {
  77284. return false;
  77285. }
  77286. }
  77287. }
  77288. return true;
  77289. };
  77290. /**
  77291. * Clones the current material and its related sub materials
  77292. * @param name Define the name of the newly cloned material
  77293. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77294. * @returns the cloned material
  77295. */
  77296. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77297. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77298. for (var index = 0; index < this.subMaterials.length; index++) {
  77299. var subMaterial = null;
  77300. var current = this.subMaterials[index];
  77301. if (cloneChildren && current) {
  77302. subMaterial = current.clone(name + "-" + current.name);
  77303. }
  77304. else {
  77305. subMaterial = this.subMaterials[index];
  77306. }
  77307. newMultiMaterial.subMaterials.push(subMaterial);
  77308. }
  77309. return newMultiMaterial;
  77310. };
  77311. /**
  77312. * Serializes the materials into a JSON representation.
  77313. * @returns the JSON representation
  77314. */
  77315. MultiMaterial.prototype.serialize = function () {
  77316. var serializationObject = {};
  77317. serializationObject.name = this.name;
  77318. serializationObject.id = this.id;
  77319. if (BABYLON.Tags) {
  77320. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77321. }
  77322. serializationObject.materials = [];
  77323. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77324. var subMat = this.subMaterials[matIndex];
  77325. if (subMat) {
  77326. serializationObject.materials.push(subMat.id);
  77327. }
  77328. else {
  77329. serializationObject.materials.push(null);
  77330. }
  77331. }
  77332. return serializationObject;
  77333. };
  77334. /**
  77335. * Dispose the material and release its associated resources
  77336. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  77337. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  77338. */
  77339. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77340. var scene = this.getScene();
  77341. if (!scene) {
  77342. return;
  77343. }
  77344. var index = scene.multiMaterials.indexOf(this);
  77345. if (index >= 0) {
  77346. scene.multiMaterials.splice(index, 1);
  77347. }
  77348. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77349. };
  77350. return MultiMaterial;
  77351. }(BABYLON.Material));
  77352. BABYLON.MultiMaterial = MultiMaterial;
  77353. })(BABYLON || (BABYLON = {}));
  77354. //# sourceMappingURL=babylon.multiMaterial.js.map
  77355. var BABYLON;
  77356. (function (BABYLON) {
  77357. /**
  77358. * Manage the touch inputs to control the movement of a free camera.
  77359. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77360. */
  77361. var FreeCameraTouchInput = /** @class */ (function () {
  77362. function FreeCameraTouchInput() {
  77363. /**
  77364. * Defines the touch sensibility for rotation.
  77365. * The higher the faster.
  77366. */
  77367. this.touchAngularSensibility = 200000.0;
  77368. /**
  77369. * Defines the touch sensibility for move.
  77370. * The higher the faster.
  77371. */
  77372. this.touchMoveSensibility = 250.0;
  77373. this._offsetX = null;
  77374. this._offsetY = null;
  77375. this._pointerPressed = new Array();
  77376. }
  77377. /**
  77378. * Attach the input controls to a specific dom element to get the input from.
  77379. * @param element Defines the element the controls should be listened from
  77380. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77381. */
  77382. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77383. var _this = this;
  77384. var previousPosition = null;
  77385. if (this._pointerInput === undefined) {
  77386. this._onLostFocus = function (evt) {
  77387. _this._offsetX = null;
  77388. _this._offsetY = null;
  77389. };
  77390. this._pointerInput = function (p, s) {
  77391. var evt = p.event;
  77392. if (evt.pointerType === "mouse") {
  77393. return;
  77394. }
  77395. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77396. if (!noPreventDefault) {
  77397. evt.preventDefault();
  77398. }
  77399. _this._pointerPressed.push(evt.pointerId);
  77400. if (_this._pointerPressed.length !== 1) {
  77401. return;
  77402. }
  77403. previousPosition = {
  77404. x: evt.clientX,
  77405. y: evt.clientY
  77406. };
  77407. }
  77408. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77409. if (!noPreventDefault) {
  77410. evt.preventDefault();
  77411. }
  77412. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77413. if (index === -1) {
  77414. return;
  77415. }
  77416. _this._pointerPressed.splice(index, 1);
  77417. if (index != 0) {
  77418. return;
  77419. }
  77420. previousPosition = null;
  77421. _this._offsetX = null;
  77422. _this._offsetY = null;
  77423. }
  77424. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77425. if (!noPreventDefault) {
  77426. evt.preventDefault();
  77427. }
  77428. if (!previousPosition) {
  77429. return;
  77430. }
  77431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77432. if (index != 0) {
  77433. return;
  77434. }
  77435. _this._offsetX = evt.clientX - previousPosition.x;
  77436. _this._offsetY = -(evt.clientY - previousPosition.y);
  77437. }
  77438. };
  77439. }
  77440. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77441. if (this._onLostFocus) {
  77442. element.addEventListener("blur", this._onLostFocus);
  77443. }
  77444. };
  77445. /**
  77446. * Detach the current controls from the specified dom element.
  77447. * @param element Defines the element to stop listening the inputs from
  77448. */
  77449. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77450. if (this._pointerInput && element) {
  77451. if (this._observer) {
  77452. this.camera.getScene().onPointerObservable.remove(this._observer);
  77453. this._observer = null;
  77454. }
  77455. if (this._onLostFocus) {
  77456. element.removeEventListener("blur", this._onLostFocus);
  77457. this._onLostFocus = null;
  77458. }
  77459. this._pointerPressed = [];
  77460. this._offsetX = null;
  77461. this._offsetY = null;
  77462. }
  77463. };
  77464. /**
  77465. * Update the current camera state depending on the inputs that have been used this frame.
  77466. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77467. */
  77468. FreeCameraTouchInput.prototype.checkInputs = function () {
  77469. if (this._offsetX && this._offsetY) {
  77470. var camera = this.camera;
  77471. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77472. if (this._pointerPressed.length > 1) {
  77473. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77474. }
  77475. else {
  77476. var speed = camera._computeLocalCameraSpeed();
  77477. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77478. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77479. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77480. }
  77481. }
  77482. };
  77483. /**
  77484. * Gets the class name of the current intput.
  77485. * @returns the class name
  77486. */
  77487. FreeCameraTouchInput.prototype.getClassName = function () {
  77488. return "FreeCameraTouchInput";
  77489. };
  77490. /**
  77491. * Get the friendly name associated with the input class.
  77492. * @returns the input friendly name
  77493. */
  77494. FreeCameraTouchInput.prototype.getSimpleName = function () {
  77495. return "touch";
  77496. };
  77497. __decorate([
  77498. BABYLON.serialize()
  77499. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  77500. __decorate([
  77501. BABYLON.serialize()
  77502. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  77503. return FreeCameraTouchInput;
  77504. }());
  77505. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  77506. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  77507. })(BABYLON || (BABYLON = {}));
  77508. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  77509. var BABYLON;
  77510. (function (BABYLON) {
  77511. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  77512. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  77513. });
  77514. /**
  77515. * This represents a FPS type of camera controlled by touch.
  77516. * This is like a universal camera minus the Gamepad controls.
  77517. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77518. */
  77519. var TouchCamera = /** @class */ (function (_super) {
  77520. __extends(TouchCamera, _super);
  77521. /**
  77522. * Instantiates a new touch camera.
  77523. * This represents a FPS type of camera controlled by touch.
  77524. * This is like a universal camera minus the Gamepad controls.
  77525. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77526. * @param name Define the name of the camera in the scene
  77527. * @param position Define the start position of the camera in the scene
  77528. * @param scene Define the scene the camera belongs to
  77529. */
  77530. function TouchCamera(name, position, scene) {
  77531. var _this = _super.call(this, name, position, scene) || this;
  77532. _this.inputs.addTouch();
  77533. _this._setupInputs();
  77534. return _this;
  77535. }
  77536. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  77537. /**
  77538. * Defines the touch sensibility for rotation.
  77539. * The higher the faster.
  77540. */
  77541. get: function () {
  77542. var touch = this.inputs.attached["touch"];
  77543. if (touch)
  77544. return touch.touchAngularSensibility;
  77545. return 0;
  77546. },
  77547. set: function (value) {
  77548. var touch = this.inputs.attached["touch"];
  77549. if (touch)
  77550. touch.touchAngularSensibility = value;
  77551. },
  77552. enumerable: true,
  77553. configurable: true
  77554. });
  77555. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  77556. /**
  77557. * Defines the touch sensibility for move.
  77558. * The higher the faster.
  77559. */
  77560. get: function () {
  77561. var touch = this.inputs.attached["touch"];
  77562. if (touch)
  77563. return touch.touchMoveSensibility;
  77564. return 0;
  77565. },
  77566. set: function (value) {
  77567. var touch = this.inputs.attached["touch"];
  77568. if (touch)
  77569. touch.touchMoveSensibility = value;
  77570. },
  77571. enumerable: true,
  77572. configurable: true
  77573. });
  77574. /**
  77575. * Gets the current object class name.
  77576. * @return the class name
  77577. */
  77578. TouchCamera.prototype.getClassName = function () {
  77579. return "TouchCamera";
  77580. };
  77581. /** @hidden */
  77582. TouchCamera.prototype._setupInputs = function () {
  77583. var mouse = this.inputs.attached["mouse"];
  77584. if (mouse) {
  77585. mouse.touchEnabled = false;
  77586. }
  77587. };
  77588. return TouchCamera;
  77589. }(BABYLON.FreeCamera));
  77590. BABYLON.TouchCamera = TouchCamera;
  77591. })(BABYLON || (BABYLON = {}));
  77592. //# sourceMappingURL=babylon.touchCamera.js.map
  77593. var BABYLON;
  77594. (function (BABYLON) {
  77595. var ProceduralTexture = /** @class */ (function (_super) {
  77596. __extends(ProceduralTexture, _super);
  77597. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  77598. if (fallbackTexture === void 0) { fallbackTexture = null; }
  77599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  77600. if (isCube === void 0) { isCube = false; }
  77601. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  77602. _this.isCube = isCube;
  77603. _this.isEnabled = true;
  77604. _this._currentRefreshId = -1;
  77605. _this._refreshRate = 1;
  77606. /**
  77607. * Event raised when the texture is generated
  77608. */
  77609. _this.onGeneratedObservable = new BABYLON.Observable();
  77610. _this._vertexBuffers = {};
  77611. _this._uniforms = new Array();
  77612. _this._samplers = new Array();
  77613. /** @hidden */
  77614. _this._textures = {};
  77615. _this._floats = {};
  77616. _this._ints = {};
  77617. _this._floatsArrays = {};
  77618. _this._colors3 = {};
  77619. _this._colors4 = {};
  77620. _this._vectors2 = {};
  77621. _this._vectors3 = {};
  77622. _this._matrices = {};
  77623. _this._fallbackTextureUsed = false;
  77624. _this._cachedDefines = "";
  77625. _this._contentUpdateId = -1;
  77626. scene = _this.getScene();
  77627. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  77628. if (!component) {
  77629. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  77630. scene._addComponent(component);
  77631. }
  77632. scene.proceduralTextures.push(_this);
  77633. _this._engine = scene.getEngine();
  77634. _this.name = name;
  77635. _this.isRenderTarget = true;
  77636. _this._size = size;
  77637. _this._generateMipMaps = generateMipMaps;
  77638. _this.setFragment(fragment);
  77639. _this._fallbackTexture = fallbackTexture;
  77640. if (isCube) {
  77641. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  77642. _this.setFloat("face", 0);
  77643. }
  77644. else {
  77645. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  77646. }
  77647. // VBO
  77648. var vertices = [];
  77649. vertices.push(1, 1);
  77650. vertices.push(-1, 1);
  77651. vertices.push(-1, -1);
  77652. vertices.push(1, -1);
  77653. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77654. _this._createIndexBuffer();
  77655. return _this;
  77656. }
  77657. /**
  77658. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  77659. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  77660. */
  77661. ProceduralTexture.prototype.getContent = function () {
  77662. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  77663. return this._contentData;
  77664. }
  77665. this._contentData = this.readPixels(0, 0, this._contentData);
  77666. this._contentUpdateId = this._currentRefreshId;
  77667. return this._contentData;
  77668. };
  77669. ProceduralTexture.prototype._createIndexBuffer = function () {
  77670. var engine = this._engine;
  77671. // Indices
  77672. var indices = [];
  77673. indices.push(0);
  77674. indices.push(1);
  77675. indices.push(2);
  77676. indices.push(0);
  77677. indices.push(2);
  77678. indices.push(3);
  77679. this._indexBuffer = engine.createIndexBuffer(indices);
  77680. };
  77681. /** @hidden */
  77682. ProceduralTexture.prototype._rebuild = function () {
  77683. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77684. if (vb) {
  77685. vb._rebuild();
  77686. }
  77687. this._createIndexBuffer();
  77688. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  77689. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  77690. }
  77691. };
  77692. ProceduralTexture.prototype.reset = function () {
  77693. if (this._effect === undefined) {
  77694. return;
  77695. }
  77696. var engine = this._engine;
  77697. engine._releaseEffect(this._effect);
  77698. };
  77699. ProceduralTexture.prototype._getDefines = function () {
  77700. return "";
  77701. };
  77702. ProceduralTexture.prototype.isReady = function () {
  77703. var _this = this;
  77704. var engine = this._engine;
  77705. var shaders;
  77706. if (!this._fragment) {
  77707. return false;
  77708. }
  77709. if (this._fallbackTextureUsed) {
  77710. return true;
  77711. }
  77712. var defines = this._getDefines();
  77713. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  77714. return true;
  77715. }
  77716. if (this._fragment.fragmentElement !== undefined) {
  77717. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  77718. }
  77719. else {
  77720. shaders = { vertex: "procedural", fragment: this._fragment };
  77721. }
  77722. this._cachedDefines = defines;
  77723. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  77724. _this.releaseInternalTexture();
  77725. if (_this._fallbackTexture) {
  77726. _this._texture = _this._fallbackTexture._texture;
  77727. if (_this._texture) {
  77728. _this._texture.incrementReferences();
  77729. }
  77730. }
  77731. _this._fallbackTextureUsed = true;
  77732. });
  77733. return this._effect.isReady();
  77734. };
  77735. ProceduralTexture.prototype.resetRefreshCounter = function () {
  77736. this._currentRefreshId = -1;
  77737. };
  77738. ProceduralTexture.prototype.setFragment = function (fragment) {
  77739. this._fragment = fragment;
  77740. };
  77741. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  77742. get: function () {
  77743. return this._refreshRate;
  77744. },
  77745. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  77746. set: function (value) {
  77747. this._refreshRate = value;
  77748. this.resetRefreshCounter();
  77749. },
  77750. enumerable: true,
  77751. configurable: true
  77752. });
  77753. /** @hidden */
  77754. ProceduralTexture.prototype._shouldRender = function () {
  77755. if (!this.isEnabled || !this.isReady() || !this._texture) {
  77756. if (this._texture) {
  77757. this._texture.isReady = false;
  77758. }
  77759. return false;
  77760. }
  77761. if (this._fallbackTextureUsed) {
  77762. return false;
  77763. }
  77764. if (this._currentRefreshId === -1) { // At least render once
  77765. this._currentRefreshId = 1;
  77766. return true;
  77767. }
  77768. if (this.refreshRate === this._currentRefreshId) {
  77769. this._currentRefreshId = 1;
  77770. return true;
  77771. }
  77772. this._currentRefreshId++;
  77773. return false;
  77774. };
  77775. ProceduralTexture.prototype.getRenderSize = function () {
  77776. return this._size;
  77777. };
  77778. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  77779. if (this._fallbackTextureUsed) {
  77780. return;
  77781. }
  77782. this.releaseInternalTexture();
  77783. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  77784. // Update properties
  77785. this._size = size;
  77786. this._generateMipMaps = generateMipMaps;
  77787. };
  77788. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  77789. if (this._uniforms.indexOf(uniformName) === -1) {
  77790. this._uniforms.push(uniformName);
  77791. }
  77792. };
  77793. ProceduralTexture.prototype.setTexture = function (name, texture) {
  77794. if (this._samplers.indexOf(name) === -1) {
  77795. this._samplers.push(name);
  77796. }
  77797. this._textures[name] = texture;
  77798. return this;
  77799. };
  77800. ProceduralTexture.prototype.setFloat = function (name, value) {
  77801. this._checkUniform(name);
  77802. this._floats[name] = value;
  77803. return this;
  77804. };
  77805. /**
  77806. * Set the value of an uniform to an integer value
  77807. * @param name defines the name of the uniform
  77808. * @param value defines the value to set
  77809. * @returns the current procedural texture
  77810. */
  77811. ProceduralTexture.prototype.setInt = function (name, value) {
  77812. this._checkUniform(name);
  77813. this._ints[name] = value;
  77814. return this;
  77815. };
  77816. ProceduralTexture.prototype.setFloats = function (name, value) {
  77817. this._checkUniform(name);
  77818. this._floatsArrays[name] = value;
  77819. return this;
  77820. };
  77821. ProceduralTexture.prototype.setColor3 = function (name, value) {
  77822. this._checkUniform(name);
  77823. this._colors3[name] = value;
  77824. return this;
  77825. };
  77826. ProceduralTexture.prototype.setColor4 = function (name, value) {
  77827. this._checkUniform(name);
  77828. this._colors4[name] = value;
  77829. return this;
  77830. };
  77831. ProceduralTexture.prototype.setVector2 = function (name, value) {
  77832. this._checkUniform(name);
  77833. this._vectors2[name] = value;
  77834. return this;
  77835. };
  77836. ProceduralTexture.prototype.setVector3 = function (name, value) {
  77837. this._checkUniform(name);
  77838. this._vectors3[name] = value;
  77839. return this;
  77840. };
  77841. ProceduralTexture.prototype.setMatrix = function (name, value) {
  77842. this._checkUniform(name);
  77843. this._matrices[name] = value;
  77844. return this;
  77845. };
  77846. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77847. var scene = this.getScene();
  77848. if (!scene) {
  77849. return;
  77850. }
  77851. var engine = this._engine;
  77852. // Render
  77853. engine.enableEffect(this._effect);
  77854. engine.setState(false);
  77855. // Texture
  77856. for (var name in this._textures) {
  77857. this._effect.setTexture(name, this._textures[name]);
  77858. }
  77859. // Float
  77860. for (name in this._ints) {
  77861. this._effect.setInt(name, this._ints[name]);
  77862. }
  77863. // Float
  77864. for (name in this._floats) {
  77865. this._effect.setFloat(name, this._floats[name]);
  77866. }
  77867. // Floats
  77868. for (name in this._floatsArrays) {
  77869. this._effect.setArray(name, this._floatsArrays[name]);
  77870. }
  77871. // Color3
  77872. for (name in this._colors3) {
  77873. this._effect.setColor3(name, this._colors3[name]);
  77874. }
  77875. // Color4
  77876. for (name in this._colors4) {
  77877. var color = this._colors4[name];
  77878. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  77879. }
  77880. // Vector2
  77881. for (name in this._vectors2) {
  77882. this._effect.setVector2(name, this._vectors2[name]);
  77883. }
  77884. // Vector3
  77885. for (name in this._vectors3) {
  77886. this._effect.setVector3(name, this._vectors3[name]);
  77887. }
  77888. // Matrix
  77889. for (name in this._matrices) {
  77890. this._effect.setMatrix(name, this._matrices[name]);
  77891. }
  77892. if (!this._texture) {
  77893. return;
  77894. }
  77895. if (this.isCube) {
  77896. for (var face = 0; face < 6; face++) {
  77897. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  77898. // VBOs
  77899. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77900. this._effect.setFloat("face", face);
  77901. // Clear
  77902. engine.clear(scene.clearColor, true, true, true);
  77903. // Draw order
  77904. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77905. // Mipmaps
  77906. if (face === 5) {
  77907. engine.generateMipMapsForCubemap(this._texture);
  77908. }
  77909. }
  77910. }
  77911. else {
  77912. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  77913. // VBOs
  77914. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77915. // Clear
  77916. engine.clear(scene.clearColor, true, true, true);
  77917. // Draw order
  77918. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77919. }
  77920. // Unbind
  77921. engine.unBindFramebuffer(this._texture, this.isCube);
  77922. if (this.onGenerated) {
  77923. this.onGenerated();
  77924. }
  77925. this.onGeneratedObservable.notifyObservers(this);
  77926. };
  77927. ProceduralTexture.prototype.clone = function () {
  77928. var textureSize = this.getSize();
  77929. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  77930. // Base texture
  77931. newTexture.hasAlpha = this.hasAlpha;
  77932. newTexture.level = this.level;
  77933. // RenderTarget Texture
  77934. newTexture.coordinatesMode = this.coordinatesMode;
  77935. return newTexture;
  77936. };
  77937. ProceduralTexture.prototype.dispose = function () {
  77938. var scene = this.getScene();
  77939. if (!scene) {
  77940. return;
  77941. }
  77942. var index = scene.proceduralTextures.indexOf(this);
  77943. if (index >= 0) {
  77944. scene.proceduralTextures.splice(index, 1);
  77945. }
  77946. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77947. if (vertexBuffer) {
  77948. vertexBuffer.dispose();
  77949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77950. }
  77951. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  77952. this._indexBuffer = null;
  77953. }
  77954. _super.prototype.dispose.call(this);
  77955. };
  77956. __decorate([
  77957. BABYLON.serialize()
  77958. ], ProceduralTexture.prototype, "_size", void 0);
  77959. __decorate([
  77960. BABYLON.serialize()
  77961. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  77962. __decorate([
  77963. BABYLON.serialize()
  77964. ], ProceduralTexture.prototype, "isEnabled", void 0);
  77965. __decorate([
  77966. BABYLON.serialize()
  77967. ], ProceduralTexture.prototype, "refreshRate", null);
  77968. return ProceduralTexture;
  77969. }(BABYLON.Texture));
  77970. BABYLON.ProceduralTexture = ProceduralTexture;
  77971. })(BABYLON || (BABYLON = {}));
  77972. //# sourceMappingURL=babylon.proceduralTexture.js.map
  77973. var BABYLON;
  77974. (function (BABYLON) {
  77975. /**
  77976. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  77977. * in a given scene.
  77978. */
  77979. var ProceduralTextureSceneComponent = /** @class */ (function () {
  77980. /**
  77981. * Creates a new instance of the component for the given scene
  77982. * @param scene Defines the scene to register the component in
  77983. */
  77984. function ProceduralTextureSceneComponent(scene) {
  77985. /**
  77986. * The component name helpfull to identify the component in the list of scene components.
  77987. */
  77988. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  77989. this.scene = scene;
  77990. this.scene.proceduralTextures = new Array();
  77991. scene.layers = new Array();
  77992. }
  77993. /**
  77994. * Registers the component in a given scene
  77995. */
  77996. ProceduralTextureSceneComponent.prototype.register = function () {
  77997. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  77998. };
  77999. /**
  78000. * Rebuilds the elements related to this component in case of
  78001. * context lost for instance.
  78002. */
  78003. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  78004. // Nothing to do here.
  78005. };
  78006. /**
  78007. * Disposes the component and the associated ressources.
  78008. */
  78009. ProceduralTextureSceneComponent.prototype.dispose = function () {
  78010. // Nothing to do here.
  78011. };
  78012. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  78013. if (this.scene.proceduralTexturesEnabled) {
  78014. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78015. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  78016. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  78017. if (proceduralTexture._shouldRender()) {
  78018. proceduralTexture.render();
  78019. }
  78020. }
  78021. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78022. }
  78023. };
  78024. return ProceduralTextureSceneComponent;
  78025. }());
  78026. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78027. })(BABYLON || (BABYLON = {}));
  78028. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78029. var BABYLON;
  78030. (function (BABYLON) {
  78031. var CustomProceduralTexture = /** @class */ (function (_super) {
  78032. __extends(CustomProceduralTexture, _super);
  78033. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78034. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78035. _this._animate = true;
  78036. _this._time = 0;
  78037. _this._texturePath = texturePath;
  78038. //Try to load json
  78039. _this.loadJson(texturePath);
  78040. _this.refreshRate = 1;
  78041. return _this;
  78042. }
  78043. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  78044. var _this = this;
  78045. var noConfigFile = function () {
  78046. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78047. try {
  78048. _this.setFragment(_this._texturePath);
  78049. }
  78050. catch (ex) {
  78051. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78052. }
  78053. };
  78054. var configFileUrl = jsonUrl + "/config.json";
  78055. var xhr = new XMLHttpRequest();
  78056. xhr.open("GET", configFileUrl, true);
  78057. xhr.addEventListener("load", function () {
  78058. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78059. try {
  78060. _this._config = JSON.parse(xhr.response);
  78061. _this.updateShaderUniforms();
  78062. _this.updateTextures();
  78063. _this.setFragment(_this._texturePath + "/custom");
  78064. _this._animate = _this._config.animate;
  78065. _this.refreshRate = _this._config.refreshrate;
  78066. }
  78067. catch (ex) {
  78068. noConfigFile();
  78069. }
  78070. }
  78071. else {
  78072. noConfigFile();
  78073. }
  78074. }, false);
  78075. xhr.addEventListener("error", function () {
  78076. noConfigFile();
  78077. }, false);
  78078. try {
  78079. xhr.send();
  78080. }
  78081. catch (ex) {
  78082. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78083. }
  78084. };
  78085. CustomProceduralTexture.prototype.isReady = function () {
  78086. if (!_super.prototype.isReady.call(this)) {
  78087. return false;
  78088. }
  78089. for (var name in this._textures) {
  78090. var texture = this._textures[name];
  78091. if (!texture.isReady()) {
  78092. return false;
  78093. }
  78094. }
  78095. return true;
  78096. };
  78097. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78098. var scene = this.getScene();
  78099. if (this._animate && scene) {
  78100. this._time += scene.getAnimationRatio() * 0.03;
  78101. this.updateShaderUniforms();
  78102. }
  78103. _super.prototype.render.call(this, useCameraPostProcess);
  78104. };
  78105. CustomProceduralTexture.prototype.updateTextures = function () {
  78106. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78107. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78108. }
  78109. };
  78110. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78111. if (this._config) {
  78112. for (var j = 0; j < this._config.uniforms.length; j++) {
  78113. var uniform = this._config.uniforms[j];
  78114. switch (uniform.type) {
  78115. case "float":
  78116. this.setFloat(uniform.name, uniform.value);
  78117. break;
  78118. case "color3":
  78119. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78120. break;
  78121. case "color4":
  78122. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78123. break;
  78124. case "vector2":
  78125. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78126. break;
  78127. case "vector3":
  78128. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78129. break;
  78130. }
  78131. }
  78132. }
  78133. this.setFloat("time", this._time);
  78134. };
  78135. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78136. get: function () {
  78137. return this._animate;
  78138. },
  78139. set: function (value) {
  78140. this._animate = value;
  78141. },
  78142. enumerable: true,
  78143. configurable: true
  78144. });
  78145. return CustomProceduralTexture;
  78146. }(BABYLON.ProceduralTexture));
  78147. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78148. })(BABYLON || (BABYLON = {}));
  78149. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78150. var BABYLON;
  78151. (function (BABYLON) {
  78152. /**
  78153. * Manage the gamepad inputs to control a free camera.
  78154. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78155. */
  78156. var FreeCameraGamepadInput = /** @class */ (function () {
  78157. function FreeCameraGamepadInput() {
  78158. /**
  78159. * Defines the gamepad rotation sensiblity.
  78160. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78161. */
  78162. this.gamepadAngularSensibility = 200;
  78163. /**
  78164. * Defines the gamepad move sensiblity.
  78165. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78166. */
  78167. this.gamepadMoveSensibility = 40;
  78168. this._cameraTransform = BABYLON.Matrix.Identity();
  78169. this._deltaTransform = BABYLON.Vector3.Zero();
  78170. this._vector3 = BABYLON.Vector3.Zero();
  78171. this._vector2 = BABYLON.Vector2.Zero();
  78172. }
  78173. /**
  78174. * Attach the input controls to a specific dom element to get the input from.
  78175. * @param element Defines the element the controls should be listened from
  78176. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78177. */
  78178. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78179. var _this = this;
  78180. var manager = this.camera.getScene().gamepadManager;
  78181. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78182. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78183. // prioritize XBOX gamepads.
  78184. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78185. _this.gamepad = gamepad;
  78186. }
  78187. }
  78188. });
  78189. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78190. if (_this.gamepad === gamepad) {
  78191. _this.gamepad = null;
  78192. }
  78193. });
  78194. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78195. };
  78196. /**
  78197. * Detach the current controls from the specified dom element.
  78198. * @param element Defines the element to stop listening the inputs from
  78199. */
  78200. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78201. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78202. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78203. this.gamepad = null;
  78204. };
  78205. /**
  78206. * Update the current camera state depending on the inputs that have been used this frame.
  78207. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78208. */
  78209. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78210. if (this.gamepad && this.gamepad.leftStick) {
  78211. var camera = this.camera;
  78212. var LSValues = this.gamepad.leftStick;
  78213. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78214. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78215. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78216. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78217. var RSValues = this.gamepad.rightStick;
  78218. if (RSValues) {
  78219. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78220. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78221. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78222. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78223. }
  78224. else {
  78225. RSValues = { x: 0, y: 0 };
  78226. }
  78227. if (!camera.rotationQuaternion) {
  78228. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78229. }
  78230. else {
  78231. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78232. }
  78233. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78234. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78235. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78236. camera.cameraDirection.addInPlace(this._deltaTransform);
  78237. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78238. camera.cameraRotation.addInPlace(this._vector2);
  78239. }
  78240. };
  78241. /**
  78242. * Gets the class name of the current intput.
  78243. * @returns the class name
  78244. */
  78245. FreeCameraGamepadInput.prototype.getClassName = function () {
  78246. return "FreeCameraGamepadInput";
  78247. };
  78248. /**
  78249. * Get the friendly name associated with the input class.
  78250. * @returns the input friendly name
  78251. */
  78252. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78253. return "gamepad";
  78254. };
  78255. __decorate([
  78256. BABYLON.serialize()
  78257. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78258. __decorate([
  78259. BABYLON.serialize()
  78260. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78261. return FreeCameraGamepadInput;
  78262. }());
  78263. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78264. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78265. })(BABYLON || (BABYLON = {}));
  78266. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78267. var BABYLON;
  78268. (function (BABYLON) {
  78269. /**
  78270. * Manage the gamepad inputs to control an arc rotate camera.
  78271. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78272. */
  78273. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78274. function ArcRotateCameraGamepadInput() {
  78275. /**
  78276. * Defines the gamepad rotation sensiblity.
  78277. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78278. */
  78279. this.gamepadRotationSensibility = 80;
  78280. /**
  78281. * Defines the gamepad move sensiblity.
  78282. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78283. */
  78284. this.gamepadMoveSensibility = 40;
  78285. }
  78286. /**
  78287. * Attach the input controls to a specific dom element to get the input from.
  78288. * @param element Defines the element the controls should be listened from
  78289. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78290. */
  78291. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78292. var _this = this;
  78293. var manager = this.camera.getScene().gamepadManager;
  78294. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78295. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78296. // prioritize XBOX gamepads.
  78297. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78298. _this.gamepad = gamepad;
  78299. }
  78300. }
  78301. });
  78302. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78303. if (_this.gamepad === gamepad) {
  78304. _this.gamepad = null;
  78305. }
  78306. });
  78307. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78308. };
  78309. /**
  78310. * Detach the current controls from the specified dom element.
  78311. * @param element Defines the element to stop listening the inputs from
  78312. */
  78313. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78314. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78315. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78316. this.gamepad = null;
  78317. };
  78318. /**
  78319. * Update the current camera state depending on the inputs that have been used this frame.
  78320. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78321. */
  78322. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78323. if (this.gamepad) {
  78324. var camera = this.camera;
  78325. var RSValues = this.gamepad.rightStick;
  78326. if (RSValues) {
  78327. if (RSValues.x != 0) {
  78328. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78329. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78330. camera.inertialAlphaOffset += normalizedRX;
  78331. }
  78332. }
  78333. if (RSValues.y != 0) {
  78334. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78335. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78336. camera.inertialBetaOffset += normalizedRY;
  78337. }
  78338. }
  78339. }
  78340. var LSValues = this.gamepad.leftStick;
  78341. if (LSValues && LSValues.y != 0) {
  78342. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78343. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78344. this.camera.inertialRadiusOffset -= normalizedLY;
  78345. }
  78346. }
  78347. }
  78348. };
  78349. /**
  78350. * Gets the class name of the current intput.
  78351. * @returns the class name
  78352. */
  78353. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  78354. return "ArcRotateCameraGamepadInput";
  78355. };
  78356. /**
  78357. * Get the friendly name associated with the input class.
  78358. * @returns the input friendly name
  78359. */
  78360. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  78361. return "gamepad";
  78362. };
  78363. __decorate([
  78364. BABYLON.serialize()
  78365. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  78366. __decorate([
  78367. BABYLON.serialize()
  78368. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78369. return ArcRotateCameraGamepadInput;
  78370. }());
  78371. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  78372. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  78373. })(BABYLON || (BABYLON = {}));
  78374. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  78375. var BABYLON;
  78376. (function (BABYLON) {
  78377. /**
  78378. * Manager for handling gamepads
  78379. */
  78380. var GamepadManager = /** @class */ (function () {
  78381. /**
  78382. * Initializes the gamepad manager
  78383. * @param _scene BabylonJS scene
  78384. */
  78385. function GamepadManager(_scene) {
  78386. var _this = this;
  78387. this._scene = _scene;
  78388. this._babylonGamepads = [];
  78389. this._oneGamepadConnected = false;
  78390. /** @hidden */
  78391. this._isMonitoring = false;
  78392. /**
  78393. * observable to be triggered when the gamepad controller has been disconnected
  78394. */
  78395. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  78396. if (!BABYLON.Tools.IsWindowObjectExist()) {
  78397. this._gamepadEventSupported = false;
  78398. }
  78399. else {
  78400. this._gamepadEventSupported = 'GamepadEvent' in window;
  78401. this._gamepadSupport = (navigator.getGamepads ||
  78402. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  78403. }
  78404. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  78405. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  78406. for (var i in _this._babylonGamepads) {
  78407. var gamepad = _this._babylonGamepads[i];
  78408. if (gamepad && gamepad._isConnected) {
  78409. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  78410. }
  78411. }
  78412. });
  78413. this._onGamepadConnectedEvent = function (evt) {
  78414. var gamepad = evt.gamepad;
  78415. if (gamepad.index in _this._babylonGamepads) {
  78416. if (_this._babylonGamepads[gamepad.index].isConnected) {
  78417. return;
  78418. }
  78419. }
  78420. var newGamepad;
  78421. if (_this._babylonGamepads[gamepad.index]) {
  78422. newGamepad = _this._babylonGamepads[gamepad.index];
  78423. newGamepad.browserGamepad = gamepad;
  78424. newGamepad._isConnected = true;
  78425. }
  78426. else {
  78427. newGamepad = _this._addNewGamepad(gamepad);
  78428. }
  78429. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  78430. _this._startMonitoringGamepads();
  78431. };
  78432. this._onGamepadDisconnectedEvent = function (evt) {
  78433. var gamepad = evt.gamepad;
  78434. // Remove the gamepad from the list of gamepads to monitor.
  78435. for (var i in _this._babylonGamepads) {
  78436. if (_this._babylonGamepads[i].index === gamepad.index) {
  78437. var disconnectedGamepad = _this._babylonGamepads[i];
  78438. disconnectedGamepad._isConnected = false;
  78439. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  78440. break;
  78441. }
  78442. }
  78443. };
  78444. if (this._gamepadSupport) {
  78445. //first add already-connected gamepads
  78446. this._updateGamepadObjects();
  78447. if (this._babylonGamepads.length) {
  78448. this._startMonitoringGamepads();
  78449. }
  78450. // Checking if the gamepad connected event is supported (like in Firefox)
  78451. if (this._gamepadEventSupported) {
  78452. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  78453. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  78454. }
  78455. else {
  78456. this._startMonitoringGamepads();
  78457. }
  78458. }
  78459. }
  78460. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  78461. /**
  78462. * The gamepads in the game pad manager
  78463. */
  78464. get: function () {
  78465. return this._babylonGamepads;
  78466. },
  78467. enumerable: true,
  78468. configurable: true
  78469. });
  78470. /**
  78471. * Get the gamepad controllers based on type
  78472. * @param type The type of gamepad controller
  78473. * @returns Nullable gamepad
  78474. */
  78475. GamepadManager.prototype.getGamepadByType = function (type) {
  78476. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  78477. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  78478. var gamepad = _a[_i];
  78479. if (gamepad && gamepad.type === type) {
  78480. return gamepad;
  78481. }
  78482. }
  78483. return null;
  78484. };
  78485. /**
  78486. * Disposes the gamepad manager
  78487. */
  78488. GamepadManager.prototype.dispose = function () {
  78489. if (this._gamepadEventSupported) {
  78490. if (this._onGamepadConnectedEvent) {
  78491. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  78492. }
  78493. if (this._onGamepadDisconnectedEvent) {
  78494. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  78495. }
  78496. this._onGamepadConnectedEvent = null;
  78497. this._onGamepadDisconnectedEvent = null;
  78498. }
  78499. this._babylonGamepads.forEach(function (gamepad) {
  78500. gamepad.dispose();
  78501. });
  78502. this.onGamepadConnectedObservable.clear();
  78503. this.onGamepadDisconnectedObservable.clear();
  78504. this._oneGamepadConnected = false;
  78505. this._stopMonitoringGamepads();
  78506. this._babylonGamepads = [];
  78507. };
  78508. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  78509. if (!this._oneGamepadConnected) {
  78510. this._oneGamepadConnected = true;
  78511. }
  78512. var newGamepad;
  78513. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  78514. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  78515. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  78516. }
  78517. // if pose is supported, use the (WebVR) pose enabled controller
  78518. else if (gamepad.pose) {
  78519. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  78520. }
  78521. else {
  78522. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  78523. }
  78524. this._babylonGamepads[newGamepad.index] = newGamepad;
  78525. return newGamepad;
  78526. };
  78527. GamepadManager.prototype._startMonitoringGamepads = function () {
  78528. if (!this._isMonitoring) {
  78529. this._isMonitoring = true;
  78530. //back-comp
  78531. if (!this._scene) {
  78532. this._checkGamepadsStatus();
  78533. }
  78534. }
  78535. };
  78536. GamepadManager.prototype._stopMonitoringGamepads = function () {
  78537. this._isMonitoring = false;
  78538. };
  78539. /** @hidden */
  78540. GamepadManager.prototype._checkGamepadsStatus = function () {
  78541. var _this = this;
  78542. // Hack to be compatible Chrome
  78543. this._updateGamepadObjects();
  78544. for (var i in this._babylonGamepads) {
  78545. var gamepad = this._babylonGamepads[i];
  78546. if (!gamepad || !gamepad.isConnected) {
  78547. continue;
  78548. }
  78549. gamepad.update();
  78550. }
  78551. if (this._isMonitoring && !this._scene) {
  78552. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  78553. }
  78554. };
  78555. // This function is called only on Chrome, which does not properly support
  78556. // connection/disconnection events and forces you to recopy again the gamepad object
  78557. GamepadManager.prototype._updateGamepadObjects = function () {
  78558. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  78559. for (var i = 0; i < gamepads.length; i++) {
  78560. var gamepad = gamepads[i];
  78561. if (gamepad) {
  78562. if (!this._babylonGamepads[gamepad.index]) {
  78563. var newGamepad = this._addNewGamepad(gamepad);
  78564. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  78565. }
  78566. else {
  78567. // Forced to copy again this object for Chrome for unknown reason
  78568. this._babylonGamepads[i].browserGamepad = gamepad;
  78569. if (!this._babylonGamepads[i].isConnected) {
  78570. this._babylonGamepads[i]._isConnected = true;
  78571. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  78572. }
  78573. }
  78574. }
  78575. }
  78576. };
  78577. return GamepadManager;
  78578. }());
  78579. BABYLON.GamepadManager = GamepadManager;
  78580. })(BABYLON || (BABYLON = {}));
  78581. //# sourceMappingURL=babylon.gamepadManager.js.map
  78582. var BABYLON;
  78583. (function (BABYLON) {
  78584. /**
  78585. * Represents a gamepad control stick position
  78586. */
  78587. var StickValues = /** @class */ (function () {
  78588. /**
  78589. * Initializes the gamepad x and y control stick values
  78590. * @param x The x component of the gamepad control stick value
  78591. * @param y The y component of the gamepad control stick value
  78592. */
  78593. function StickValues(
  78594. /**
  78595. * The x component of the control stick
  78596. */
  78597. x,
  78598. /**
  78599. * The y component of the control stick
  78600. */
  78601. y) {
  78602. this.x = x;
  78603. this.y = y;
  78604. }
  78605. return StickValues;
  78606. }());
  78607. BABYLON.StickValues = StickValues;
  78608. /**
  78609. * Represents a gamepad
  78610. */
  78611. var Gamepad = /** @class */ (function () {
  78612. /**
  78613. * Initializes the gamepad
  78614. * @param id The id of the gamepad
  78615. * @param index The index of the gamepad
  78616. * @param browserGamepad The browser gamepad
  78617. * @param leftStickX The x component of the left joystick
  78618. * @param leftStickY The y component of the left joystick
  78619. * @param rightStickX The x component of the right joystick
  78620. * @param rightStickY The y component of the right joystick
  78621. */
  78622. function Gamepad(
  78623. /**
  78624. * The id of the gamepad
  78625. */
  78626. id,
  78627. /**
  78628. * The index of the gamepad
  78629. */
  78630. index,
  78631. /**
  78632. * The browser gamepad
  78633. */
  78634. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  78635. if (leftStickX === void 0) { leftStickX = 0; }
  78636. if (leftStickY === void 0) { leftStickY = 1; }
  78637. if (rightStickX === void 0) { rightStickX = 2; }
  78638. if (rightStickY === void 0) { rightStickY = 3; }
  78639. this.id = id;
  78640. this.index = index;
  78641. this.browserGamepad = browserGamepad;
  78642. this._leftStick = { x: 0, y: 0 };
  78643. this._rightStick = { x: 0, y: 0 };
  78644. /** @hidden */
  78645. this._isConnected = true;
  78646. /**
  78647. * Specifies whether the left control stick should be Y-inverted
  78648. */
  78649. this._invertLeftStickY = false;
  78650. this.type = Gamepad.GAMEPAD;
  78651. this._leftStickAxisX = leftStickX;
  78652. this._leftStickAxisY = leftStickY;
  78653. this._rightStickAxisX = rightStickX;
  78654. this._rightStickAxisY = rightStickY;
  78655. if (this.browserGamepad.axes.length >= 2) {
  78656. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  78657. }
  78658. if (this.browserGamepad.axes.length >= 4) {
  78659. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  78660. }
  78661. }
  78662. Object.defineProperty(Gamepad.prototype, "isConnected", {
  78663. /**
  78664. * Specifies if the gamepad has been connected
  78665. */
  78666. get: function () {
  78667. return this._isConnected;
  78668. },
  78669. enumerable: true,
  78670. configurable: true
  78671. });
  78672. /**
  78673. * Callback triggered when the left joystick has changed
  78674. * @param callback
  78675. */
  78676. Gamepad.prototype.onleftstickchanged = function (callback) {
  78677. this._onleftstickchanged = callback;
  78678. };
  78679. /**
  78680. * Callback triggered when the right joystick has changed
  78681. * @param callback
  78682. */
  78683. Gamepad.prototype.onrightstickchanged = function (callback) {
  78684. this._onrightstickchanged = callback;
  78685. };
  78686. Object.defineProperty(Gamepad.prototype, "leftStick", {
  78687. /**
  78688. * Gets the left joystick
  78689. */
  78690. get: function () {
  78691. return this._leftStick;
  78692. },
  78693. /**
  78694. * Sets the left joystick values
  78695. */
  78696. set: function (newValues) {
  78697. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  78698. this._onleftstickchanged(newValues);
  78699. }
  78700. this._leftStick = newValues;
  78701. },
  78702. enumerable: true,
  78703. configurable: true
  78704. });
  78705. Object.defineProperty(Gamepad.prototype, "rightStick", {
  78706. /**
  78707. * Gets the right joystick
  78708. */
  78709. get: function () {
  78710. return this._rightStick;
  78711. },
  78712. /**
  78713. * Sets the right joystick value
  78714. */
  78715. set: function (newValues) {
  78716. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  78717. this._onrightstickchanged(newValues);
  78718. }
  78719. this._rightStick = newValues;
  78720. },
  78721. enumerable: true,
  78722. configurable: true
  78723. });
  78724. /**
  78725. * Updates the gamepad joystick positions
  78726. */
  78727. Gamepad.prototype.update = function () {
  78728. if (this._leftStick) {
  78729. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  78730. if (this._invertLeftStickY) {
  78731. this.leftStick.y *= -1;
  78732. }
  78733. }
  78734. if (this._rightStick) {
  78735. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  78736. }
  78737. };
  78738. /**
  78739. * Disposes the gamepad
  78740. */
  78741. Gamepad.prototype.dispose = function () {
  78742. };
  78743. /**
  78744. * Represents a gamepad controller
  78745. */
  78746. Gamepad.GAMEPAD = 0;
  78747. /**
  78748. * Represents a generic controller
  78749. */
  78750. Gamepad.GENERIC = 1;
  78751. /**
  78752. * Represents an XBox controller
  78753. */
  78754. Gamepad.XBOX = 2;
  78755. /**
  78756. * Represents a pose-enabled controller
  78757. */
  78758. Gamepad.POSE_ENABLED = 3;
  78759. return Gamepad;
  78760. }());
  78761. BABYLON.Gamepad = Gamepad;
  78762. /**
  78763. * Represents a generic gamepad
  78764. */
  78765. var GenericPad = /** @class */ (function (_super) {
  78766. __extends(GenericPad, _super);
  78767. /**
  78768. * Initializes the generic gamepad
  78769. * @param id The id of the generic gamepad
  78770. * @param index The index of the generic gamepad
  78771. * @param browserGamepad The browser gamepad
  78772. */
  78773. function GenericPad(id, index, browserGamepad) {
  78774. var _this = _super.call(this, id, index, browserGamepad) || this;
  78775. /**
  78776. * Observable triggered when a button has been pressed
  78777. */
  78778. _this.onButtonDownObservable = new BABYLON.Observable();
  78779. /**
  78780. * Observable triggered when a button has been released
  78781. */
  78782. _this.onButtonUpObservable = new BABYLON.Observable();
  78783. _this.type = Gamepad.GENERIC;
  78784. _this._buttons = new Array(browserGamepad.buttons.length);
  78785. return _this;
  78786. }
  78787. /**
  78788. * Callback triggered when a button has been pressed
  78789. * @param callback Called when a button has been pressed
  78790. */
  78791. GenericPad.prototype.onbuttondown = function (callback) {
  78792. this._onbuttondown = callback;
  78793. };
  78794. /**
  78795. * Callback triggered when a button has been released
  78796. * @param callback Called when a button has been released
  78797. */
  78798. GenericPad.prototype.onbuttonup = function (callback) {
  78799. this._onbuttonup = callback;
  78800. };
  78801. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  78802. if (newValue !== currentValue) {
  78803. if (newValue === 1) {
  78804. if (this._onbuttondown) {
  78805. this._onbuttondown(buttonIndex);
  78806. }
  78807. this.onButtonDownObservable.notifyObservers(buttonIndex);
  78808. }
  78809. if (newValue === 0) {
  78810. if (this._onbuttonup) {
  78811. this._onbuttonup(buttonIndex);
  78812. }
  78813. this.onButtonUpObservable.notifyObservers(buttonIndex);
  78814. }
  78815. }
  78816. return newValue;
  78817. };
  78818. /**
  78819. * Updates the generic gamepad
  78820. */
  78821. GenericPad.prototype.update = function () {
  78822. _super.prototype.update.call(this);
  78823. for (var index = 0; index < this._buttons.length; index++) {
  78824. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  78825. }
  78826. };
  78827. /**
  78828. * Disposes the generic gamepad
  78829. */
  78830. GenericPad.prototype.dispose = function () {
  78831. _super.prototype.dispose.call(this);
  78832. this.onButtonDownObservable.clear();
  78833. this.onButtonUpObservable.clear();
  78834. };
  78835. return GenericPad;
  78836. }(Gamepad));
  78837. BABYLON.GenericPad = GenericPad;
  78838. })(BABYLON || (BABYLON = {}));
  78839. //# sourceMappingURL=babylon.gamepad.js.map
  78840. var BABYLON;
  78841. (function (BABYLON) {
  78842. /**
  78843. * Defines supported buttons for XBox360 compatible gamepads
  78844. */
  78845. var Xbox360Button;
  78846. (function (Xbox360Button) {
  78847. /** A */
  78848. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  78849. /** B */
  78850. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  78851. /** X */
  78852. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  78853. /** Y */
  78854. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  78855. /** Start */
  78856. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  78857. /** Back */
  78858. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  78859. /** Left button */
  78860. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  78861. /** Right button */
  78862. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  78863. /** Left stick */
  78864. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  78865. /** Right stick */
  78866. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  78867. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  78868. /** Defines values for XBox360 DPad */
  78869. var Xbox360Dpad;
  78870. (function (Xbox360Dpad) {
  78871. /** Up */
  78872. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  78873. /** Down */
  78874. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  78875. /** Left */
  78876. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  78877. /** Right */
  78878. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  78879. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  78880. /**
  78881. * Defines a XBox360 gamepad
  78882. */
  78883. var Xbox360Pad = /** @class */ (function (_super) {
  78884. __extends(Xbox360Pad, _super);
  78885. /**
  78886. * Creates a new XBox360 gamepad object
  78887. * @param id defines the id of this gamepad
  78888. * @param index defines its index
  78889. * @param gamepad defines the internal HTML gamepad object
  78890. * @param xboxOne defines if it is a XBox One gamepad
  78891. */
  78892. function Xbox360Pad(id, index, gamepad, xboxOne) {
  78893. if (xboxOne === void 0) { xboxOne = false; }
  78894. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  78895. _this._leftTrigger = 0;
  78896. _this._rightTrigger = 0;
  78897. /** Observable raised when a button is pressed */
  78898. _this.onButtonDownObservable = new BABYLON.Observable();
  78899. /** Observable raised when a button is released */
  78900. _this.onButtonUpObservable = new BABYLON.Observable();
  78901. /** Observable raised when a pad is pressed */
  78902. _this.onPadDownObservable = new BABYLON.Observable();
  78903. /** Observable raised when a pad is released */
  78904. _this.onPadUpObservable = new BABYLON.Observable();
  78905. _this._buttonA = 0;
  78906. _this._buttonB = 0;
  78907. _this._buttonX = 0;
  78908. _this._buttonY = 0;
  78909. _this._buttonBack = 0;
  78910. _this._buttonStart = 0;
  78911. _this._buttonLB = 0;
  78912. _this._buttonRB = 0;
  78913. _this._buttonLeftStick = 0;
  78914. _this._buttonRightStick = 0;
  78915. _this._dPadUp = 0;
  78916. _this._dPadDown = 0;
  78917. _this._dPadLeft = 0;
  78918. _this._dPadRight = 0;
  78919. _this._isXboxOnePad = false;
  78920. _this.type = BABYLON.Gamepad.XBOX;
  78921. _this._isXboxOnePad = xboxOne;
  78922. return _this;
  78923. }
  78924. /**
  78925. * Defines the callback to call when left trigger is pressed
  78926. * @param callback defines the callback to use
  78927. */
  78928. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  78929. this._onlefttriggerchanged = callback;
  78930. };
  78931. /**
  78932. * Defines the callback to call when right trigger is pressed
  78933. * @param callback defines the callback to use
  78934. */
  78935. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  78936. this._onrighttriggerchanged = callback;
  78937. };
  78938. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  78939. /**
  78940. * Gets the left trigger value
  78941. */
  78942. get: function () {
  78943. return this._leftTrigger;
  78944. },
  78945. /**
  78946. * Sets the left trigger value
  78947. */
  78948. set: function (newValue) {
  78949. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  78950. this._onlefttriggerchanged(newValue);
  78951. }
  78952. this._leftTrigger = newValue;
  78953. },
  78954. enumerable: true,
  78955. configurable: true
  78956. });
  78957. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  78958. /**
  78959. * Gets the right trigger value
  78960. */
  78961. get: function () {
  78962. return this._rightTrigger;
  78963. },
  78964. /**
  78965. * Sets the right trigger value
  78966. */
  78967. set: function (newValue) {
  78968. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  78969. this._onrighttriggerchanged(newValue);
  78970. }
  78971. this._rightTrigger = newValue;
  78972. },
  78973. enumerable: true,
  78974. configurable: true
  78975. });
  78976. /**
  78977. * Defines the callback to call when a button is pressed
  78978. * @param callback defines the callback to use
  78979. */
  78980. Xbox360Pad.prototype.onbuttondown = function (callback) {
  78981. this._onbuttondown = callback;
  78982. };
  78983. /**
  78984. * Defines the callback to call when a button is released
  78985. * @param callback defines the callback to use
  78986. */
  78987. Xbox360Pad.prototype.onbuttonup = function (callback) {
  78988. this._onbuttonup = callback;
  78989. };
  78990. /**
  78991. * Defines the callback to call when a pad is pressed
  78992. * @param callback defines the callback to use
  78993. */
  78994. Xbox360Pad.prototype.ondpaddown = function (callback) {
  78995. this._ondpaddown = callback;
  78996. };
  78997. /**
  78998. * Defines the callback to call when a pad is released
  78999. * @param callback defines the callback to use
  79000. */
  79001. Xbox360Pad.prototype.ondpadup = function (callback) {
  79002. this._ondpadup = callback;
  79003. };
  79004. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  79005. if (newValue !== currentValue) {
  79006. if (newValue === 1) {
  79007. if (this._onbuttondown) {
  79008. this._onbuttondown(buttonType);
  79009. }
  79010. this.onButtonDownObservable.notifyObservers(buttonType);
  79011. }
  79012. if (newValue === 0) {
  79013. if (this._onbuttonup) {
  79014. this._onbuttonup(buttonType);
  79015. }
  79016. this.onButtonUpObservable.notifyObservers(buttonType);
  79017. }
  79018. }
  79019. return newValue;
  79020. };
  79021. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  79022. if (newValue !== currentValue) {
  79023. if (newValue === 1) {
  79024. if (this._ondpaddown) {
  79025. this._ondpaddown(buttonType);
  79026. }
  79027. this.onPadDownObservable.notifyObservers(buttonType);
  79028. }
  79029. if (newValue === 0) {
  79030. if (this._ondpadup) {
  79031. this._ondpadup(buttonType);
  79032. }
  79033. this.onPadUpObservable.notifyObservers(buttonType);
  79034. }
  79035. }
  79036. return newValue;
  79037. };
  79038. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79039. /**
  79040. * Gets the value of the `A` button
  79041. */
  79042. get: function () {
  79043. return this._buttonA;
  79044. },
  79045. /**
  79046. * Sets the value of the `A` button
  79047. */
  79048. set: function (value) {
  79049. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79050. },
  79051. enumerable: true,
  79052. configurable: true
  79053. });
  79054. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79055. /**
  79056. * Gets the value of the `B` button
  79057. */
  79058. get: function () {
  79059. return this._buttonB;
  79060. },
  79061. /**
  79062. * Sets the value of the `B` button
  79063. */
  79064. set: function (value) {
  79065. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79066. },
  79067. enumerable: true,
  79068. configurable: true
  79069. });
  79070. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79071. /**
  79072. * Gets the value of the `X` button
  79073. */
  79074. get: function () {
  79075. return this._buttonX;
  79076. },
  79077. /**
  79078. * Sets the value of the `X` button
  79079. */
  79080. set: function (value) {
  79081. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79082. },
  79083. enumerable: true,
  79084. configurable: true
  79085. });
  79086. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79087. /**
  79088. * Gets the value of the `Y` button
  79089. */
  79090. get: function () {
  79091. return this._buttonY;
  79092. },
  79093. /**
  79094. * Sets the value of the `Y` button
  79095. */
  79096. set: function (value) {
  79097. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79098. },
  79099. enumerable: true,
  79100. configurable: true
  79101. });
  79102. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79103. /**
  79104. * Gets the value of the `Start` button
  79105. */
  79106. get: function () {
  79107. return this._buttonStart;
  79108. },
  79109. /**
  79110. * Sets the value of the `Start` button
  79111. */
  79112. set: function (value) {
  79113. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79114. },
  79115. enumerable: true,
  79116. configurable: true
  79117. });
  79118. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79119. /**
  79120. * Gets the value of the `Back` button
  79121. */
  79122. get: function () {
  79123. return this._buttonBack;
  79124. },
  79125. /**
  79126. * Sets the value of the `Back` button
  79127. */
  79128. set: function (value) {
  79129. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79130. },
  79131. enumerable: true,
  79132. configurable: true
  79133. });
  79134. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79135. /**
  79136. * Gets the value of the `Left` button
  79137. */
  79138. get: function () {
  79139. return this._buttonLB;
  79140. },
  79141. /**
  79142. * Sets the value of the `Left` button
  79143. */
  79144. set: function (value) {
  79145. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79146. },
  79147. enumerable: true,
  79148. configurable: true
  79149. });
  79150. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79151. /**
  79152. * Gets the value of the `Right` button
  79153. */
  79154. get: function () {
  79155. return this._buttonRB;
  79156. },
  79157. /**
  79158. * Sets the value of the `Right` button
  79159. */
  79160. set: function (value) {
  79161. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79162. },
  79163. enumerable: true,
  79164. configurable: true
  79165. });
  79166. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79167. /**
  79168. * Gets the value of the Left joystick
  79169. */
  79170. get: function () {
  79171. return this._buttonLeftStick;
  79172. },
  79173. /**
  79174. * Sets the value of the Left joystick
  79175. */
  79176. set: function (value) {
  79177. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79178. },
  79179. enumerable: true,
  79180. configurable: true
  79181. });
  79182. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79183. /**
  79184. * Gets the value of the Right joystick
  79185. */
  79186. get: function () {
  79187. return this._buttonRightStick;
  79188. },
  79189. /**
  79190. * Sets the value of the Right joystick
  79191. */
  79192. set: function (value) {
  79193. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79194. },
  79195. enumerable: true,
  79196. configurable: true
  79197. });
  79198. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79199. /**
  79200. * Gets the value of D-pad up
  79201. */
  79202. get: function () {
  79203. return this._dPadUp;
  79204. },
  79205. /**
  79206. * Sets the value of D-pad up
  79207. */
  79208. set: function (value) {
  79209. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79210. },
  79211. enumerable: true,
  79212. configurable: true
  79213. });
  79214. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79215. /**
  79216. * Gets the value of D-pad down
  79217. */
  79218. get: function () {
  79219. return this._dPadDown;
  79220. },
  79221. /**
  79222. * Sets the value of D-pad down
  79223. */
  79224. set: function (value) {
  79225. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79226. },
  79227. enumerable: true,
  79228. configurable: true
  79229. });
  79230. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79231. /**
  79232. * Gets the value of D-pad left
  79233. */
  79234. get: function () {
  79235. return this._dPadLeft;
  79236. },
  79237. /**
  79238. * Sets the value of D-pad left
  79239. */
  79240. set: function (value) {
  79241. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79247. /**
  79248. * Gets the value of D-pad right
  79249. */
  79250. get: function () {
  79251. return this._dPadRight;
  79252. },
  79253. /**
  79254. * Sets the value of D-pad right
  79255. */
  79256. set: function (value) {
  79257. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79258. },
  79259. enumerable: true,
  79260. configurable: true
  79261. });
  79262. /**
  79263. * Force the gamepad to synchronize with device values
  79264. */
  79265. Xbox360Pad.prototype.update = function () {
  79266. _super.prototype.update.call(this);
  79267. if (this._isXboxOnePad) {
  79268. this.buttonA = this.browserGamepad.buttons[0].value;
  79269. this.buttonB = this.browserGamepad.buttons[1].value;
  79270. this.buttonX = this.browserGamepad.buttons[2].value;
  79271. this.buttonY = this.browserGamepad.buttons[3].value;
  79272. this.buttonLB = this.browserGamepad.buttons[4].value;
  79273. this.buttonRB = this.browserGamepad.buttons[5].value;
  79274. this.leftTrigger = this.browserGamepad.axes[2];
  79275. this.rightTrigger = this.browserGamepad.axes[5];
  79276. this.buttonBack = this.browserGamepad.buttons[9].value;
  79277. this.buttonStart = this.browserGamepad.buttons[8].value;
  79278. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79279. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79280. this.dPadUp = this.browserGamepad.buttons[11].value;
  79281. this.dPadDown = this.browserGamepad.buttons[12].value;
  79282. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79283. this.dPadRight = this.browserGamepad.buttons[14].value;
  79284. }
  79285. else {
  79286. this.buttonA = this.browserGamepad.buttons[0].value;
  79287. this.buttonB = this.browserGamepad.buttons[1].value;
  79288. this.buttonX = this.browserGamepad.buttons[2].value;
  79289. this.buttonY = this.browserGamepad.buttons[3].value;
  79290. this.buttonLB = this.browserGamepad.buttons[4].value;
  79291. this.buttonRB = this.browserGamepad.buttons[5].value;
  79292. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79293. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79294. this.buttonBack = this.browserGamepad.buttons[8].value;
  79295. this.buttonStart = this.browserGamepad.buttons[9].value;
  79296. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79297. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79298. this.dPadUp = this.browserGamepad.buttons[12].value;
  79299. this.dPadDown = this.browserGamepad.buttons[13].value;
  79300. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79301. this.dPadRight = this.browserGamepad.buttons[15].value;
  79302. }
  79303. };
  79304. /**
  79305. * Disposes the gamepad
  79306. */
  79307. Xbox360Pad.prototype.dispose = function () {
  79308. _super.prototype.dispose.call(this);
  79309. this.onButtonDownObservable.clear();
  79310. this.onButtonUpObservable.clear();
  79311. this.onPadDownObservable.clear();
  79312. this.onPadUpObservable.clear();
  79313. };
  79314. return Xbox360Pad;
  79315. }(BABYLON.Gamepad));
  79316. BABYLON.Xbox360Pad = Xbox360Pad;
  79317. })(BABYLON || (BABYLON = {}));
  79318. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79319. var BABYLON;
  79320. (function (BABYLON) {
  79321. /**
  79322. * Defines the types of pose enabled controllers that are supported
  79323. */
  79324. var PoseEnabledControllerType;
  79325. (function (PoseEnabledControllerType) {
  79326. /**
  79327. * HTC Vive
  79328. */
  79329. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79330. /**
  79331. * Oculus Rift
  79332. */
  79333. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79334. /**
  79335. * Windows mixed reality
  79336. */
  79337. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79338. /**
  79339. * Samsung gear VR
  79340. */
  79341. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79342. /**
  79343. * Google Daydream
  79344. */
  79345. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79346. /**
  79347. * Generic
  79348. */
  79349. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79350. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  79351. /**
  79352. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79353. */
  79354. var PoseEnabledControllerHelper = /** @class */ (function () {
  79355. function PoseEnabledControllerHelper() {
  79356. }
  79357. /**
  79358. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79359. * @param vrGamepad the gamepad to initialized
  79360. * @returns a vr controller of the type the gamepad identified as
  79361. */
  79362. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  79363. // Oculus Touch
  79364. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  79365. return new BABYLON.OculusTouchController(vrGamepad);
  79366. }
  79367. // Windows Mixed Reality controllers
  79368. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  79369. return new BABYLON.WindowsMotionController(vrGamepad);
  79370. }
  79371. // HTC Vive
  79372. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  79373. return new BABYLON.ViveController(vrGamepad);
  79374. }
  79375. // Samsung/Oculus Gear VR or Oculus Go
  79376. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  79377. return new BABYLON.GearVRController(vrGamepad);
  79378. }
  79379. // Google Daydream
  79380. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  79381. return new BABYLON.DaydreamController(vrGamepad);
  79382. }
  79383. // Generic
  79384. else {
  79385. return new BABYLON.GenericController(vrGamepad);
  79386. }
  79387. };
  79388. return PoseEnabledControllerHelper;
  79389. }());
  79390. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  79391. /**
  79392. * Defines the PoseEnabledController object that contains state of a vr capable controller
  79393. */
  79394. var PoseEnabledController = /** @class */ (function (_super) {
  79395. __extends(PoseEnabledController, _super);
  79396. /**
  79397. * Creates a new PoseEnabledController from a gamepad
  79398. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  79399. */
  79400. function PoseEnabledController(browserGamepad) {
  79401. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  79402. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79403. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79404. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  79405. /**
  79406. * The device position in babylon space
  79407. */
  79408. _this.devicePosition = BABYLON.Vector3.Zero();
  79409. /**
  79410. * The device rotation in babylon space
  79411. */
  79412. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  79413. /**
  79414. * The scale factor of the device in babylon space
  79415. */
  79416. _this.deviceScaleFactor = 1;
  79417. // Used to convert 6dof controllers to 3dof
  79418. _this._trackPosition = true;
  79419. _this._maxRotationDistFromHeadset = Math.PI / 5;
  79420. _this._draggedRoomRotation = 0;
  79421. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  79422. /**
  79423. * Internal, matrix used to convert room space to babylon space
  79424. * @hidden
  79425. */
  79426. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79427. /**
  79428. * Node to be used when casting a ray from the controller
  79429. * @hidden
  79430. */
  79431. _this._pointingPoseNode = null;
  79432. _this._workingMatrix = BABYLON.Matrix.Identity();
  79433. /**
  79434. * @hidden
  79435. */
  79436. _this._meshAttachedObservable = new BABYLON.Observable();
  79437. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  79438. _this.controllerType = PoseEnabledControllerType.GENERIC;
  79439. _this.position = BABYLON.Vector3.Zero();
  79440. _this.rotationQuaternion = new BABYLON.Quaternion();
  79441. _this._calculatedPosition = BABYLON.Vector3.Zero();
  79442. _this._calculatedRotation = new BABYLON.Quaternion();
  79443. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  79444. return _this;
  79445. }
  79446. /**
  79447. * @hidden
  79448. */
  79449. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  79450. if (this._trackPosition) {
  79451. this._calculatedPosition.copyFrom(fixedPosition);
  79452. this._trackPosition = false;
  79453. }
  79454. };
  79455. /**
  79456. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  79457. */
  79458. PoseEnabledController.prototype.update = function () {
  79459. _super.prototype.update.call(this);
  79460. this._updatePoseAndMesh();
  79461. };
  79462. /**
  79463. * Updates only the pose device and mesh without doing any button event checking
  79464. */
  79465. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  79466. var pose = this.browserGamepad.pose;
  79467. this.updateFromDevice(pose);
  79468. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  79469. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  79470. camera._computeDevicePosition();
  79471. this._deviceToWorld.setTranslation(camera.devicePosition);
  79472. if (camera.deviceRotationQuaternion) {
  79473. var camera = camera;
  79474. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  79475. // Find the radian distance away that the headset is from the controllers rotation
  79476. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  79477. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  79478. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  79479. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  79480. this._draggedRoomRotation += rotationAmount;
  79481. // Rotate controller around headset
  79482. var sin = Math.sin(-rotationAmount);
  79483. var cos = Math.cos(-rotationAmount);
  79484. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  79485. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  79486. }
  79487. }
  79488. }
  79489. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  79490. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  79491. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79492. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  79493. if (this._mesh) {
  79494. this._mesh.position.copyFrom(this.devicePosition);
  79495. if (this._mesh.rotationQuaternion) {
  79496. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  79497. }
  79498. }
  79499. };
  79500. /**
  79501. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  79502. * @param poseData raw pose fromthe device
  79503. */
  79504. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  79505. if (poseData) {
  79506. this.rawPose = poseData;
  79507. if (poseData.position) {
  79508. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  79509. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  79510. this._deviceRoomPosition.z *= -1;
  79511. }
  79512. if (this._trackPosition) {
  79513. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  79514. }
  79515. this._calculatedPosition.addInPlace(this.position);
  79516. }
  79517. var pose = this.rawPose;
  79518. if (poseData.orientation && pose.orientation) {
  79519. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  79520. if (this._mesh) {
  79521. if (this._mesh.getScene().useRightHandedSystem) {
  79522. this._deviceRoomRotationQuaternion.z *= -1;
  79523. this._deviceRoomRotationQuaternion.w *= -1;
  79524. }
  79525. else {
  79526. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  79527. }
  79528. }
  79529. // if the camera is set, rotate to the camera's rotation
  79530. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  79531. }
  79532. }
  79533. };
  79534. /**
  79535. * Attaches a mesh to the controller
  79536. * @param mesh the mesh to be attached
  79537. */
  79538. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  79539. if (this._mesh) {
  79540. this._mesh.parent = null;
  79541. }
  79542. this._mesh = mesh;
  79543. if (this._poseControlledCamera) {
  79544. this._mesh.parent = this._poseControlledCamera;
  79545. }
  79546. if (!this._mesh.rotationQuaternion) {
  79547. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  79548. }
  79549. // 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
  79550. this._updatePoseAndMesh();
  79551. if (this._pointingPoseNode) {
  79552. var parents = [];
  79553. var obj = this._pointingPoseNode;
  79554. while (obj.parent) {
  79555. parents.push(obj.parent);
  79556. obj = obj.parent;
  79557. }
  79558. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  79559. }
  79560. this._meshAttachedObservable.notifyObservers(mesh);
  79561. };
  79562. /**
  79563. * Attaches the controllers mesh to a camera
  79564. * @param camera the camera the mesh should be attached to
  79565. */
  79566. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  79567. this._poseControlledCamera = camera;
  79568. if (this._mesh) {
  79569. this._mesh.parent = this._poseControlledCamera;
  79570. }
  79571. };
  79572. /**
  79573. * Disposes of the controller
  79574. */
  79575. PoseEnabledController.prototype.dispose = function () {
  79576. if (this._mesh) {
  79577. this._mesh.dispose();
  79578. }
  79579. this._mesh = null;
  79580. _super.prototype.dispose.call(this);
  79581. };
  79582. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  79583. /**
  79584. * The mesh that is attached to the controller
  79585. */
  79586. get: function () {
  79587. return this._mesh;
  79588. },
  79589. enumerable: true,
  79590. configurable: true
  79591. });
  79592. /**
  79593. * Gets the ray of the controller in the direction the controller is pointing
  79594. * @param length the length the resulting ray should be
  79595. * @returns a ray in the direction the controller is pointing
  79596. */
  79597. PoseEnabledController.prototype.getForwardRay = function (length) {
  79598. if (length === void 0) { length = 100; }
  79599. if (!this.mesh) {
  79600. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  79601. }
  79602. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  79603. var origin = m.getTranslation();
  79604. var forward = new BABYLON.Vector3(0, 0, -1);
  79605. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79606. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79607. return new BABYLON.Ray(origin, direction, length);
  79608. };
  79609. /**
  79610. * Name of the child mesh that can be used to cast a ray from the controller
  79611. */
  79612. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  79613. return PoseEnabledController;
  79614. }(BABYLON.Gamepad));
  79615. BABYLON.PoseEnabledController = PoseEnabledController;
  79616. })(BABYLON || (BABYLON = {}));
  79617. //# sourceMappingURL=babylon.poseEnabledController.js.map
  79618. var BABYLON;
  79619. (function (BABYLON) {
  79620. /**
  79621. * Defines the WebVRController object that represents controllers tracked in 3D space
  79622. */
  79623. var WebVRController = /** @class */ (function (_super) {
  79624. __extends(WebVRController, _super);
  79625. /**
  79626. * Creates a new WebVRController from a gamepad
  79627. * @param vrGamepad the gamepad that the WebVRController should be created from
  79628. */
  79629. function WebVRController(vrGamepad) {
  79630. var _this = _super.call(this, vrGamepad) || this;
  79631. // Observables
  79632. /**
  79633. * Fired when the trigger state has changed
  79634. */
  79635. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  79636. /**
  79637. * Fired when the main button state has changed
  79638. */
  79639. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  79640. /**
  79641. * Fired when the secondary button state has changed
  79642. */
  79643. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  79644. /**
  79645. * Fired when the pad state has changed
  79646. */
  79647. _this.onPadStateChangedObservable = new BABYLON.Observable();
  79648. /**
  79649. * Fired when controllers stick values have changed
  79650. */
  79651. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  79652. /**
  79653. * X and Y axis corrisponding to the controllers joystick
  79654. */
  79655. _this.pad = { x: 0, y: 0 };
  79656. // avoid GC, store state in a tmp object
  79657. _this._changes = {
  79658. pressChanged: false,
  79659. touchChanged: false,
  79660. valueChanged: false,
  79661. changed: false
  79662. };
  79663. _this._buttons = new Array(vrGamepad.buttons.length);
  79664. _this.hand = vrGamepad.hand;
  79665. return _this;
  79666. }
  79667. /**
  79668. * Fired when a controller button's state has changed
  79669. * @param callback the callback containing the button that was modified
  79670. */
  79671. WebVRController.prototype.onButtonStateChange = function (callback) {
  79672. this._onButtonStateChange = callback;
  79673. };
  79674. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  79675. /**
  79676. * The default controller model for the controller
  79677. */
  79678. get: function () {
  79679. return this._defaultModel;
  79680. },
  79681. enumerable: true,
  79682. configurable: true
  79683. });
  79684. /**
  79685. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  79686. */
  79687. WebVRController.prototype.update = function () {
  79688. _super.prototype.update.call(this);
  79689. for (var index = 0; index < this._buttons.length; index++) {
  79690. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  79691. }
  79692. ;
  79693. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  79694. this.pad.x = this.leftStick.x;
  79695. this.pad.y = this.leftStick.y;
  79696. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  79697. }
  79698. };
  79699. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  79700. if (!newState) {
  79701. newState = {
  79702. pressed: false,
  79703. touched: false,
  79704. value: 0
  79705. };
  79706. }
  79707. if (!currentState) {
  79708. this._buttons[buttonIndex] = {
  79709. pressed: newState.pressed,
  79710. touched: newState.touched,
  79711. value: newState.value
  79712. };
  79713. return;
  79714. }
  79715. this._checkChanges(newState, currentState);
  79716. if (this._changes.changed) {
  79717. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  79718. this._handleButtonChange(buttonIndex, newState, this._changes);
  79719. }
  79720. this._buttons[buttonIndex].pressed = newState.pressed;
  79721. this._buttons[buttonIndex].touched = newState.touched;
  79722. // oculus triggers are never 0, thou not touched.
  79723. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  79724. };
  79725. WebVRController.prototype._checkChanges = function (newState, currentState) {
  79726. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  79727. this._changes.touchChanged = newState.touched !== currentState.touched;
  79728. this._changes.valueChanged = newState.value !== currentState.value;
  79729. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  79730. return this._changes;
  79731. };
  79732. /**
  79733. * Disposes of th webVRCOntroller
  79734. */
  79735. WebVRController.prototype.dispose = function () {
  79736. _super.prototype.dispose.call(this);
  79737. this.onTriggerStateChangedObservable.clear();
  79738. this.onMainButtonStateChangedObservable.clear();
  79739. this.onSecondaryButtonStateChangedObservable.clear();
  79740. this.onPadStateChangedObservable.clear();
  79741. this.onPadValuesChangedObservable.clear();
  79742. };
  79743. return WebVRController;
  79744. }(BABYLON.PoseEnabledController));
  79745. BABYLON.WebVRController = WebVRController;
  79746. })(BABYLON || (BABYLON = {}));
  79747. //# sourceMappingURL=babylon.webVRController.js.map
  79748. var BABYLON;
  79749. (function (BABYLON) {
  79750. /**
  79751. * Oculus Touch Controller
  79752. */
  79753. var OculusTouchController = /** @class */ (function (_super) {
  79754. __extends(OculusTouchController, _super);
  79755. /**
  79756. * Creates a new OculusTouchController from a gamepad
  79757. * @param vrGamepad the gamepad that the controller should be created from
  79758. */
  79759. function OculusTouchController(vrGamepad) {
  79760. var _this = _super.call(this, vrGamepad) || this;
  79761. /**
  79762. * Fired when the secondary trigger on this controller is modified
  79763. */
  79764. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  79765. /**
  79766. * Fired when the thumb rest on this controller is modified
  79767. */
  79768. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  79769. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  79770. return _this;
  79771. }
  79772. /**
  79773. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79774. * @param scene scene in which to add meshes
  79775. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79776. */
  79777. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79778. var _this = this;
  79779. var meshName;
  79780. // Hand
  79781. if (this.hand === 'left') {
  79782. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  79783. }
  79784. else { // Right is the default if no hand is specified
  79785. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  79786. }
  79787. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  79788. /*
  79789. Parent Mesh name: oculus_touch_left
  79790. - body
  79791. - trigger
  79792. - thumbstick
  79793. - grip
  79794. - button_y
  79795. - button_x
  79796. - button_enter
  79797. */
  79798. _this._defaultModel = newMeshes[1];
  79799. _this.attachToMesh(_this._defaultModel);
  79800. if (meshLoaded) {
  79801. meshLoaded(_this._defaultModel);
  79802. }
  79803. });
  79804. };
  79805. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  79806. /**
  79807. * Fired when the A button on this controller is modified
  79808. */
  79809. get: function () {
  79810. if (this.hand === 'right') {
  79811. return this.onMainButtonStateChangedObservable;
  79812. }
  79813. else {
  79814. throw new Error('No A button on left hand');
  79815. }
  79816. },
  79817. enumerable: true,
  79818. configurable: true
  79819. });
  79820. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  79821. /**
  79822. * Fired when the B button on this controller is modified
  79823. */
  79824. get: function () {
  79825. if (this.hand === 'right') {
  79826. return this.onSecondaryButtonStateChangedObservable;
  79827. }
  79828. else {
  79829. throw new Error('No B button on left hand');
  79830. }
  79831. },
  79832. enumerable: true,
  79833. configurable: true
  79834. });
  79835. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  79836. /**
  79837. * Fired when the X button on this controller is modified
  79838. */
  79839. get: function () {
  79840. if (this.hand === 'left') {
  79841. return this.onMainButtonStateChangedObservable;
  79842. }
  79843. else {
  79844. throw new Error('No X button on right hand');
  79845. }
  79846. },
  79847. enumerable: true,
  79848. configurable: true
  79849. });
  79850. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  79851. /**
  79852. * Fired when the Y button on this controller is modified
  79853. */
  79854. get: function () {
  79855. if (this.hand === 'left') {
  79856. return this.onSecondaryButtonStateChangedObservable;
  79857. }
  79858. else {
  79859. throw new Error('No Y button on right hand');
  79860. }
  79861. },
  79862. enumerable: true,
  79863. configurable: true
  79864. });
  79865. /**
  79866. * Called once for each button that changed state since the last frame
  79867. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  79868. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  79869. * 2) secondary trigger (same)
  79870. * 3) A (right) X (left), touch, pressed = value
  79871. * 4) B / Y
  79872. * 5) thumb rest
  79873. * @param buttonIdx Which button index changed
  79874. * @param state New state of the button
  79875. * @param changes Which properties on the state changed since last frame
  79876. */
  79877. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79878. var notifyObject = state; //{ state: state, changes: changes };
  79879. var triggerDirection = this.hand === 'right' ? -1 : 1;
  79880. switch (buttonIdx) {
  79881. case 0:
  79882. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79883. return;
  79884. case 1: // index trigger
  79885. if (this._defaultModel) {
  79886. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  79887. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  79888. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  79889. }
  79890. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79891. return;
  79892. case 2: // secondary trigger
  79893. if (this._defaultModel) {
  79894. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  79895. }
  79896. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  79897. return;
  79898. case 3:
  79899. if (this._defaultModel) {
  79900. if (notifyObject.pressed) {
  79901. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  79902. }
  79903. else {
  79904. (this._defaultModel.getChildren()[1]).position.y = 0;
  79905. }
  79906. }
  79907. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79908. return;
  79909. case 4:
  79910. if (this._defaultModel) {
  79911. if (notifyObject.pressed) {
  79912. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79913. }
  79914. else {
  79915. (this._defaultModel.getChildren()[2]).position.y = 0;
  79916. }
  79917. }
  79918. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79919. return;
  79920. case 5:
  79921. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  79922. return;
  79923. }
  79924. };
  79925. /**
  79926. * Base Url for the controller model.
  79927. */
  79928. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  79929. /**
  79930. * File name for the left controller model.
  79931. */
  79932. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  79933. /**
  79934. * File name for the right controller model.
  79935. */
  79936. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  79937. return OculusTouchController;
  79938. }(BABYLON.WebVRController));
  79939. BABYLON.OculusTouchController = OculusTouchController;
  79940. })(BABYLON || (BABYLON = {}));
  79941. //# sourceMappingURL=babylon.oculusTouchController.js.map
  79942. var BABYLON;
  79943. (function (BABYLON) {
  79944. /**
  79945. * Vive Controller
  79946. */
  79947. var ViveController = /** @class */ (function (_super) {
  79948. __extends(ViveController, _super);
  79949. /**
  79950. * Creates a new ViveController from a gamepad
  79951. * @param vrGamepad the gamepad that the controller should be created from
  79952. */
  79953. function ViveController(vrGamepad) {
  79954. var _this = _super.call(this, vrGamepad) || this;
  79955. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  79956. _this._invertLeftStickY = true;
  79957. return _this;
  79958. }
  79959. /**
  79960. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79961. * @param scene scene in which to add meshes
  79962. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79963. */
  79964. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79965. var _this = this;
  79966. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  79967. /*
  79968. Parent Mesh name: ViveWand
  79969. - body
  79970. - r_gripper
  79971. - l_gripper
  79972. - menu_button
  79973. - system_button
  79974. - trackpad
  79975. - trigger
  79976. - LED
  79977. */
  79978. _this._defaultModel = newMeshes[1];
  79979. _this.attachToMesh(_this._defaultModel);
  79980. if (meshLoaded) {
  79981. meshLoaded(_this._defaultModel);
  79982. }
  79983. });
  79984. };
  79985. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  79986. /**
  79987. * Fired when the left button on this controller is modified
  79988. */
  79989. get: function () {
  79990. return this.onMainButtonStateChangedObservable;
  79991. },
  79992. enumerable: true,
  79993. configurable: true
  79994. });
  79995. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  79996. /**
  79997. * Fired when the right button on this controller is modified
  79998. */
  79999. get: function () {
  80000. return this.onMainButtonStateChangedObservable;
  80001. },
  80002. enumerable: true,
  80003. configurable: true
  80004. });
  80005. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  80006. /**
  80007. * Fired when the menu button on this controller is modified
  80008. */
  80009. get: function () {
  80010. return this.onSecondaryButtonStateChangedObservable;
  80011. },
  80012. enumerable: true,
  80013. configurable: true
  80014. });
  80015. /**
  80016. * Called once for each button that changed state since the last frame
  80017. * Vive mapping:
  80018. * 0: touchpad
  80019. * 1: trigger
  80020. * 2: left AND right buttons
  80021. * 3: menu button
  80022. * @param buttonIdx Which button index changed
  80023. * @param state New state of the button
  80024. * @param changes Which properties on the state changed since last frame
  80025. */
  80026. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80027. var notifyObject = state; //{ state: state, changes: changes };
  80028. switch (buttonIdx) {
  80029. case 0:
  80030. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80031. return;
  80032. case 1: // index trigger
  80033. if (this._defaultModel) {
  80034. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80035. }
  80036. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80037. return;
  80038. case 2: // left AND right button
  80039. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80040. return;
  80041. case 3:
  80042. if (this._defaultModel) {
  80043. if (notifyObject.pressed) {
  80044. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80045. }
  80046. else {
  80047. (this._defaultModel.getChildren()[2]).position.y = 0;
  80048. }
  80049. }
  80050. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80051. return;
  80052. }
  80053. };
  80054. /**
  80055. * Base Url for the controller model.
  80056. */
  80057. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80058. /**
  80059. * File name for the controller model.
  80060. */
  80061. ViveController.MODEL_FILENAME = 'wand.babylon';
  80062. return ViveController;
  80063. }(BABYLON.WebVRController));
  80064. BABYLON.ViveController = ViveController;
  80065. })(BABYLON || (BABYLON = {}));
  80066. //# sourceMappingURL=babylon.viveController.js.map
  80067. var BABYLON;
  80068. (function (BABYLON) {
  80069. /**
  80070. * Generic Controller
  80071. */
  80072. var GenericController = /** @class */ (function (_super) {
  80073. __extends(GenericController, _super);
  80074. /**
  80075. * Creates a new GenericController from a gamepad
  80076. * @param vrGamepad the gamepad that the controller should be created from
  80077. */
  80078. function GenericController(vrGamepad) {
  80079. return _super.call(this, vrGamepad) || this;
  80080. }
  80081. /**
  80082. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80083. * @param scene scene in which to add meshes
  80084. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80085. */
  80086. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80087. var _this = this;
  80088. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80089. _this._defaultModel = newMeshes[1];
  80090. _this.attachToMesh(_this._defaultModel);
  80091. if (meshLoaded) {
  80092. meshLoaded(_this._defaultModel);
  80093. }
  80094. });
  80095. };
  80096. /**
  80097. * Called once for each button that changed state since the last frame
  80098. * @param buttonIdx Which button index changed
  80099. * @param state New state of the button
  80100. * @param changes Which properties on the state changed since last frame
  80101. */
  80102. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80103. console.log("Button id: " + buttonIdx + "state: ");
  80104. console.dir(state);
  80105. };
  80106. /**
  80107. * Base Url for the controller model.
  80108. */
  80109. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80110. /**
  80111. * File name for the controller model.
  80112. */
  80113. GenericController.MODEL_FILENAME = 'generic.babylon';
  80114. return GenericController;
  80115. }(BABYLON.WebVRController));
  80116. BABYLON.GenericController = GenericController;
  80117. })(BABYLON || (BABYLON = {}));
  80118. //# sourceMappingURL=babylon.genericController.js.map
  80119. var BABYLON;
  80120. (function (BABYLON) {
  80121. /**
  80122. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80123. */
  80124. var LoadedMeshInfo = /** @class */ (function () {
  80125. function LoadedMeshInfo() {
  80126. /**
  80127. * Map of the button meshes contained in the controller
  80128. */
  80129. this.buttonMeshes = {};
  80130. /**
  80131. * Map of the axis meshes contained in the controller
  80132. */
  80133. this.axisMeshes = {};
  80134. }
  80135. return LoadedMeshInfo;
  80136. }());
  80137. /**
  80138. * Defines the WindowsMotionController object that the state of the windows motion controller
  80139. */
  80140. var WindowsMotionController = /** @class */ (function (_super) {
  80141. __extends(WindowsMotionController, _super);
  80142. /**
  80143. * Creates a new WindowsMotionController from a gamepad
  80144. * @param vrGamepad the gamepad that the controller should be created from
  80145. */
  80146. function WindowsMotionController(vrGamepad) {
  80147. var _this = _super.call(this, vrGamepad) || this;
  80148. _this._mapping = {
  80149. // Semantic button names
  80150. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80151. // A mapping of the button name to glTF model node name
  80152. // that should be transformed by button value.
  80153. buttonMeshNames: {
  80154. 'trigger': 'SELECT',
  80155. 'menu': 'MENU',
  80156. 'grip': 'GRASP',
  80157. 'thumbstick': 'THUMBSTICK_PRESS',
  80158. 'trackpad': 'TOUCHPAD_PRESS'
  80159. },
  80160. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80161. buttonObservableNames: {
  80162. 'trigger': 'onTriggerStateChangedObservable',
  80163. 'menu': 'onSecondaryButtonStateChangedObservable',
  80164. 'grip': 'onMainButtonStateChangedObservable',
  80165. 'thumbstick': 'onPadStateChangedObservable',
  80166. 'trackpad': 'onTrackpadChangedObservable'
  80167. },
  80168. // A mapping of the axis name to glTF model node name
  80169. // that should be transformed by axis value.
  80170. // This array mirrors the browserGamepad.axes array, such that
  80171. // the mesh corresponding to axis 0 is in this array index 0.
  80172. axisMeshNames: [
  80173. 'THUMBSTICK_X',
  80174. 'THUMBSTICK_Y',
  80175. 'TOUCHPAD_TOUCH_X',
  80176. 'TOUCHPAD_TOUCH_Y'
  80177. ],
  80178. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80179. };
  80180. /**
  80181. * Fired when the trackpad on this controller is clicked
  80182. */
  80183. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80184. /**
  80185. * Fired when the trackpad on this controller is modified
  80186. */
  80187. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80188. /**
  80189. * The current x and y values of this controller's trackpad
  80190. */
  80191. _this.trackpad = { x: 0, y: 0 };
  80192. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80193. _this._loadedMeshInfo = null;
  80194. return _this;
  80195. }
  80196. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80197. /**
  80198. * Fired when the trigger on this controller is modified
  80199. */
  80200. get: function () {
  80201. return this.onTriggerStateChangedObservable;
  80202. },
  80203. enumerable: true,
  80204. configurable: true
  80205. });
  80206. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80207. /**
  80208. * Fired when the menu button on this controller is modified
  80209. */
  80210. get: function () {
  80211. return this.onSecondaryButtonStateChangedObservable;
  80212. },
  80213. enumerable: true,
  80214. configurable: true
  80215. });
  80216. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80217. /**
  80218. * Fired when the grip button on this controller is modified
  80219. */
  80220. get: function () {
  80221. return this.onMainButtonStateChangedObservable;
  80222. },
  80223. enumerable: true,
  80224. configurable: true
  80225. });
  80226. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80227. /**
  80228. * Fired when the thumbstick button on this controller is modified
  80229. */
  80230. get: function () {
  80231. return this.onPadStateChangedObservable;
  80232. },
  80233. enumerable: true,
  80234. configurable: true
  80235. });
  80236. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80237. /**
  80238. * Fired when the touchpad button on this controller is modified
  80239. */
  80240. get: function () {
  80241. return this.onTrackpadChangedObservable;
  80242. },
  80243. enumerable: true,
  80244. configurable: true
  80245. });
  80246. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80247. /**
  80248. * Fired when the touchpad values on this controller are modified
  80249. */
  80250. get: function () {
  80251. return this.onTrackpadValuesChangedObservable;
  80252. },
  80253. enumerable: true,
  80254. configurable: true
  80255. });
  80256. WindowsMotionController.prototype._updateTrackpad = function () {
  80257. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80258. this.trackpad.x = this.browserGamepad["axes"][2];
  80259. this.trackpad.y = this.browserGamepad["axes"][3];
  80260. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80261. }
  80262. };
  80263. /**
  80264. * Called once per frame by the engine.
  80265. */
  80266. WindowsMotionController.prototype.update = function () {
  80267. _super.prototype.update.call(this);
  80268. if (this.browserGamepad.axes) {
  80269. this._updateTrackpad();
  80270. // Only need to animate axes if there is a loaded mesh
  80271. if (this._loadedMeshInfo) {
  80272. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80273. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80274. }
  80275. }
  80276. }
  80277. };
  80278. /**
  80279. * Called once for each button that changed state since the last frame
  80280. * @param buttonIdx Which button index changed
  80281. * @param state New state of the button
  80282. * @param changes Which properties on the state changed since last frame
  80283. */
  80284. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80285. var buttonName = this._mapping.buttons[buttonIdx];
  80286. if (!buttonName) {
  80287. return;
  80288. }
  80289. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80290. this._updateTrackpad();
  80291. // Only emit events for buttons that we know how to map from index to name
  80292. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80293. if (observable) {
  80294. observable.notifyObservers(state);
  80295. }
  80296. this._lerpButtonTransform(buttonName, state.value);
  80297. };
  80298. /**
  80299. * Moves the buttons on the controller mesh based on their current state
  80300. * @param buttonName the name of the button to move
  80301. * @param buttonValue the value of the button which determines the buttons new position
  80302. */
  80303. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80304. // If there is no loaded mesh, there is nothing to transform.
  80305. if (!this._loadedMeshInfo) {
  80306. return;
  80307. }
  80308. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80309. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80310. return;
  80311. }
  80312. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80313. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80314. };
  80315. /**
  80316. * Moves the axis on the controller mesh based on its current state
  80317. * @param axis the index of the axis
  80318. * @param axisValue the value of the axis which determines the meshes new position
  80319. * @hidden
  80320. */
  80321. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80322. if (!this._loadedMeshInfo) {
  80323. return;
  80324. }
  80325. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80326. if (!meshInfo) {
  80327. return;
  80328. }
  80329. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80330. return;
  80331. }
  80332. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80333. var lerpValue = axisValue * 0.5 + 0.5;
  80334. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80335. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80336. };
  80337. /**
  80338. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80339. * @param scene scene in which to add meshes
  80340. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80341. */
  80342. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80343. var _this = this;
  80344. if (forceDefault === void 0) { forceDefault = false; }
  80345. var path;
  80346. var filename;
  80347. // Checking if GLB loader is present
  80348. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80349. // Determine the device specific folder based on the ID suffix
  80350. var device = 'default';
  80351. if (this.id && !forceDefault) {
  80352. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  80353. device = ((match && match[0]) || device);
  80354. }
  80355. // Hand
  80356. if (this.hand === 'left') {
  80357. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  80358. }
  80359. else { // Right is the default if no hand is specified
  80360. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  80361. }
  80362. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  80363. }
  80364. else {
  80365. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  80366. path = BABYLON.GenericController.MODEL_BASE_URL;
  80367. filename = BABYLON.GenericController.MODEL_FILENAME;
  80368. }
  80369. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  80370. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  80371. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  80372. if (!_this._loadedMeshInfo) {
  80373. return;
  80374. }
  80375. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  80376. _this.attachToMesh(_this._defaultModel);
  80377. if (meshLoaded) {
  80378. meshLoaded(_this._defaultModel);
  80379. }
  80380. }, null, function (scene, message) {
  80381. BABYLON.Tools.Log(message);
  80382. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  80383. if (!forceDefault) {
  80384. _this.initControllerMesh(scene, meshLoaded, true);
  80385. }
  80386. });
  80387. };
  80388. /**
  80389. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  80390. * can be transformed by button presses and axes values, based on this._mapping.
  80391. *
  80392. * @param scene scene in which the meshes exist
  80393. * @param meshes list of meshes that make up the controller model to process
  80394. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  80395. */
  80396. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  80397. var loadedMeshInfo = null;
  80398. // Create a new mesh to contain the glTF hierarchy
  80399. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  80400. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  80401. var childMesh = null;
  80402. for (var i = 0; i < meshes.length; i++) {
  80403. var mesh = meshes[i];
  80404. if (!mesh.parent) {
  80405. // Exclude controller meshes from picking results
  80406. mesh.isPickable = false;
  80407. // Handle root node, attach to the new parentMesh
  80408. childMesh = mesh;
  80409. break;
  80410. }
  80411. }
  80412. if (childMesh) {
  80413. childMesh.setParent(parentMesh);
  80414. // Create our mesh info. Note that this method will always return non-null.
  80415. loadedMeshInfo = this.createMeshInfo(parentMesh);
  80416. }
  80417. else {
  80418. BABYLON.Tools.Warn('Could not find root node in model file.');
  80419. }
  80420. return loadedMeshInfo;
  80421. };
  80422. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  80423. var loadedMeshInfo = new LoadedMeshInfo();
  80424. var i;
  80425. loadedMeshInfo.rootNode = rootNode;
  80426. // Reset the caches
  80427. loadedMeshInfo.buttonMeshes = {};
  80428. loadedMeshInfo.axisMeshes = {};
  80429. // Button Meshes
  80430. for (i = 0; i < this._mapping.buttons.length; i++) {
  80431. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  80432. if (!buttonMeshName) {
  80433. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  80434. continue;
  80435. }
  80436. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  80437. if (!buttonMesh) {
  80438. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  80439. continue;
  80440. }
  80441. var buttonMeshInfo = {
  80442. index: i,
  80443. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  80444. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  80445. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  80446. };
  80447. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  80448. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  80449. }
  80450. else {
  80451. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  80452. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  80453. '(VALUE: ' + !!buttonMeshInfo.value +
  80454. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  80455. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  80456. ')');
  80457. }
  80458. }
  80459. // Axis Meshes
  80460. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  80461. var axisMeshName = this._mapping.axisMeshNames[i];
  80462. if (!axisMeshName) {
  80463. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  80464. continue;
  80465. }
  80466. var axisMesh = getChildByName(rootNode, axisMeshName);
  80467. if (!axisMesh) {
  80468. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  80469. continue;
  80470. }
  80471. var axisMeshInfo = {
  80472. index: i,
  80473. value: getImmediateChildByName(axisMesh, 'VALUE'),
  80474. min: getImmediateChildByName(axisMesh, 'MIN'),
  80475. max: getImmediateChildByName(axisMesh, 'MAX')
  80476. };
  80477. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  80478. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  80479. }
  80480. else {
  80481. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  80482. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  80483. '(VALUE: ' + !!axisMeshInfo.value +
  80484. ', MIN: ' + !!axisMeshInfo.min +
  80485. ', MAX:' + !!axisMeshInfo.max +
  80486. ')');
  80487. }
  80488. }
  80489. // Pointing Ray
  80490. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  80491. if (!loadedMeshInfo.pointingPoseNode) {
  80492. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  80493. }
  80494. else {
  80495. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  80496. }
  80497. return loadedMeshInfo;
  80498. // Look through all children recursively. This will return null if no mesh exists with the given name.
  80499. function getChildByName(node, name) {
  80500. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  80501. }
  80502. // Look through only immediate children. This will return null if no mesh exists with the given name.
  80503. function getImmediateChildByName(node, name) {
  80504. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  80505. }
  80506. };
  80507. /**
  80508. * Gets the ray of the controller in the direction the controller is pointing
  80509. * @param length the length the resulting ray should be
  80510. * @returns a ray in the direction the controller is pointing
  80511. */
  80512. WindowsMotionController.prototype.getForwardRay = function (length) {
  80513. if (length === void 0) { length = 100; }
  80514. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  80515. return _super.prototype.getForwardRay.call(this, length);
  80516. }
  80517. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  80518. var origin = m.getTranslation();
  80519. var forward = new BABYLON.Vector3(0, 0, -1);
  80520. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80521. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80522. return new BABYLON.Ray(origin, direction, length);
  80523. };
  80524. /**
  80525. * Disposes of the controller
  80526. */
  80527. WindowsMotionController.prototype.dispose = function () {
  80528. _super.prototype.dispose.call(this);
  80529. this.onTrackpadChangedObservable.clear();
  80530. };
  80531. /**
  80532. * The base url used to load the left and right controller models
  80533. */
  80534. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  80535. /**
  80536. * The name of the left controller model file
  80537. */
  80538. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  80539. /**
  80540. * The name of the right controller model file
  80541. */
  80542. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  80543. /**
  80544. * The controller name prefix for this controller type
  80545. */
  80546. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  80547. /**
  80548. * The controller id pattern for this controller type
  80549. */
  80550. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  80551. return WindowsMotionController;
  80552. }(BABYLON.WebVRController));
  80553. BABYLON.WindowsMotionController = WindowsMotionController;
  80554. })(BABYLON || (BABYLON = {}));
  80555. //# sourceMappingURL=babylon.windowsMotionController.js.map
  80556. var BABYLON;
  80557. (function (BABYLON) {
  80558. /**
  80559. * Gear VR Controller
  80560. */
  80561. var GearVRController = /** @class */ (function (_super) {
  80562. __extends(GearVRController, _super);
  80563. /**
  80564. * Creates a new GearVRController from a gamepad
  80565. * @param vrGamepad the gamepad that the controller should be created from
  80566. */
  80567. function GearVRController(vrGamepad) {
  80568. var _this = _super.call(this, vrGamepad) || this;
  80569. _this._buttonIndexToObservableNameMap = [
  80570. 'onTrackpadChangedObservable',
  80571. 'onTriggerStateChangedObservable' // Trigger
  80572. ];
  80573. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  80574. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  80575. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  80576. _this._disableTrackPosition(_this._calculatedPosition);
  80577. return _this;
  80578. }
  80579. /**
  80580. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80581. * @param scene scene in which to add meshes
  80582. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80583. */
  80584. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80585. var _this = this;
  80586. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  80587. // Offset the controller so it will rotate around the users wrist
  80588. var mesh = new BABYLON.Mesh("", scene);
  80589. newMeshes[1].parent = mesh;
  80590. newMeshes[1].position.z = -0.15;
  80591. _this._defaultModel = mesh;
  80592. _this.attachToMesh(_this._defaultModel);
  80593. if (meshLoaded) {
  80594. meshLoaded(_this._defaultModel);
  80595. }
  80596. });
  80597. };
  80598. /**
  80599. * Called once for each button that changed state since the last frame
  80600. * @param buttonIdx Which button index changed
  80601. * @param state New state of the button
  80602. * @param changes Which properties on the state changed since last frame
  80603. */
  80604. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80605. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  80606. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  80607. // Only emit events for buttons that we know how to map from index to observable
  80608. var observable = this[observableName];
  80609. if (observable) {
  80610. observable.notifyObservers(state);
  80611. }
  80612. }
  80613. };
  80614. /**
  80615. * Base Url for the controller model.
  80616. */
  80617. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80618. /**
  80619. * File name for the controller model.
  80620. */
  80621. GearVRController.MODEL_FILENAME = 'generic.babylon';
  80622. /**
  80623. * Gamepad Id prefix used to identify this controller.
  80624. */
  80625. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  80626. return GearVRController;
  80627. }(BABYLON.WebVRController));
  80628. BABYLON.GearVRController = GearVRController;
  80629. })(BABYLON || (BABYLON = {}));
  80630. //# sourceMappingURL=babylon.gearVRController.js.map
  80631. var BABYLON;
  80632. (function (BABYLON) {
  80633. /**
  80634. * Google Daydream controller
  80635. */
  80636. var DaydreamController = /** @class */ (function (_super) {
  80637. __extends(DaydreamController, _super);
  80638. /**
  80639. * Creates a new DaydreamController from a gamepad
  80640. * @param vrGamepad the gamepad that the controller should be created from
  80641. */
  80642. function DaydreamController(vrGamepad) {
  80643. var _this = _super.call(this, vrGamepad) || this;
  80644. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  80645. return _this;
  80646. }
  80647. /**
  80648. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80649. * @param scene scene in which to add meshes
  80650. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80651. */
  80652. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80653. var _this = this;
  80654. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  80655. _this._defaultModel = newMeshes[1];
  80656. _this.attachToMesh(_this._defaultModel);
  80657. if (meshLoaded) {
  80658. meshLoaded(_this._defaultModel);
  80659. }
  80660. });
  80661. };
  80662. /**
  80663. * Called once for each button that changed state since the last frame
  80664. * @param buttonIdx Which button index changed
  80665. * @param state New state of the button
  80666. * @param changes Which properties on the state changed since last frame
  80667. */
  80668. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80669. // Daydream controller only has 1 GamepadButton (on the trackpad).
  80670. if (buttonIdx === 0) {
  80671. var observable = this.onTriggerStateChangedObservable;
  80672. if (observable) {
  80673. observable.notifyObservers(state);
  80674. }
  80675. }
  80676. else {
  80677. // If the app or home buttons are ever made available
  80678. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  80679. }
  80680. };
  80681. /**
  80682. * Base Url for the controller model.
  80683. */
  80684. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80685. /**
  80686. * File name for the controller model.
  80687. */
  80688. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  80689. /**
  80690. * Gamepad Id prefix used to identify Daydream Controller.
  80691. */
  80692. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  80693. return DaydreamController;
  80694. }(BABYLON.WebVRController));
  80695. BABYLON.DaydreamController = DaydreamController;
  80696. })(BABYLON || (BABYLON = {}));
  80697. //# sourceMappingURL=babylon.daydreamController.js.map
  80698. var BABYLON;
  80699. (function (BABYLON) {
  80700. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  80701. get: function () {
  80702. if (!this._gamepadManager) {
  80703. this._gamepadManager = new BABYLON.GamepadManager(this);
  80704. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  80705. if (!component) {
  80706. component = new GamepadSystemSceneComponent(this);
  80707. this._addComponent(component);
  80708. }
  80709. }
  80710. return this._gamepadManager;
  80711. },
  80712. enumerable: true,
  80713. configurable: true
  80714. });
  80715. /**
  80716. * Adds a gamepad to the free camera inputs manager
  80717. */
  80718. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  80719. this.add(new BABYLON.FreeCameraGamepadInput());
  80720. return this;
  80721. };
  80722. /**
  80723. * Adds a gamepad to the arc rotate camera inputs manager
  80724. */
  80725. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  80726. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  80727. return this;
  80728. };
  80729. /**
  80730. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  80731. */
  80732. var GamepadSystemSceneComponent = /** @class */ (function () {
  80733. /**
  80734. * Creates a new instance of the component for the given scene
  80735. * @param scene Defines the scene to register the component in
  80736. */
  80737. function GamepadSystemSceneComponent(scene) {
  80738. /**
  80739. * The component name helpfull to identify the component in the list of scene components.
  80740. */
  80741. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  80742. this.scene = scene;
  80743. }
  80744. /**
  80745. * Registers the component in a given scene
  80746. */
  80747. GamepadSystemSceneComponent.prototype.register = function () {
  80748. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  80749. };
  80750. /**
  80751. * Rebuilds the elements related to this component in case of
  80752. * context lost for instance.
  80753. */
  80754. GamepadSystemSceneComponent.prototype.rebuild = function () {
  80755. // Nothing to do for gamepads
  80756. };
  80757. /**
  80758. * Disposes the component and the associated ressources
  80759. */
  80760. GamepadSystemSceneComponent.prototype.dispose = function () {
  80761. var gamepadManager = this.scene._gamepadManager;
  80762. if (gamepadManager) {
  80763. gamepadManager.dispose();
  80764. this.scene._gamepadManager = null;
  80765. }
  80766. };
  80767. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  80768. var gamepadManager = this.scene._gamepadManager;
  80769. if (gamepadManager && gamepadManager._isMonitoring) {
  80770. gamepadManager._checkGamepadsStatus();
  80771. }
  80772. };
  80773. return GamepadSystemSceneComponent;
  80774. }());
  80775. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  80776. })(BABYLON || (BABYLON = {}));
  80777. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  80778. var BABYLON;
  80779. (function (BABYLON) {
  80780. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  80781. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  80782. });
  80783. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  80784. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  80785. });
  80786. /**
  80787. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  80788. * an arc rotate version arcFollowCamera are available.
  80789. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80790. */
  80791. var FollowCamera = /** @class */ (function (_super) {
  80792. __extends(FollowCamera, _super);
  80793. /**
  80794. * Instantiates the follow camera.
  80795. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80796. * @param name Define the name of the camera in the scene
  80797. * @param position Define the position of the camera
  80798. * @param scene Define the scene the camera belong to
  80799. * @param lockedTarget Define the target of the camera
  80800. */
  80801. function FollowCamera(name, position, scene, lockedTarget) {
  80802. if (lockedTarget === void 0) { lockedTarget = null; }
  80803. var _this = _super.call(this, name, position, scene) || this;
  80804. /**
  80805. * Distance the follow camera should follow an object at
  80806. */
  80807. _this.radius = 12;
  80808. /**
  80809. * Define a rotation offset between the camera and the object it follows
  80810. */
  80811. _this.rotationOffset = 0;
  80812. /**
  80813. * Define a height offset between the camera and the object it follows.
  80814. * It can help following an object from the top (like a car chaing a plane)
  80815. */
  80816. _this.heightOffset = 4;
  80817. /**
  80818. * Define how fast the camera can accelerate to follow it s target.
  80819. */
  80820. _this.cameraAcceleration = 0.05;
  80821. /**
  80822. * Define the speed limit of the camera following an object.
  80823. */
  80824. _this.maxCameraSpeed = 20;
  80825. _this.lockedTarget = lockedTarget;
  80826. return _this;
  80827. }
  80828. FollowCamera.prototype._follow = function (cameraTarget) {
  80829. if (!cameraTarget)
  80830. return;
  80831. var yRotation;
  80832. if (cameraTarget.rotationQuaternion) {
  80833. var rotMatrix = new BABYLON.Matrix();
  80834. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  80835. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  80836. }
  80837. else {
  80838. yRotation = cameraTarget.rotation.y;
  80839. }
  80840. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  80841. var targetPosition = cameraTarget.getAbsolutePosition();
  80842. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  80843. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  80844. var dx = targetX - this.position.x;
  80845. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  80846. var dz = (targetZ) - this.position.z;
  80847. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  80848. var vy = dy * this.cameraAcceleration;
  80849. var vz = dz * this.cameraAcceleration * 2;
  80850. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  80851. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80852. }
  80853. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  80854. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80855. }
  80856. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  80857. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80858. }
  80859. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  80860. this.setTarget(targetPosition);
  80861. };
  80862. /** @hidden */
  80863. FollowCamera.prototype._checkInputs = function () {
  80864. _super.prototype._checkInputs.call(this);
  80865. if (this.lockedTarget) {
  80866. this._follow(this.lockedTarget);
  80867. }
  80868. };
  80869. /**
  80870. * Gets the camera class name.
  80871. * @returns the class name
  80872. */
  80873. FollowCamera.prototype.getClassName = function () {
  80874. return "FollowCamera";
  80875. };
  80876. __decorate([
  80877. BABYLON.serialize()
  80878. ], FollowCamera.prototype, "radius", void 0);
  80879. __decorate([
  80880. BABYLON.serialize()
  80881. ], FollowCamera.prototype, "rotationOffset", void 0);
  80882. __decorate([
  80883. BABYLON.serialize()
  80884. ], FollowCamera.prototype, "heightOffset", void 0);
  80885. __decorate([
  80886. BABYLON.serialize()
  80887. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  80888. __decorate([
  80889. BABYLON.serialize()
  80890. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  80891. __decorate([
  80892. BABYLON.serializeAsMeshReference("lockedTargetId")
  80893. ], FollowCamera.prototype, "lockedTarget", void 0);
  80894. return FollowCamera;
  80895. }(BABYLON.TargetCamera));
  80896. BABYLON.FollowCamera = FollowCamera;
  80897. /**
  80898. * Arc Rotate version of the follow camera.
  80899. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  80900. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80901. */
  80902. var ArcFollowCamera = /** @class */ (function (_super) {
  80903. __extends(ArcFollowCamera, _super);
  80904. /**
  80905. * Instantiates a new ArcFollowCamera
  80906. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80907. * @param name Define the name of the camera
  80908. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  80909. * @param beta Define the rotation angle of the camera around the elevation axis
  80910. * @param radius Define the radius of the camera from its target point
  80911. * @param target Define the target of the camera
  80912. * @param scene Define the scene the camera belongs to
  80913. */
  80914. function ArcFollowCamera(name,
  80915. /** The longitudinal angle of the camera */
  80916. alpha,
  80917. /** The latitudinal angle of the camera */
  80918. beta,
  80919. /** The radius of the camera from its target */
  80920. radius,
  80921. /** Define the camera target (the messh it should follow) */
  80922. target, scene) {
  80923. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  80924. _this.alpha = alpha;
  80925. _this.beta = beta;
  80926. _this.radius = radius;
  80927. _this.target = target;
  80928. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  80929. _this._follow();
  80930. return _this;
  80931. }
  80932. ArcFollowCamera.prototype._follow = function () {
  80933. if (!this.target) {
  80934. return;
  80935. }
  80936. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  80937. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  80938. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  80939. var targetPosition = this.target.getAbsolutePosition();
  80940. this.position = targetPosition.add(this._cartesianCoordinates);
  80941. this.setTarget(targetPosition);
  80942. };
  80943. /** @hidden */
  80944. ArcFollowCamera.prototype._checkInputs = function () {
  80945. _super.prototype._checkInputs.call(this);
  80946. this._follow();
  80947. };
  80948. /**
  80949. * Returns the class name of the object.
  80950. * It is mostly used internally for serialization purposes.
  80951. */
  80952. ArcFollowCamera.prototype.getClassName = function () {
  80953. return "ArcFollowCamera";
  80954. };
  80955. return ArcFollowCamera;
  80956. }(BABYLON.TargetCamera));
  80957. BABYLON.ArcFollowCamera = ArcFollowCamera;
  80958. })(BABYLON || (BABYLON = {}));
  80959. //# sourceMappingURL=babylon.followCamera.js.map
  80960. var BABYLON;
  80961. (function (BABYLON) {
  80962. /**
  80963. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  80964. * which still works and will still be found in many Playgrounds.
  80965. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80966. */
  80967. var UniversalCamera = /** @class */ (function (_super) {
  80968. __extends(UniversalCamera, _super);
  80969. /**
  80970. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  80971. * which still works and will still be found in many Playgrounds.
  80972. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80973. * @param name Define the name of the camera in the scene
  80974. * @param position Define the start position of the camera in the scene
  80975. * @param scene Define the scene the camera belongs to
  80976. */
  80977. function UniversalCamera(name, position, scene) {
  80978. var _this = _super.call(this, name, position, scene) || this;
  80979. _this.inputs.addGamepad();
  80980. return _this;
  80981. }
  80982. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  80983. /**
  80984. * Defines the gamepad rotation sensiblity.
  80985. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80986. */
  80987. get: function () {
  80988. var gamepad = this.inputs.attached["gamepad"];
  80989. if (gamepad)
  80990. return gamepad.gamepadAngularSensibility;
  80991. return 0;
  80992. },
  80993. set: function (value) {
  80994. var gamepad = this.inputs.attached["gamepad"];
  80995. if (gamepad)
  80996. gamepad.gamepadAngularSensibility = value;
  80997. },
  80998. enumerable: true,
  80999. configurable: true
  81000. });
  81001. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  81002. /**
  81003. * Defines the gamepad move sensiblity.
  81004. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81005. */
  81006. get: function () {
  81007. var gamepad = this.inputs.attached["gamepad"];
  81008. if (gamepad)
  81009. return gamepad.gamepadMoveSensibility;
  81010. return 0;
  81011. },
  81012. set: function (value) {
  81013. var gamepad = this.inputs.attached["gamepad"];
  81014. if (gamepad)
  81015. gamepad.gamepadMoveSensibility = value;
  81016. },
  81017. enumerable: true,
  81018. configurable: true
  81019. });
  81020. /**
  81021. * Gets the current object class name.
  81022. * @return the class name
  81023. */
  81024. UniversalCamera.prototype.getClassName = function () {
  81025. return "UniversalCamera";
  81026. };
  81027. return UniversalCamera;
  81028. }(BABYLON.TouchCamera));
  81029. BABYLON.UniversalCamera = UniversalCamera;
  81030. })(BABYLON || (BABYLON = {}));
  81031. //# sourceMappingURL=babylon.universalCamera.js.map
  81032. var BABYLON;
  81033. (function (BABYLON) {
  81034. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81035. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81036. });
  81037. /**
  81038. * This represents a FPS type of camera. This is only here for back compat purpose.
  81039. * Please use the UniversalCamera instead as both are identical.
  81040. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81041. */
  81042. var GamepadCamera = /** @class */ (function (_super) {
  81043. __extends(GamepadCamera, _super);
  81044. /**
  81045. * Instantiates a new Gamepad Camera
  81046. * This represents a FPS type of camera. This is only here for back compat purpose.
  81047. * Please use the UniversalCamera instead as both are identical.
  81048. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81049. * @param name Define the name of the camera in the scene
  81050. * @param position Define the start position of the camera in the scene
  81051. * @param scene Define the scene the camera belongs to
  81052. */
  81053. function GamepadCamera(name, position, scene) {
  81054. return _super.call(this, name, position, scene) || this;
  81055. }
  81056. /**
  81057. * Gets the current object class name.
  81058. * @return the class name
  81059. */
  81060. GamepadCamera.prototype.getClassName = function () {
  81061. return "GamepadCamera";
  81062. };
  81063. return GamepadCamera;
  81064. }(BABYLON.UniversalCamera));
  81065. BABYLON.GamepadCamera = GamepadCamera;
  81066. })(BABYLON || (BABYLON = {}));
  81067. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81068. var BABYLON;
  81069. (function (BABYLON) {
  81070. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81071. function PostProcessRenderPipelineManager() {
  81072. this._renderPipelines = {};
  81073. }
  81074. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81075. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81076. };
  81077. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81078. if (unique === void 0) { unique = false; }
  81079. var renderPipeline = this._renderPipelines[renderPipelineName];
  81080. if (!renderPipeline) {
  81081. return;
  81082. }
  81083. renderPipeline._attachCameras(cameras, unique);
  81084. };
  81085. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81086. var renderPipeline = this._renderPipelines[renderPipelineName];
  81087. if (!renderPipeline) {
  81088. return;
  81089. }
  81090. renderPipeline._detachCameras(cameras);
  81091. };
  81092. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81093. var renderPipeline = this._renderPipelines[renderPipelineName];
  81094. if (!renderPipeline) {
  81095. return;
  81096. }
  81097. renderPipeline._enableEffect(renderEffectName, cameras);
  81098. };
  81099. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81100. var renderPipeline = this._renderPipelines[renderPipelineName];
  81101. if (!renderPipeline) {
  81102. return;
  81103. }
  81104. renderPipeline._disableEffect(renderEffectName, cameras);
  81105. };
  81106. PostProcessRenderPipelineManager.prototype.update = function () {
  81107. for (var renderPipelineName in this._renderPipelines) {
  81108. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81109. var pipeline = this._renderPipelines[renderPipelineName];
  81110. if (!pipeline.isSupported) {
  81111. pipeline.dispose();
  81112. delete this._renderPipelines[renderPipelineName];
  81113. }
  81114. else {
  81115. pipeline._update();
  81116. }
  81117. }
  81118. }
  81119. };
  81120. /** @hidden */
  81121. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81122. for (var renderPipelineName in this._renderPipelines) {
  81123. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81124. var pipeline = this._renderPipelines[renderPipelineName];
  81125. pipeline._rebuild();
  81126. }
  81127. }
  81128. };
  81129. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81130. for (var renderPipelineName in this._renderPipelines) {
  81131. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81132. var pipeline = this._renderPipelines[renderPipelineName];
  81133. pipeline.dispose();
  81134. }
  81135. }
  81136. };
  81137. return PostProcessRenderPipelineManager;
  81138. }());
  81139. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81140. })(BABYLON || (BABYLON = {}));
  81141. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81142. var BABYLON;
  81143. (function (BABYLON) {
  81144. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81145. get: function () {
  81146. if (!this._postProcessRenderPipelineManager) {
  81147. // Register the G Buffer component to the scene.
  81148. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81149. if (!component) {
  81150. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81151. this._addComponent(component);
  81152. }
  81153. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81154. }
  81155. return this._postProcessRenderPipelineManager;
  81156. },
  81157. enumerable: true,
  81158. configurable: true
  81159. });
  81160. /**
  81161. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81162. */
  81163. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81164. /**
  81165. * Creates a new instance of the component for the given scene
  81166. * @param scene Defines the scene to register the component in
  81167. */
  81168. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81169. /**
  81170. * The component name helpfull to identify the component in the list of scene components.
  81171. */
  81172. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81173. this.scene = scene;
  81174. }
  81175. /**
  81176. * Registers the component in a given scene
  81177. */
  81178. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81179. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81180. };
  81181. /**
  81182. * Rebuilds the elements related to this component in case of
  81183. * context lost for instance.
  81184. */
  81185. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81186. if (this.scene._postProcessRenderPipelineManager) {
  81187. this.scene._postProcessRenderPipelineManager._rebuild();
  81188. }
  81189. };
  81190. /**
  81191. * Disposes the component and the associated ressources
  81192. */
  81193. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81194. if (this.scene._postProcessRenderPipelineManager) {
  81195. this.scene._postProcessRenderPipelineManager.dispose();
  81196. }
  81197. };
  81198. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81199. if (this.scene._postProcessRenderPipelineManager) {
  81200. this.scene._postProcessRenderPipelineManager.update();
  81201. }
  81202. };
  81203. return PostProcessRenderPipelineManagerSceneComponent;
  81204. }());
  81205. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81206. })(BABYLON || (BABYLON = {}));
  81207. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81208. var BABYLON;
  81209. (function (BABYLON) {
  81210. /**
  81211. * This represents a set of one or more post processes in Babylon.
  81212. * A post process can be used to apply a shader to a texture after it is rendered.
  81213. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81214. */
  81215. var PostProcessRenderEffect = /** @class */ (function () {
  81216. /**
  81217. * Instantiates a post process render effect.
  81218. * A post process can be used to apply a shader to a texture after it is rendered.
  81219. * @param engine The engine the effect is tied to
  81220. * @param name The name of the effect
  81221. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81222. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81223. */
  81224. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81225. this._name = name;
  81226. this._singleInstance = singleInstance || true;
  81227. this._getPostProcesses = getPostProcesses;
  81228. this._cameras = {};
  81229. this._indicesForCamera = {};
  81230. this._postProcesses = {};
  81231. }
  81232. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81233. /**
  81234. * Checks if all the post processes in the effect are supported.
  81235. */
  81236. get: function () {
  81237. for (var index in this._postProcesses) {
  81238. if (this._postProcesses.hasOwnProperty(index)) {
  81239. var pps = this._postProcesses[index];
  81240. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81241. if (!pps[ppIndex].isSupported) {
  81242. return false;
  81243. }
  81244. }
  81245. }
  81246. }
  81247. return true;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. /**
  81253. * Updates the current state of the effect
  81254. * @hidden
  81255. */
  81256. PostProcessRenderEffect.prototype._update = function () {
  81257. };
  81258. /**
  81259. * Attaches the effect on cameras
  81260. * @param cameras The camera to attach to.
  81261. * @hidden
  81262. */
  81263. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81264. var _this = this;
  81265. var cameraKey;
  81266. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81267. if (!cams) {
  81268. return;
  81269. }
  81270. for (var i = 0; i < cams.length; i++) {
  81271. var camera = cams[i];
  81272. var cameraName = camera.name;
  81273. if (this._singleInstance) {
  81274. cameraKey = 0;
  81275. }
  81276. else {
  81277. cameraKey = cameraName;
  81278. }
  81279. if (!this._postProcesses[cameraKey]) {
  81280. var postProcess = this._getPostProcesses();
  81281. if (postProcess) {
  81282. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81283. }
  81284. }
  81285. if (!this._indicesForCamera[cameraName]) {
  81286. this._indicesForCamera[cameraName] = [];
  81287. }
  81288. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81289. var index = camera.attachPostProcess(postProcess);
  81290. _this._indicesForCamera[cameraName].push(index);
  81291. });
  81292. if (!this._cameras[cameraName]) {
  81293. this._cameras[cameraName] = camera;
  81294. }
  81295. }
  81296. };
  81297. /**
  81298. * Detatches the effect on cameras
  81299. * @param cameras The camera to detatch from.
  81300. * @hidden
  81301. */
  81302. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81303. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81304. if (!cams) {
  81305. return;
  81306. }
  81307. for (var i = 0; i < cams.length; i++) {
  81308. var camera = cams[i];
  81309. var cameraName = camera.name;
  81310. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81311. camera.detachPostProcess(postProcess);
  81312. });
  81313. if (this._cameras[cameraName]) {
  81314. //this._indicesForCamera.splice(index, 1);
  81315. this._cameras[cameraName] = null;
  81316. }
  81317. }
  81318. };
  81319. /**
  81320. * Enables the effect on given cameras
  81321. * @param cameras The camera to enable.
  81322. * @hidden
  81323. */
  81324. PostProcessRenderEffect.prototype._enable = function (cameras) {
  81325. var _this = this;
  81326. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81327. if (!cams) {
  81328. return;
  81329. }
  81330. for (var i = 0; i < cams.length; i++) {
  81331. var camera = cams[i];
  81332. var cameraName = camera.name;
  81333. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  81334. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  81335. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81336. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  81337. });
  81338. }
  81339. }
  81340. }
  81341. };
  81342. /**
  81343. * Disables the effect on the given cameras
  81344. * @param cameras The camera to disable.
  81345. * @hidden
  81346. */
  81347. PostProcessRenderEffect.prototype._disable = function (cameras) {
  81348. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81349. if (!cams) {
  81350. return;
  81351. }
  81352. for (var i = 0; i < cams.length; i++) {
  81353. var camera = cams[i];
  81354. var cameraName = camera.name;
  81355. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81356. camera.detachPostProcess(postProcess);
  81357. });
  81358. }
  81359. };
  81360. /**
  81361. * Gets a list of the post processes contained in the effect.
  81362. * @param camera The camera to get the post processes on.
  81363. * @returns The list of the post processes in the effect.
  81364. */
  81365. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  81366. if (this._singleInstance) {
  81367. return this._postProcesses[0];
  81368. }
  81369. else {
  81370. if (!camera) {
  81371. return null;
  81372. }
  81373. return this._postProcesses[camera.name];
  81374. }
  81375. };
  81376. return PostProcessRenderEffect;
  81377. }());
  81378. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  81379. })(BABYLON || (BABYLON = {}));
  81380. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  81381. var BABYLON;
  81382. (function (BABYLON) {
  81383. var PostProcessRenderPipeline = /** @class */ (function () {
  81384. function PostProcessRenderPipeline(engine, name) {
  81385. this.engine = engine;
  81386. this._name = name;
  81387. this._renderEffects = {};
  81388. this._renderEffectsForIsolatedPass = new Array();
  81389. this._cameras = [];
  81390. }
  81391. PostProcessRenderPipeline.prototype.getClassName = function () {
  81392. return "PostProcessRenderPipeline";
  81393. };
  81394. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  81395. get: function () {
  81396. for (var renderEffectName in this._renderEffects) {
  81397. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81398. if (!this._renderEffects[renderEffectName].isSupported) {
  81399. return false;
  81400. }
  81401. }
  81402. }
  81403. return true;
  81404. },
  81405. enumerable: true,
  81406. configurable: true
  81407. });
  81408. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  81409. this._renderEffects[renderEffect._name] = renderEffect;
  81410. };
  81411. // private
  81412. /** @hidden */
  81413. PostProcessRenderPipeline.prototype._rebuild = function () {
  81414. };
  81415. /** @hidden */
  81416. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  81417. var renderEffects = this._renderEffects[renderEffectName];
  81418. if (!renderEffects) {
  81419. return;
  81420. }
  81421. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  81422. };
  81423. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  81424. var renderEffects = this._renderEffects[renderEffectName];
  81425. if (!renderEffects) {
  81426. return;
  81427. }
  81428. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  81429. };
  81430. /** @hidden */
  81431. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  81432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81433. if (!cams) {
  81434. return;
  81435. }
  81436. var indicesToDelete = [];
  81437. var i;
  81438. for (i = 0; i < cams.length; i++) {
  81439. var camera = cams[i];
  81440. var cameraName = camera.name;
  81441. if (this._cameras.indexOf(camera) === -1) {
  81442. this._cameras[cameraName] = camera;
  81443. }
  81444. else if (unique) {
  81445. indicesToDelete.push(i);
  81446. }
  81447. }
  81448. for (i = 0; i < indicesToDelete.length; i++) {
  81449. cameras.splice(indicesToDelete[i], 1);
  81450. }
  81451. for (var renderEffectName in this._renderEffects) {
  81452. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81453. this._renderEffects[renderEffectName]._attachCameras(cams);
  81454. }
  81455. }
  81456. };
  81457. /** @hidden */
  81458. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  81459. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81460. if (!cams) {
  81461. return;
  81462. }
  81463. for (var renderEffectName in this._renderEffects) {
  81464. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81465. this._renderEffects[renderEffectName]._detachCameras(cams);
  81466. }
  81467. }
  81468. for (var i = 0; i < cams.length; i++) {
  81469. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  81470. }
  81471. };
  81472. /** @hidden */
  81473. PostProcessRenderPipeline.prototype._update = function () {
  81474. for (var renderEffectName in this._renderEffects) {
  81475. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  81476. this._renderEffects[renderEffectName]._update();
  81477. }
  81478. }
  81479. for (var i = 0; i < this._cameras.length; i++) {
  81480. var cameraName = this._cameras[i].name;
  81481. if (this._renderEffectsForIsolatedPass[cameraName]) {
  81482. this._renderEffectsForIsolatedPass[cameraName]._update();
  81483. }
  81484. }
  81485. };
  81486. /** @hidden */
  81487. PostProcessRenderPipeline.prototype._reset = function () {
  81488. this._renderEffects = {};
  81489. this._renderEffectsForIsolatedPass = new Array();
  81490. };
  81491. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  81492. // 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)
  81493. var effectKeys = Object.keys(this._renderEffects);
  81494. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  81495. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  81496. if (postProcesses) {
  81497. postProcesses[0].samples = sampleCount;
  81498. return true;
  81499. }
  81500. }
  81501. return false;
  81502. };
  81503. PostProcessRenderPipeline.prototype.dispose = function () {
  81504. // Must be implemented by children
  81505. };
  81506. __decorate([
  81507. BABYLON.serialize()
  81508. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  81509. return PostProcessRenderPipeline;
  81510. }());
  81511. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  81512. })(BABYLON || (BABYLON = {}));
  81513. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  81514. var BABYLON;
  81515. (function (BABYLON) {
  81516. /**
  81517. * This represents a depth renderer in Babylon.
  81518. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  81519. */
  81520. var DepthRenderer = /** @class */ (function () {
  81521. /**
  81522. * Instantiates a depth renderer
  81523. * @param scene The scene the renderer belongs to
  81524. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  81525. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  81526. */
  81527. function DepthRenderer(scene, type, camera) {
  81528. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  81529. if (camera === void 0) { camera = null; }
  81530. var _this = this;
  81531. /**
  81532. * Specifiess that the depth renderer will only be used within
  81533. * the camera it is created for.
  81534. * This can help forcing its rendering during the camera processing.
  81535. */
  81536. this.useOnlyInActiveCamera = false;
  81537. this._scene = scene;
  81538. // Register the G Buffer component to the scene.
  81539. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  81540. if (!component) {
  81541. component = new BABYLON.DepthRendererSceneComponent(scene);
  81542. scene._addComponent(component);
  81543. }
  81544. this._camera = camera;
  81545. var engine = scene.getEngine();
  81546. // Render target
  81547. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  81548. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81549. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81550. this._depthMap.refreshRate = 1;
  81551. this._depthMap.renderParticles = false;
  81552. this._depthMap.renderList = null;
  81553. // Camera to get depth map from to support multiple concurrent cameras
  81554. this._depthMap.activeCamera = this._camera;
  81555. this._depthMap.ignoreCameraViewport = true;
  81556. this._depthMap.useCameraPostProcesses = false;
  81557. // set default depth value to 1.0 (far away)
  81558. this._depthMap.onClearObservable.add(function (engine) {
  81559. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  81560. });
  81561. // Custom render function
  81562. var renderSubMesh = function (subMesh) {
  81563. var mesh = subMesh.getRenderingMesh();
  81564. var scene = _this._scene;
  81565. var engine = scene.getEngine();
  81566. var material = subMesh.getMaterial();
  81567. if (!material) {
  81568. return;
  81569. }
  81570. // Culling and reverse (right handed system)
  81571. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81572. // Managing instances
  81573. var batch = mesh._getInstancesRenderList(subMesh._id);
  81574. if (batch.mustReturn) {
  81575. return;
  81576. }
  81577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81578. var camera = _this._camera || scene.activeCamera;
  81579. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  81580. engine.enableEffect(_this._effect);
  81581. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81582. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81583. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  81584. // Alpha test
  81585. if (material && material.needAlphaTesting()) {
  81586. var alphaTexture = material.getAlphaTestTexture();
  81587. if (alphaTexture) {
  81588. _this._effect.setTexture("diffuseSampler", alphaTexture);
  81589. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81590. }
  81591. }
  81592. // Bones
  81593. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81594. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81595. }
  81596. // Draw
  81597. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  81598. }
  81599. };
  81600. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81601. var index;
  81602. if (depthOnlySubMeshes.length) {
  81603. engine.setColorWrite(false);
  81604. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81605. renderSubMesh(depthOnlySubMeshes.data[index]);
  81606. }
  81607. engine.setColorWrite(true);
  81608. }
  81609. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81610. renderSubMesh(opaqueSubMeshes.data[index]);
  81611. }
  81612. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81613. renderSubMesh(alphaTestSubMeshes.data[index]);
  81614. }
  81615. };
  81616. }
  81617. /**
  81618. * Creates the depth rendering effect and checks if the effect is ready.
  81619. * @param subMesh The submesh to be used to render the depth map of
  81620. * @param useInstances If multiple world instances should be used
  81621. * @returns if the depth renderer is ready to render the depth map
  81622. */
  81623. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  81624. var material = subMesh.getMaterial();
  81625. if (material.disableDepthWrite) {
  81626. return false;
  81627. }
  81628. var defines = [];
  81629. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81630. var mesh = subMesh.getMesh();
  81631. // Alpha test
  81632. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  81633. defines.push("#define ALPHATEST");
  81634. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81635. attribs.push(BABYLON.VertexBuffer.UVKind);
  81636. defines.push("#define UV1");
  81637. }
  81638. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81639. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81640. defines.push("#define UV2");
  81641. }
  81642. }
  81643. // Bones
  81644. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81647. if (mesh.numBoneInfluencers > 4) {
  81648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81650. }
  81651. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81652. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81653. }
  81654. else {
  81655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81656. }
  81657. // Instances
  81658. if (useInstances) {
  81659. defines.push("#define INSTANCES");
  81660. attribs.push("world0");
  81661. attribs.push("world1");
  81662. attribs.push("world2");
  81663. attribs.push("world3");
  81664. }
  81665. // Get correct effect
  81666. var join = defines.join("\n");
  81667. if (this._cachedDefines !== join) {
  81668. this._cachedDefines = join;
  81669. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  81670. }
  81671. return this._effect.isReady();
  81672. };
  81673. /**
  81674. * Gets the texture which the depth map will be written to.
  81675. * @returns The depth map texture
  81676. */
  81677. DepthRenderer.prototype.getDepthMap = function () {
  81678. return this._depthMap;
  81679. };
  81680. /**
  81681. * Disposes of the depth renderer.
  81682. */
  81683. DepthRenderer.prototype.dispose = function () {
  81684. this._depthMap.dispose();
  81685. };
  81686. return DepthRenderer;
  81687. }());
  81688. BABYLON.DepthRenderer = DepthRenderer;
  81689. })(BABYLON || (BABYLON = {}));
  81690. //# sourceMappingURL=babylon.depthRenderer.js.map
  81691. var BABYLON;
  81692. (function (BABYLON) {
  81693. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  81694. camera = camera || this.activeCamera;
  81695. if (!camera) {
  81696. throw "No camera available to enable depth renderer";
  81697. }
  81698. if (!this._depthRenderer) {
  81699. this._depthRenderer = {};
  81700. }
  81701. if (!this._depthRenderer[camera.id]) {
  81702. var textureType = 0;
  81703. if (this.getEngine().getCaps().textureHalfFloatRender) {
  81704. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81705. }
  81706. else if (this.getEngine().getCaps().textureFloatRender) {
  81707. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81708. }
  81709. else {
  81710. throw "Depth renderer does not support int texture type";
  81711. }
  81712. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  81713. }
  81714. return this._depthRenderer[camera.id];
  81715. };
  81716. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  81717. camera = camera || this.activeCamera;
  81718. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  81719. return;
  81720. }
  81721. this._depthRenderer[camera.id].dispose();
  81722. delete this._depthRenderer[camera.id];
  81723. };
  81724. /**
  81725. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  81726. * in several rendering techniques.
  81727. */
  81728. var DepthRendererSceneComponent = /** @class */ (function () {
  81729. /**
  81730. * Creates a new instance of the component for the given scene
  81731. * @param scene Defines the scene to register the component in
  81732. */
  81733. function DepthRendererSceneComponent(scene) {
  81734. /**
  81735. * The component name helpfull to identify the component in the list of scene components.
  81736. */
  81737. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  81738. this.scene = scene;
  81739. }
  81740. /**
  81741. * Registers the component in a given scene
  81742. */
  81743. DepthRendererSceneComponent.prototype.register = function () {
  81744. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  81745. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  81746. };
  81747. /**
  81748. * Rebuilds the elements related to this component in case of
  81749. * context lost for instance.
  81750. */
  81751. DepthRendererSceneComponent.prototype.rebuild = function () {
  81752. // Nothing to do for this component
  81753. };
  81754. /**
  81755. * Disposes the component and the associated ressources
  81756. */
  81757. DepthRendererSceneComponent.prototype.dispose = function () {
  81758. for (var key in this.scene._depthRenderer) {
  81759. this.scene._depthRenderer[key].dispose();
  81760. }
  81761. };
  81762. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81763. if (this.scene._depthRenderer) {
  81764. for (var key in this.scene._depthRenderer) {
  81765. var depthRenderer = this.scene._depthRenderer[key];
  81766. if (!depthRenderer.useOnlyInActiveCamera) {
  81767. renderTargets.push(depthRenderer.getDepthMap());
  81768. }
  81769. }
  81770. }
  81771. };
  81772. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  81773. if (this.scene._depthRenderer) {
  81774. for (var key in this.scene._depthRenderer) {
  81775. var depthRenderer = this.scene._depthRenderer[key];
  81776. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  81777. renderTargets.push(depthRenderer.getDepthMap());
  81778. }
  81779. }
  81780. }
  81781. };
  81782. return DepthRendererSceneComponent;
  81783. }());
  81784. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  81785. })(BABYLON || (BABYLON = {}));
  81786. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  81787. var BABYLON;
  81788. (function (BABYLON) {
  81789. /**
  81790. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  81791. */
  81792. var GeometryBufferRenderer = /** @class */ (function () {
  81793. /**
  81794. * Creates a new G Buffer for the scene
  81795. * @param scene The scene the buffer belongs to
  81796. * @param ratio How big is the buffer related to the main canvas.
  81797. */
  81798. function GeometryBufferRenderer(scene, ratio) {
  81799. if (ratio === void 0) { ratio = 1; }
  81800. this._enablePosition = false;
  81801. this._scene = scene;
  81802. this._ratio = ratio;
  81803. // Register the G Buffer component to the scene.
  81804. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  81805. if (!component) {
  81806. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  81807. scene._addComponent(component);
  81808. }
  81809. // Render target
  81810. this._createRenderTargets();
  81811. }
  81812. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  81813. /**
  81814. * Set the render list (meshes to be rendered) used in the G buffer.
  81815. */
  81816. set: function (meshes) {
  81817. this._multiRenderTarget.renderList = meshes;
  81818. },
  81819. enumerable: true,
  81820. configurable: true
  81821. });
  81822. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  81823. /**
  81824. * Gets wether or not G buffer are supported by the running hardware.
  81825. * This requires draw buffer supports
  81826. */
  81827. get: function () {
  81828. return this._multiRenderTarget.isSupported;
  81829. },
  81830. enumerable: true,
  81831. configurable: true
  81832. });
  81833. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  81834. /**
  81835. * Gets wether or not position are enabled for the G buffer.
  81836. */
  81837. get: function () {
  81838. return this._enablePosition;
  81839. },
  81840. /**
  81841. * Sets wether or not position are enabled for the G buffer.
  81842. */
  81843. set: function (enable) {
  81844. this._enablePosition = enable;
  81845. this.dispose();
  81846. this._createRenderTargets();
  81847. },
  81848. enumerable: true,
  81849. configurable: true
  81850. });
  81851. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  81852. /**
  81853. * Gets the scene associated with the buffer.
  81854. */
  81855. get: function () {
  81856. return this._scene;
  81857. },
  81858. enumerable: true,
  81859. configurable: true
  81860. });
  81861. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  81862. /**
  81863. * Gets the ratio used by the buffer during its creation.
  81864. * How big is the buffer related to the main canvas.
  81865. */
  81866. get: function () {
  81867. return this._ratio;
  81868. },
  81869. enumerable: true,
  81870. configurable: true
  81871. });
  81872. /**
  81873. * Checks wether everything is ready to render a submesh to the G buffer.
  81874. * @param subMesh the submesh to check readiness for
  81875. * @param useInstances is the mesh drawn using instance or not
  81876. * @returns true if ready otherwise false
  81877. */
  81878. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  81879. var material = subMesh.getMaterial();
  81880. if (material && material.disableDepthWrite) {
  81881. return false;
  81882. }
  81883. var defines = [];
  81884. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81885. var mesh = subMesh.getMesh();
  81886. // Alpha test
  81887. if (material && material.needAlphaTesting()) {
  81888. defines.push("#define ALPHATEST");
  81889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81890. attribs.push(BABYLON.VertexBuffer.UVKind);
  81891. defines.push("#define UV1");
  81892. }
  81893. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81894. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81895. defines.push("#define UV2");
  81896. }
  81897. }
  81898. // Buffers
  81899. if (this._enablePosition) {
  81900. defines.push("#define POSITION");
  81901. }
  81902. // Bones
  81903. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81904. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81905. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81906. if (mesh.numBoneInfluencers > 4) {
  81907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81909. }
  81910. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81911. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81912. }
  81913. else {
  81914. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81915. }
  81916. // Instances
  81917. if (useInstances) {
  81918. defines.push("#define INSTANCES");
  81919. attribs.push("world0");
  81920. attribs.push("world1");
  81921. attribs.push("world2");
  81922. attribs.push("world3");
  81923. }
  81924. // Get correct effect
  81925. var join = defines.join("\n");
  81926. if (this._cachedDefines !== join) {
  81927. this._cachedDefines = join;
  81928. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  81929. }
  81930. return this._effect.isReady();
  81931. };
  81932. /**
  81933. * Gets the current underlying G Buffer.
  81934. * @returns the buffer
  81935. */
  81936. GeometryBufferRenderer.prototype.getGBuffer = function () {
  81937. return this._multiRenderTarget;
  81938. };
  81939. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  81940. /**
  81941. * Gets the number of samples used to render the buffer (anti aliasing).
  81942. */
  81943. get: function () {
  81944. return this._multiRenderTarget.samples;
  81945. },
  81946. /**
  81947. * Sets the number of samples used to render the buffer (anti aliasing).
  81948. */
  81949. set: function (value) {
  81950. this._multiRenderTarget.samples = value;
  81951. },
  81952. enumerable: true,
  81953. configurable: true
  81954. });
  81955. /**
  81956. * Disposes the renderer and frees up associated resources.
  81957. */
  81958. GeometryBufferRenderer.prototype.dispose = function () {
  81959. this.getGBuffer().dispose();
  81960. };
  81961. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  81962. var _this = this;
  81963. var engine = this._scene.getEngine();
  81964. var count = this._enablePosition ? 3 : 2;
  81965. 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 });
  81966. if (!this.isSupported) {
  81967. return;
  81968. }
  81969. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81970. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81971. this._multiRenderTarget.refreshRate = 1;
  81972. this._multiRenderTarget.renderParticles = false;
  81973. this._multiRenderTarget.renderList = null;
  81974. // set default depth value to 1.0 (far away)
  81975. this._multiRenderTarget.onClearObservable.add(function (engine) {
  81976. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  81977. });
  81978. // Custom render function
  81979. var renderSubMesh = function (subMesh) {
  81980. var mesh = subMesh.getRenderingMesh();
  81981. var scene = _this._scene;
  81982. var engine = scene.getEngine();
  81983. var material = subMesh.getMaterial();
  81984. if (!material) {
  81985. return;
  81986. }
  81987. // Culling
  81988. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81989. // Managing instances
  81990. var batch = mesh._getInstancesRenderList(subMesh._id);
  81991. if (batch.mustReturn) {
  81992. return;
  81993. }
  81994. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81995. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  81996. engine.enableEffect(_this._effect);
  81997. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81998. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81999. _this._effect.setMatrix("view", scene.getViewMatrix());
  82000. // Alpha test
  82001. if (material && material.needAlphaTesting()) {
  82002. var alphaTexture = material.getAlphaTestTexture();
  82003. if (alphaTexture) {
  82004. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82005. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82006. }
  82007. }
  82008. // Bones
  82009. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82010. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82011. }
  82012. // Draw
  82013. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82014. }
  82015. };
  82016. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82017. var index;
  82018. if (depthOnlySubMeshes.length) {
  82019. engine.setColorWrite(false);
  82020. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82021. renderSubMesh(depthOnlySubMeshes.data[index]);
  82022. }
  82023. engine.setColorWrite(true);
  82024. }
  82025. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82026. renderSubMesh(opaqueSubMeshes.data[index]);
  82027. }
  82028. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82029. renderSubMesh(alphaTestSubMeshes.data[index]);
  82030. }
  82031. };
  82032. };
  82033. return GeometryBufferRenderer;
  82034. }());
  82035. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82036. })(BABYLON || (BABYLON = {}));
  82037. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82038. var BABYLON;
  82039. (function (BABYLON) {
  82040. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82041. get: function () {
  82042. this._geometryBufferRenderer;
  82043. },
  82044. set: function (value) {
  82045. if (value && value.isSupported) {
  82046. this._geometryBufferRenderer = value;
  82047. }
  82048. ;
  82049. },
  82050. enumerable: true,
  82051. configurable: true
  82052. });
  82053. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82054. if (ratio === void 0) { ratio = 1; }
  82055. if (this._geometryBufferRenderer) {
  82056. return this._geometryBufferRenderer;
  82057. }
  82058. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82059. if (!this._geometryBufferRenderer.isSupported) {
  82060. this._geometryBufferRenderer = null;
  82061. }
  82062. return this._geometryBufferRenderer;
  82063. };
  82064. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82065. if (!this._geometryBufferRenderer) {
  82066. return;
  82067. }
  82068. this._geometryBufferRenderer.dispose();
  82069. this._geometryBufferRenderer = null;
  82070. };
  82071. /**
  82072. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82073. * in several rendering techniques.
  82074. */
  82075. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82076. /**
  82077. * Creates a new instance of the component for the given scene
  82078. * @param scene Defines the scene to register the component in
  82079. */
  82080. function GeometryBufferRendererSceneComponent(scene) {
  82081. /**
  82082. * The component name helpful to identify the component in the list of scene components.
  82083. */
  82084. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82085. this.scene = scene;
  82086. }
  82087. /**
  82088. * Registers the component in a given scene
  82089. */
  82090. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82091. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82092. };
  82093. /**
  82094. * Rebuilds the elements related to this component in case of
  82095. * context lost for instance.
  82096. */
  82097. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82098. // Nothing to do for this component
  82099. };
  82100. /**
  82101. * Disposes the component and the associated ressources
  82102. */
  82103. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82104. // Nothing to do for this component
  82105. };
  82106. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82107. if (this.scene._geometryBufferRenderer) {
  82108. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82109. }
  82110. };
  82111. return GeometryBufferRendererSceneComponent;
  82112. }());
  82113. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82114. })(BABYLON || (BABYLON = {}));
  82115. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82116. var BABYLON;
  82117. (function (BABYLON) {
  82118. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82119. __extends(SSAORenderingPipeline, _super);
  82120. /**
  82121. * @constructor
  82122. * @param {string} name - The rendering pipeline name
  82123. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82124. * @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 }
  82125. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82126. */
  82127. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82128. var _this = _super.call(this, scene.getEngine(), name) || this;
  82129. // Members
  82130. /**
  82131. * The PassPostProcess id in the pipeline that contains the original scene color
  82132. */
  82133. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82134. /**
  82135. * The SSAO PostProcess id in the pipeline
  82136. */
  82137. _this.SSAORenderEffect = "SSAORenderEffect";
  82138. /**
  82139. * The horizontal blur PostProcess id in the pipeline
  82140. */
  82141. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82142. /**
  82143. * The vertical blur PostProcess id in the pipeline
  82144. */
  82145. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82146. /**
  82147. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82148. */
  82149. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82150. /**
  82151. * The output strength of the SSAO post-process. Default value is 1.0.
  82152. */
  82153. _this.totalStrength = 1.0;
  82154. /**
  82155. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82156. */
  82157. _this.radius = 0.0001;
  82158. /**
  82159. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82160. * Must not be equal to fallOff and superior to fallOff.
  82161. * Default value is 0.975
  82162. */
  82163. _this.area = 0.0075;
  82164. /**
  82165. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82166. * Must not be equal to area and inferior to area.
  82167. * Default value is 0.0
  82168. */
  82169. _this.fallOff = 0.000001;
  82170. /**
  82171. * The base color of the SSAO post-process
  82172. * The final result is "base + ssao" between [0, 1]
  82173. */
  82174. _this.base = 0.5;
  82175. _this._firstUpdate = true;
  82176. _this._scene = scene;
  82177. // Set up assets
  82178. _this._createRandomTexture();
  82179. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82180. var ssaoRatio = ratio.ssaoRatio || ratio;
  82181. var combineRatio = ratio.combineRatio || ratio;
  82182. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82183. _this._createSSAOPostProcess(ssaoRatio);
  82184. _this._createBlurPostProcess(ssaoRatio);
  82185. _this._createSSAOCombinePostProcess(combineRatio);
  82186. // Set up pipeline
  82187. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82188. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82189. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82191. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82192. // Finish
  82193. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82194. if (cameras)
  82195. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82196. return _this;
  82197. }
  82198. // Public Methods
  82199. /**
  82200. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82201. */
  82202. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82203. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82204. for (var i = 0; i < this._scene.cameras.length; i++) {
  82205. var camera = this._scene.cameras[i];
  82206. this._originalColorPostProcess.dispose(camera);
  82207. this._ssaoPostProcess.dispose(camera);
  82208. this._blurHPostProcess.dispose(camera);
  82209. this._blurVPostProcess.dispose(camera);
  82210. this._ssaoCombinePostProcess.dispose(camera);
  82211. }
  82212. this._randomTexture.dispose();
  82213. if (disableDepthRender)
  82214. this._scene.disableDepthRenderer();
  82215. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82216. _super.prototype.dispose.call(this);
  82217. };
  82218. // Private Methods
  82219. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82220. var _this = this;
  82221. var size = 16;
  82222. 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);
  82223. 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);
  82224. this._blurHPostProcess.onActivateObservable.add(function () {
  82225. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82226. _this._blurHPostProcess.kernel = size * dw;
  82227. });
  82228. this._blurVPostProcess.onActivateObservable.add(function () {
  82229. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82230. _this._blurVPostProcess.kernel = size * dw;
  82231. });
  82232. };
  82233. /** @hidden */
  82234. SSAORenderingPipeline.prototype._rebuild = function () {
  82235. this._firstUpdate = true;
  82236. _super.prototype._rebuild.call(this);
  82237. };
  82238. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82239. var _this = this;
  82240. var numSamples = 16;
  82241. var sampleSphere = [
  82242. 0.5381, 0.1856, -0.4319,
  82243. 0.1379, 0.2486, 0.4430,
  82244. 0.3371, 0.5679, -0.0057,
  82245. -0.6999, -0.0451, -0.0019,
  82246. 0.0689, -0.1598, -0.8547,
  82247. 0.0560, 0.0069, -0.1843,
  82248. -0.0146, 0.1402, 0.0762,
  82249. 0.0100, -0.1924, -0.0344,
  82250. -0.3577, -0.5301, -0.4358,
  82251. -0.3169, 0.1063, 0.0158,
  82252. 0.0103, -0.5869, 0.0046,
  82253. -0.0897, -0.4940, 0.3287,
  82254. 0.7119, -0.0154, -0.0918,
  82255. -0.0533, 0.0596, -0.5411,
  82256. 0.0352, -0.0631, 0.5460,
  82257. -0.4776, 0.2847, -0.0271
  82258. ];
  82259. var samplesFactor = 1.0 / numSamples;
  82260. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82261. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82262. "area", "fallOff", "base", "range", "viewport"
  82263. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82264. this._ssaoPostProcess.onApply = function (effect) {
  82265. if (_this._firstUpdate) {
  82266. effect.setArray3("sampleSphere", sampleSphere);
  82267. effect.setFloat("samplesFactor", samplesFactor);
  82268. effect.setFloat("randTextureTiles", 4.0);
  82269. }
  82270. effect.setFloat("totalStrength", _this.totalStrength);
  82271. effect.setFloat("radius", _this.radius);
  82272. effect.setFloat("area", _this.area);
  82273. effect.setFloat("fallOff", _this.fallOff);
  82274. effect.setFloat("base", _this.base);
  82275. effect.setTexture("textureSampler", _this._depthTexture);
  82276. effect.setTexture("randomSampler", _this._randomTexture);
  82277. };
  82278. };
  82279. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82280. var _this = this;
  82281. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82282. this._ssaoCombinePostProcess.onApply = function (effect) {
  82283. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82284. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82285. };
  82286. };
  82287. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  82288. var size = 512;
  82289. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82290. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82291. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82292. var context = this._randomTexture.getContext();
  82293. var rand = function (min, max) {
  82294. return Math.random() * (max - min) + min;
  82295. };
  82296. var randVector = BABYLON.Vector3.Zero();
  82297. for (var x = 0; x < size; x++) {
  82298. for (var y = 0; y < size; y++) {
  82299. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  82300. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  82301. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  82302. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82303. context.fillRect(x, y, 1, 1);
  82304. }
  82305. }
  82306. this._randomTexture.update(false);
  82307. };
  82308. __decorate([
  82309. BABYLON.serialize()
  82310. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  82311. __decorate([
  82312. BABYLON.serialize()
  82313. ], SSAORenderingPipeline.prototype, "radius", void 0);
  82314. __decorate([
  82315. BABYLON.serialize()
  82316. ], SSAORenderingPipeline.prototype, "area", void 0);
  82317. __decorate([
  82318. BABYLON.serialize()
  82319. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  82320. __decorate([
  82321. BABYLON.serialize()
  82322. ], SSAORenderingPipeline.prototype, "base", void 0);
  82323. return SSAORenderingPipeline;
  82324. }(BABYLON.PostProcessRenderPipeline));
  82325. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  82326. })(BABYLON || (BABYLON = {}));
  82327. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  82328. var BABYLON;
  82329. (function (BABYLON) {
  82330. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  82331. __extends(SSAO2RenderingPipeline, _super);
  82332. /**
  82333. * @constructor
  82334. * @param {string} name - The rendering pipeline name
  82335. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82336. * @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 }
  82337. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82338. */
  82339. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  82340. var _this = _super.call(this, scene.getEngine(), name) || this;
  82341. // Members
  82342. /**
  82343. * The PassPostProcess id in the pipeline that contains the original scene color
  82344. */
  82345. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82346. /**
  82347. * The SSAO PostProcess id in the pipeline
  82348. */
  82349. _this.SSAORenderEffect = "SSAORenderEffect";
  82350. /**
  82351. * The horizontal blur PostProcess id in the pipeline
  82352. */
  82353. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82354. /**
  82355. * The vertical blur PostProcess id in the pipeline
  82356. */
  82357. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82358. /**
  82359. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82360. */
  82361. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82362. /**
  82363. * The output strength of the SSAO post-process. Default value is 1.0.
  82364. */
  82365. _this.totalStrength = 1.0;
  82366. /**
  82367. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  82368. */
  82369. _this.maxZ = 100.0;
  82370. /**
  82371. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  82372. */
  82373. _this.minZAspect = 0.2;
  82374. _this._samples = 8;
  82375. _this._textureSamples = 1;
  82376. /**
  82377. * Are we using bilateral blur ?
  82378. */
  82379. _this._expensiveBlur = true;
  82380. /**
  82381. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  82382. */
  82383. _this.radius = 2.0;
  82384. /**
  82385. * The base color of the SSAO post-process
  82386. * The final result is "base + ssao" between [0, 1]
  82387. */
  82388. _this.base = 0;
  82389. _this._firstUpdate = true;
  82390. _this._bits = new Uint32Array(1);
  82391. _this._scene = scene;
  82392. _this._ratio = ratio;
  82393. if (!_this.isSupported) {
  82394. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  82395. return _this;
  82396. }
  82397. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  82398. var blurRatio = _this._ratio.blurRatio || ratio;
  82399. // Set up assets
  82400. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  82401. _this._createRandomTexture();
  82402. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  82403. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  82404. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82405. _this._originalColorPostProcess.samples = _this.textureSamples;
  82406. _this._createSSAOPostProcess(1.0);
  82407. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  82408. _this._createSSAOCombinePostProcess(blurRatio);
  82409. // Set up pipeline
  82410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82411. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82413. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82414. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82415. // Finish
  82416. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82417. if (cameras)
  82418. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82419. return _this;
  82420. }
  82421. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  82422. get: function () {
  82423. return this._samples;
  82424. },
  82425. /**
  82426. * Number of samples used for the SSAO calculations. Default value is 8
  82427. */
  82428. set: function (n) {
  82429. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  82430. this._samples = n;
  82431. this._sampleSphere = this._generateHemisphere();
  82432. this._firstUpdate = true;
  82433. },
  82434. enumerable: true,
  82435. configurable: true
  82436. });
  82437. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  82438. get: function () {
  82439. return this._textureSamples;
  82440. },
  82441. /**
  82442. * Number of samples to use for antialiasing
  82443. */
  82444. set: function (n) {
  82445. this._textureSamples = n;
  82446. this._originalColorPostProcess.samples = n;
  82447. this._blurHPostProcess.samples = n;
  82448. this._blurVPostProcess.samples = n;
  82449. this._ssaoPostProcess.samples = n;
  82450. this._ssaoCombinePostProcess.samples = n;
  82451. },
  82452. enumerable: true,
  82453. configurable: true
  82454. });
  82455. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  82456. get: function () {
  82457. return this._expensiveBlur;
  82458. },
  82459. set: function (b) {
  82460. 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"]);
  82461. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  82462. this._expensiveBlur = b;
  82463. this._firstUpdate = true;
  82464. },
  82465. enumerable: true,
  82466. configurable: true
  82467. });
  82468. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  82469. /**
  82470. * Support test.
  82471. */
  82472. get: function () {
  82473. var engine = BABYLON.Engine.LastCreatedEngine;
  82474. if (!engine) {
  82475. return false;
  82476. }
  82477. return engine.getCaps().drawBuffersExtension;
  82478. },
  82479. enumerable: true,
  82480. configurable: true
  82481. });
  82482. // Public Methods
  82483. /**
  82484. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82485. */
  82486. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  82487. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  82488. for (var i = 0; i < this._scene.cameras.length; i++) {
  82489. var camera = this._scene.cameras[i];
  82490. this._originalColorPostProcess.dispose(camera);
  82491. this._ssaoPostProcess.dispose(camera);
  82492. this._blurHPostProcess.dispose(camera);
  82493. this._blurVPostProcess.dispose(camera);
  82494. this._ssaoCombinePostProcess.dispose(camera);
  82495. }
  82496. this._randomTexture.dispose();
  82497. if (disableGeometryBufferRenderer)
  82498. this._scene.disableGeometryBufferRenderer();
  82499. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82500. _super.prototype.dispose.call(this);
  82501. };
  82502. // Private Methods
  82503. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  82504. var _this = this;
  82505. this._samplerOffsets = [];
  82506. var expensive = this.expensiveBlur;
  82507. for (var i = -8; i < 8; i++) {
  82508. this._samplerOffsets.push(i * 2 + 0.5);
  82509. }
  82510. 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");
  82511. this._blurHPostProcess.onApply = function (effect) {
  82512. if (!_this._scene.activeCamera) {
  82513. return;
  82514. }
  82515. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  82516. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82517. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82518. effect.setFloat("radius", _this.radius);
  82519. effect.setTexture("depthSampler", _this._depthTexture);
  82520. if (_this._firstUpdate) {
  82521. effect.setArray("samplerOffsets", _this._samplerOffsets);
  82522. }
  82523. };
  82524. 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");
  82525. this._blurVPostProcess.onApply = function (effect) {
  82526. if (!_this._scene.activeCamera) {
  82527. return;
  82528. }
  82529. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  82530. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82531. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82532. effect.setFloat("radius", _this.radius);
  82533. effect.setTexture("depthSampler", _this._depthTexture);
  82534. if (_this._firstUpdate) {
  82535. effect.setArray("samplerOffsets", _this._samplerOffsets);
  82536. _this._firstUpdate = false;
  82537. }
  82538. };
  82539. this._blurHPostProcess.samples = this.textureSamples;
  82540. this._blurVPostProcess.samples = this.textureSamples;
  82541. };
  82542. /** @hidden */
  82543. SSAO2RenderingPipeline.prototype._rebuild = function () {
  82544. this._firstUpdate = true;
  82545. _super.prototype._rebuild.call(this);
  82546. };
  82547. //Van der Corput radical inverse
  82548. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  82549. this._bits[0] = i;
  82550. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  82551. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  82552. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  82553. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  82554. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  82555. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  82556. };
  82557. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  82558. return [i / n, this._radicalInverse_VdC(i)];
  82559. };
  82560. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  82561. var phi = v * 2.0 * Math.PI;
  82562. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  82563. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  82564. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  82565. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  82566. };
  82567. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  82568. var numSamples = this.samples;
  82569. var result = [];
  82570. var vector;
  82571. var i = 0;
  82572. while (i < numSamples) {
  82573. if (numSamples < 16) {
  82574. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  82575. }
  82576. else {
  82577. var rand = this._hammersley(i, numSamples);
  82578. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  82579. }
  82580. result.push(vector.x, vector.y, vector.z);
  82581. i++;
  82582. }
  82583. return result;
  82584. };
  82585. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82586. var _this = this;
  82587. var numSamples = this.samples;
  82588. this._sampleSphere = this._generateHemisphere();
  82589. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  82590. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82591. "base", "range", "projection", "near", "far", "texelSize",
  82592. "xViewport", "yViewport", "maxZ", "minZAspect"
  82593. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82594. this._ssaoPostProcess.onApply = function (effect) {
  82595. if (_this._firstUpdate) {
  82596. effect.setArray3("sampleSphere", _this._sampleSphere);
  82597. effect.setFloat("randTextureTiles", 32.0);
  82598. }
  82599. if (!_this._scene.activeCamera) {
  82600. return;
  82601. }
  82602. effect.setFloat("samplesFactor", 1 / _this.samples);
  82603. effect.setFloat("totalStrength", _this.totalStrength);
  82604. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  82605. effect.setFloat("radius", _this.radius);
  82606. effect.setFloat("maxZ", _this.maxZ);
  82607. effect.setFloat("minZAspect", _this.minZAspect);
  82608. effect.setFloat("base", _this.base);
  82609. effect.setFloat("near", _this._scene.activeCamera.minZ);
  82610. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  82611. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  82612. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  82613. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  82614. effect.setTexture("textureSampler", _this._depthTexture);
  82615. effect.setTexture("normalSampler", _this._normalTexture);
  82616. effect.setTexture("randomSampler", _this._randomTexture);
  82617. };
  82618. this._ssaoPostProcess.samples = this.textureSamples;
  82619. };
  82620. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82621. var _this = this;
  82622. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82623. this._ssaoCombinePostProcess.onApply = function (effect) {
  82624. var viewport = _this._scene.activeCamera.viewport;
  82625. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  82626. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82627. };
  82628. this._ssaoCombinePostProcess.samples = this.textureSamples;
  82629. };
  82630. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  82631. var size = 128;
  82632. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82633. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82634. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82635. var context = this._randomTexture.getContext();
  82636. var rand = function (min, max) {
  82637. return Math.random() * (max - min) + min;
  82638. };
  82639. var randVector = BABYLON.Vector3.Zero();
  82640. for (var x = 0; x < size; x++) {
  82641. for (var y = 0; y < size; y++) {
  82642. randVector.x = rand(0.0, 1.0);
  82643. randVector.y = rand(0.0, 1.0);
  82644. randVector.z = 0.0;
  82645. randVector.normalize();
  82646. randVector.scaleInPlace(255);
  82647. randVector.x = Math.floor(randVector.x);
  82648. randVector.y = Math.floor(randVector.y);
  82649. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82650. context.fillRect(x, y, 1, 1);
  82651. }
  82652. }
  82653. this._randomTexture.update(false);
  82654. };
  82655. /**
  82656. * Serialize the rendering pipeline (Used when exporting)
  82657. * @returns the serialized object
  82658. */
  82659. SSAO2RenderingPipeline.prototype.serialize = function () {
  82660. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82661. serializationObject.customType = "SSAO2RenderingPipeline";
  82662. return serializationObject;
  82663. };
  82664. /**
  82665. * Parse the serialized pipeline
  82666. * @param source Source pipeline.
  82667. * @param scene The scene to load the pipeline to.
  82668. * @param rootUrl The URL of the serialized pipeline.
  82669. * @returns An instantiated pipeline from the serialized object.
  82670. */
  82671. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  82672. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82673. };
  82674. __decorate([
  82675. BABYLON.serialize()
  82676. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  82677. __decorate([
  82678. BABYLON.serialize()
  82679. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  82680. __decorate([
  82681. BABYLON.serialize()
  82682. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  82683. __decorate([
  82684. BABYLON.serialize("samples")
  82685. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  82686. __decorate([
  82687. BABYLON.serialize("textureSamples")
  82688. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  82689. __decorate([
  82690. BABYLON.serialize()
  82691. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  82692. __decorate([
  82693. BABYLON.serialize("expensiveBlur")
  82694. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  82695. __decorate([
  82696. BABYLON.serialize()
  82697. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  82698. __decorate([
  82699. BABYLON.serialize()
  82700. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  82701. return SSAO2RenderingPipeline;
  82702. }(BABYLON.PostProcessRenderPipeline));
  82703. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  82704. })(BABYLON || (BABYLON = {}));
  82705. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  82706. // BABYLON.JS Chromatic Aberration GLSL Shader
  82707. // Author: Olivier Guyot
  82708. // Separates very slightly R, G and B colors on the edges of the screen
  82709. // Inspired by Francois Tarlier & Martins Upitis
  82710. var BABYLON;
  82711. (function (BABYLON) {
  82712. var LensRenderingPipeline = /** @class */ (function (_super) {
  82713. __extends(LensRenderingPipeline, _super);
  82714. /**
  82715. * @constructor
  82716. *
  82717. * Effect parameters are as follow:
  82718. * {
  82719. * chromatic_aberration: number; // from 0 to x (1 for realism)
  82720. * edge_blur: number; // from 0 to x (1 for realism)
  82721. * distortion: number; // from 0 to x (1 for realism)
  82722. * grain_amount: number; // from 0 to 1
  82723. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  82724. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  82725. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  82726. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  82727. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  82728. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  82729. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  82730. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  82731. * }
  82732. * Note: if an effect parameter is unset, effect is disabled
  82733. *
  82734. * @param {string} name - The rendering pipeline name
  82735. * @param {object} parameters - An object containing all parameters (see above)
  82736. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82737. * @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)
  82738. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82739. */
  82740. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  82741. if (ratio === void 0) { ratio = 1.0; }
  82742. var _this = _super.call(this, scene.getEngine(), name) || this;
  82743. // Lens effects can be of the following:
  82744. // - chromatic aberration (slight shift of RGB colors)
  82745. // - blur on the edge of the lens
  82746. // - lens distortion
  82747. // - depth-of-field blur & highlights enhancing
  82748. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  82749. // - grain effect (noise or custom texture)
  82750. // Two additional texture samplers are needed:
  82751. // - depth map (for depth-of-field)
  82752. // - grain texture
  82753. /**
  82754. * The chromatic aberration PostProcess id in the pipeline
  82755. */
  82756. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  82757. /**
  82758. * The highlights enhancing PostProcess id in the pipeline
  82759. */
  82760. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  82761. /**
  82762. * The depth-of-field PostProcess id in the pipeline
  82763. */
  82764. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  82765. _this._scene = scene;
  82766. // Fetch texture samplers
  82767. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82768. if (parameters.grain_texture) {
  82769. _this._grainTexture = parameters.grain_texture;
  82770. }
  82771. else {
  82772. _this._createGrainTexture();
  82773. }
  82774. // save parameters
  82775. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  82776. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  82777. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  82778. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  82779. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  82780. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  82781. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  82782. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  82783. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  82784. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  82785. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  82786. // Create effects
  82787. _this._createChromaticAberrationPostProcess(ratio);
  82788. _this._createHighlightsPostProcess(ratio);
  82789. _this._createDepthOfFieldPostProcess(ratio / 4);
  82790. // Set up pipeline
  82791. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  82792. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  82793. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  82794. if (_this._highlightsGain === -1) {
  82795. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  82796. }
  82797. // Finish
  82798. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82799. if (cameras) {
  82800. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82801. }
  82802. return _this;
  82803. }
  82804. // public methods (self explanatory)
  82805. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  82806. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  82807. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  82808. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  82809. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  82810. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  82811. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  82812. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  82813. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  82814. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  82815. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  82816. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  82817. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  82818. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  82819. };
  82820. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  82821. this._highlightsPostProcess.updateEffect();
  82822. };
  82823. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  82824. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  82825. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  82826. this._highlightsGain = amount;
  82827. };
  82828. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  82829. if (this._highlightsGain === -1) {
  82830. this._highlightsGain = 1.0;
  82831. }
  82832. this._highlightsThreshold = amount;
  82833. };
  82834. LensRenderingPipeline.prototype.disableHighlights = function () {
  82835. this._highlightsGain = -1;
  82836. };
  82837. /**
  82838. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  82839. */
  82840. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82841. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82842. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82843. this._chromaticAberrationPostProcess = null;
  82844. this._highlightsPostProcess = null;
  82845. this._depthOfFieldPostProcess = null;
  82846. this._grainTexture.dispose();
  82847. if (disableDepthRender)
  82848. this._scene.disableDepthRenderer();
  82849. };
  82850. // colors shifting and distortion
  82851. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  82852. var _this = this;
  82853. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  82854. [], // samplers
  82855. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82856. this._chromaticAberrationPostProcess.onApply = function (effect) {
  82857. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  82858. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82859. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82860. effect.setFloat('radialIntensity', 1);
  82861. effect.setFloat2('direction', 17, 17);
  82862. effect.setFloat2('centerPosition', 0.5, 0.5);
  82863. };
  82864. };
  82865. // highlights enhancing
  82866. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  82867. var _this = this;
  82868. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  82869. [], // samplers
  82870. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  82871. this._highlightsPostProcess.onApply = function (effect) {
  82872. effect.setFloat('gain', _this._highlightsGain);
  82873. effect.setFloat('threshold', _this._highlightsThreshold);
  82874. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  82875. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82876. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82877. };
  82878. };
  82879. // colors shifting and distortion
  82880. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  82881. var _this = this;
  82882. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  82883. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  82884. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  82885. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82886. this._depthOfFieldPostProcess.onApply = function (effect) {
  82887. effect.setTexture("depthSampler", _this._depthTexture);
  82888. effect.setTexture("grainSampler", _this._grainTexture);
  82889. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  82890. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  82891. effect.setFloat('grain_amount', _this._grainAmount);
  82892. effect.setBool('blur_noise', _this._blurNoise);
  82893. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82894. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82895. effect.setFloat('distortion', _this._distortion);
  82896. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  82897. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  82898. effect.setFloat('aperture', _this._dofAperture);
  82899. effect.setFloat('darken', _this._dofDarken);
  82900. effect.setFloat('edge_blur', _this._edgeBlur);
  82901. effect.setBool('highlights', (_this._highlightsGain !== -1));
  82902. if (_this._scene.activeCamera) {
  82903. effect.setFloat('near', _this._scene.activeCamera.minZ);
  82904. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  82905. }
  82906. };
  82907. };
  82908. // creates a black and white random noise texture, 512x512
  82909. LensRenderingPipeline.prototype._createGrainTexture = function () {
  82910. var size = 512;
  82911. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82912. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82913. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82914. var context = this._grainTexture.getContext();
  82915. var rand = function (min, max) {
  82916. return Math.random() * (max - min) + min;
  82917. };
  82918. var value;
  82919. for (var x = 0; x < size; x++) {
  82920. for (var y = 0; y < size; y++) {
  82921. value = Math.floor(rand(0.42, 0.58) * 255);
  82922. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  82923. context.fillRect(x, y, 1, 1);
  82924. }
  82925. }
  82926. this._grainTexture.update(false);
  82927. };
  82928. return LensRenderingPipeline;
  82929. }(BABYLON.PostProcessRenderPipeline));
  82930. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  82931. })(BABYLON || (BABYLON = {}));
  82932. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  82933. var BABYLON;
  82934. (function (BABYLON) {
  82935. var StandardRenderingPipeline = /** @class */ (function (_super) {
  82936. __extends(StandardRenderingPipeline, _super);
  82937. /**
  82938. * @constructor
  82939. * @param {string} name - The rendering pipeline name
  82940. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82941. * @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)
  82942. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  82943. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82944. */
  82945. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  82946. if (originalPostProcess === void 0) { originalPostProcess = null; }
  82947. var _this = _super.call(this, scene.getEngine(), name) || this;
  82948. /**
  82949. * Post-process used to down scale an image x4
  82950. */
  82951. _this.downSampleX4PostProcess = null;
  82952. /**
  82953. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  82954. */
  82955. _this.brightPassPostProcess = null;
  82956. /**
  82957. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  82958. */
  82959. _this.blurHPostProcesses = [];
  82960. /**
  82961. * Post-process array storing all the vertical blur post-processes used by the pipeline
  82962. */
  82963. _this.blurVPostProcesses = [];
  82964. /**
  82965. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  82966. */
  82967. _this.textureAdderPostProcess = null;
  82968. /**
  82969. * Post-process used to create volumetric lighting effect
  82970. */
  82971. _this.volumetricLightPostProcess = null;
  82972. /**
  82973. * Post-process used to smooth the previous volumetric light post-process on the X axis
  82974. */
  82975. _this.volumetricLightSmoothXPostProcess = null;
  82976. /**
  82977. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  82978. */
  82979. _this.volumetricLightSmoothYPostProcess = null;
  82980. /**
  82981. * Post-process used to merge the volumetric light effect and the real scene color
  82982. */
  82983. _this.volumetricLightMergePostProces = null;
  82984. /**
  82985. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  82986. */
  82987. _this.volumetricLightFinalPostProcess = null;
  82988. /**
  82989. * Base post-process used to calculate the average luminance of the final image for HDR
  82990. */
  82991. _this.luminancePostProcess = null;
  82992. /**
  82993. * Post-processes used to create down sample post-processes in order to get
  82994. * the average luminance of the final image for HDR
  82995. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  82996. */
  82997. _this.luminanceDownSamplePostProcesses = [];
  82998. /**
  82999. * Post-process used to create a HDR effect (light adaptation)
  83000. */
  83001. _this.hdrPostProcess = null;
  83002. /**
  83003. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  83004. */
  83005. _this.textureAdderFinalPostProcess = null;
  83006. /**
  83007. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  83008. */
  83009. _this.lensFlareFinalPostProcess = null;
  83010. /**
  83011. * Post-process used to merge the final HDR post-process and the real scene color
  83012. */
  83013. _this.hdrFinalPostProcess = null;
  83014. /**
  83015. * Post-process used to create a lens flare effect
  83016. */
  83017. _this.lensFlarePostProcess = null;
  83018. /**
  83019. * Post-process that merges the result of the lens flare post-process and the real scene color
  83020. */
  83021. _this.lensFlareComposePostProcess = null;
  83022. /**
  83023. * Post-process used to create a motion blur effect
  83024. */
  83025. _this.motionBlurPostProcess = null;
  83026. /**
  83027. * Post-process used to create a depth of field effect
  83028. */
  83029. _this.depthOfFieldPostProcess = null;
  83030. /**
  83031. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83032. */
  83033. _this.fxaaPostProcess = null;
  83034. // Values
  83035. /**
  83036. * Represents the brightness threshold in order to configure the illuminated surfaces
  83037. */
  83038. _this.brightThreshold = 1.0;
  83039. /**
  83040. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83041. */
  83042. _this.blurWidth = 512.0;
  83043. /**
  83044. * Sets if the blur for highlighted surfaces must be only horizontal
  83045. */
  83046. _this.horizontalBlur = false;
  83047. /**
  83048. * Sets the overall exposure used by the pipeline
  83049. */
  83050. _this.exposure = 1.0;
  83051. /**
  83052. * Texture used typically to simulate "dirty" on camera lens
  83053. */
  83054. _this.lensTexture = null;
  83055. /**
  83056. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83057. */
  83058. _this.volumetricLightCoefficient = 0.2;
  83059. /**
  83060. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83061. */
  83062. _this.volumetricLightPower = 4.0;
  83063. /**
  83064. * Used the set the blur intensity to smooth the volumetric lights
  83065. */
  83066. _this.volumetricLightBlurScale = 64.0;
  83067. /**
  83068. * Light (spot or directional) used to generate the volumetric lights rays
  83069. * The source light must have a shadow generate so the pipeline can get its
  83070. * depth map
  83071. */
  83072. _this.sourceLight = null;
  83073. /**
  83074. * For eye adaptation, represents the minimum luminance the eye can see
  83075. */
  83076. _this.hdrMinimumLuminance = 1.0;
  83077. /**
  83078. * For eye adaptation, represents the decrease luminance speed
  83079. */
  83080. _this.hdrDecreaseRate = 0.5;
  83081. /**
  83082. * For eye adaptation, represents the increase luminance speed
  83083. */
  83084. _this.hdrIncreaseRate = 0.5;
  83085. /**
  83086. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83087. */
  83088. _this.lensColorTexture = null;
  83089. /**
  83090. * The overall strengh for the lens flare effect
  83091. */
  83092. _this.lensFlareStrength = 20.0;
  83093. /**
  83094. * Dispersion coefficient for lens flare ghosts
  83095. */
  83096. _this.lensFlareGhostDispersal = 1.4;
  83097. /**
  83098. * Main lens flare halo width
  83099. */
  83100. _this.lensFlareHaloWidth = 0.7;
  83101. /**
  83102. * Based on the lens distortion effect, defines how much the lens flare result
  83103. * is distorted
  83104. */
  83105. _this.lensFlareDistortionStrength = 16.0;
  83106. /**
  83107. * Lens star texture must be used to simulate rays on the flares and is available
  83108. * in the documentation
  83109. */
  83110. _this.lensStarTexture = null;
  83111. /**
  83112. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83113. * flare effect by taking account of the dirt texture
  83114. */
  83115. _this.lensFlareDirtTexture = null;
  83116. /**
  83117. * Represents the focal length for the depth of field effect
  83118. */
  83119. _this.depthOfFieldDistance = 10.0;
  83120. /**
  83121. * Represents the blur intensity for the blurred part of the depth of field effect
  83122. */
  83123. _this.depthOfFieldBlurWidth = 64.0;
  83124. /**
  83125. * For motion blur, defines how much the image is blurred by the movement
  83126. */
  83127. _this.motionStrength = 1.0;
  83128. /**
  83129. * List of animations for the pipeline (IAnimatable implementation)
  83130. */
  83131. _this.animations = [];
  83132. _this._currentDepthOfFieldSource = null;
  83133. _this._hdrCurrentLuminance = 1.0;
  83134. // Getters and setters
  83135. _this._bloomEnabled = false;
  83136. _this._depthOfFieldEnabled = false;
  83137. _this._vlsEnabled = false;
  83138. _this._lensFlareEnabled = false;
  83139. _this._hdrEnabled = false;
  83140. _this._motionBlurEnabled = false;
  83141. _this._fxaaEnabled = false;
  83142. _this._motionBlurSamples = 64.0;
  83143. _this._volumetricLightStepsCount = 50.0;
  83144. _this._samples = 1;
  83145. _this._cameras = cameras || [];
  83146. // Initialize
  83147. _this._scene = scene;
  83148. _this._basePostProcess = originalPostProcess;
  83149. _this._ratio = ratio;
  83150. // Misc
  83151. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83152. // Finish
  83153. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83154. _this._buildPipeline();
  83155. return _this;
  83156. }
  83157. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83158. /**
  83159. * Specifies if the bloom pipeline is enabled
  83160. */
  83161. get: function () {
  83162. return this._bloomEnabled;
  83163. },
  83164. set: function (enabled) {
  83165. if (this._bloomEnabled === enabled) {
  83166. return;
  83167. }
  83168. this._bloomEnabled = enabled;
  83169. this._buildPipeline();
  83170. },
  83171. enumerable: true,
  83172. configurable: true
  83173. });
  83174. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83175. /**
  83176. * Specifies if the depth of field pipeline is enabed
  83177. */
  83178. get: function () {
  83179. return this._depthOfFieldEnabled;
  83180. },
  83181. set: function (enabled) {
  83182. if (this._depthOfFieldEnabled === enabled) {
  83183. return;
  83184. }
  83185. this._depthOfFieldEnabled = enabled;
  83186. this._buildPipeline();
  83187. },
  83188. enumerable: true,
  83189. configurable: true
  83190. });
  83191. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83192. /**
  83193. * Specifies if the lens flare pipeline is enabed
  83194. */
  83195. get: function () {
  83196. return this._lensFlareEnabled;
  83197. },
  83198. set: function (enabled) {
  83199. if (this._lensFlareEnabled === enabled) {
  83200. return;
  83201. }
  83202. this._lensFlareEnabled = enabled;
  83203. this._buildPipeline();
  83204. },
  83205. enumerable: true,
  83206. configurable: true
  83207. });
  83208. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83209. /**
  83210. * Specifies if the HDR pipeline is enabled
  83211. */
  83212. get: function () {
  83213. return this._hdrEnabled;
  83214. },
  83215. set: function (enabled) {
  83216. if (this._hdrEnabled === enabled) {
  83217. return;
  83218. }
  83219. this._hdrEnabled = enabled;
  83220. this._buildPipeline();
  83221. },
  83222. enumerable: true,
  83223. configurable: true
  83224. });
  83225. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83226. /**
  83227. * Specifies if the volumetric lights scattering effect is enabled
  83228. */
  83229. get: function () {
  83230. return this._vlsEnabled;
  83231. },
  83232. set: function (enabled) {
  83233. if (this._vlsEnabled === enabled) {
  83234. return;
  83235. }
  83236. if (enabled) {
  83237. var geometry = this._scene.enableGeometryBufferRenderer();
  83238. if (!geometry) {
  83239. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83240. return;
  83241. }
  83242. }
  83243. this._vlsEnabled = enabled;
  83244. this._buildPipeline();
  83245. },
  83246. enumerable: true,
  83247. configurable: true
  83248. });
  83249. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83250. /**
  83251. * Specifies if the motion blur effect is enabled
  83252. */
  83253. get: function () {
  83254. return this._motionBlurEnabled;
  83255. },
  83256. set: function (enabled) {
  83257. if (this._motionBlurEnabled === enabled) {
  83258. return;
  83259. }
  83260. this._motionBlurEnabled = enabled;
  83261. this._buildPipeline();
  83262. },
  83263. enumerable: true,
  83264. configurable: true
  83265. });
  83266. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83267. /**
  83268. * Specifies if anti-aliasing is enabled
  83269. */
  83270. get: function () {
  83271. return this._fxaaEnabled;
  83272. },
  83273. set: function (enabled) {
  83274. if (this._fxaaEnabled === enabled) {
  83275. return;
  83276. }
  83277. this._fxaaEnabled = enabled;
  83278. this._buildPipeline();
  83279. },
  83280. enumerable: true,
  83281. configurable: true
  83282. });
  83283. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  83284. /**
  83285. * Specifies the number of steps used to calculate the volumetric lights
  83286. * Typically in interval [50, 200]
  83287. */
  83288. get: function () {
  83289. return this._volumetricLightStepsCount;
  83290. },
  83291. set: function (count) {
  83292. if (this.volumetricLightPostProcess) {
  83293. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  83294. }
  83295. this._volumetricLightStepsCount = count;
  83296. },
  83297. enumerable: true,
  83298. configurable: true
  83299. });
  83300. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  83301. /**
  83302. * Specifies the number of samples used for the motion blur effect
  83303. * Typically in interval [16, 64]
  83304. */
  83305. get: function () {
  83306. return this._motionBlurSamples;
  83307. },
  83308. set: function (samples) {
  83309. if (this.motionBlurPostProcess) {
  83310. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  83311. }
  83312. this._motionBlurSamples = samples;
  83313. },
  83314. enumerable: true,
  83315. configurable: true
  83316. });
  83317. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  83318. /**
  83319. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83320. */
  83321. get: function () {
  83322. return this._samples;
  83323. },
  83324. set: function (sampleCount) {
  83325. if (this._samples === sampleCount) {
  83326. return;
  83327. }
  83328. this._samples = sampleCount;
  83329. this._buildPipeline();
  83330. },
  83331. enumerable: true,
  83332. configurable: true
  83333. });
  83334. StandardRenderingPipeline.prototype._buildPipeline = function () {
  83335. var _this = this;
  83336. var ratio = this._ratio;
  83337. var scene = this._scene;
  83338. this._disposePostProcesses();
  83339. this._reset();
  83340. // Create pass post-process
  83341. if (!this._basePostProcess) {
  83342. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  83343. this.originalPostProcess.onApply = function (effect) {
  83344. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  83345. };
  83346. }
  83347. else {
  83348. this.originalPostProcess = this._basePostProcess;
  83349. }
  83350. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  83351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  83352. }
  83353. this._currentDepthOfFieldSource = this.originalPostProcess;
  83354. if (this._bloomEnabled) {
  83355. // Create down sample X4 post-process
  83356. this._createDownSampleX4PostProcess(scene, ratio / 2);
  83357. // Create bright pass post-process
  83358. this._createBrightPassPostProcess(scene, ratio / 2);
  83359. // Create gaussian blur post-processes (down sampling blurs)
  83360. this._createBlurPostProcesses(scene, ratio / 4, 1);
  83361. // Create texture adder post-process
  83362. this._createTextureAdderPostProcess(scene, ratio);
  83363. // Create depth-of-field source post-process
  83364. 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);
  83365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  83366. }
  83367. if (this._vlsEnabled) {
  83368. // Create volumetric light
  83369. this._createVolumetricLightPostProcess(scene, ratio);
  83370. // Create volumetric light final post-process
  83371. 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);
  83372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  83373. }
  83374. if (this._lensFlareEnabled) {
  83375. // Create lens flare post-process
  83376. this._createLensFlarePostProcess(scene, ratio);
  83377. // Create depth-of-field source post-process post lens-flare and disable it now
  83378. 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);
  83379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  83380. }
  83381. if (this._hdrEnabled) {
  83382. // Create luminance
  83383. this._createLuminancePostProcesses(scene, this._floatTextureType);
  83384. // Create HDR
  83385. this._createHdrPostProcess(scene, ratio);
  83386. // Create depth-of-field source post-process post hdr and disable it now
  83387. 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);
  83388. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  83389. }
  83390. if (this._depthOfFieldEnabled) {
  83391. // Create gaussian blur used by depth-of-field
  83392. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  83393. // Create depth-of-field post-process
  83394. this._createDepthOfFieldPostProcess(scene, ratio);
  83395. }
  83396. if (this._motionBlurEnabled) {
  83397. // Create motion blur post-process
  83398. this._createMotionBlurPostProcess(scene, ratio);
  83399. }
  83400. if (this._fxaaEnabled) {
  83401. // Create fxaa post-process
  83402. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  83404. }
  83405. if (this._cameras !== null) {
  83406. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83407. }
  83408. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  83409. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83410. }
  83411. };
  83412. // Down Sample X4 Post-Processs
  83413. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  83414. var _this = this;
  83415. var downSampleX4Offsets = new Array(32);
  83416. 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);
  83417. this.downSampleX4PostProcess.onApply = function (effect) {
  83418. var id = 0;
  83419. var width = _this.downSampleX4PostProcess.width;
  83420. var height = _this.downSampleX4PostProcess.height;
  83421. for (var i = -2; i < 2; i++) {
  83422. for (var j = -2; j < 2; j++) {
  83423. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  83424. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  83425. id += 2;
  83426. }
  83427. }
  83428. effect.setArray2("dsOffsets", downSampleX4Offsets);
  83429. };
  83430. // Add to pipeline
  83431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  83432. };
  83433. // Brightpass Post-Process
  83434. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  83435. var _this = this;
  83436. var brightOffsets = new Array(8);
  83437. 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);
  83438. this.brightPassPostProcess.onApply = function (effect) {
  83439. var sU = (1.0 / _this.brightPassPostProcess.width);
  83440. var sV = (1.0 / _this.brightPassPostProcess.height);
  83441. brightOffsets[0] = -0.5 * sU;
  83442. brightOffsets[1] = 0.5 * sV;
  83443. brightOffsets[2] = 0.5 * sU;
  83444. brightOffsets[3] = 0.5 * sV;
  83445. brightOffsets[4] = -0.5 * sU;
  83446. brightOffsets[5] = -0.5 * sV;
  83447. brightOffsets[6] = 0.5 * sU;
  83448. brightOffsets[7] = -0.5 * sV;
  83449. effect.setArray2("dsOffsets", brightOffsets);
  83450. effect.setFloat("brightThreshold", _this.brightThreshold);
  83451. };
  83452. // Add to pipeline
  83453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  83454. };
  83455. // Create blur H&V post-processes
  83456. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  83457. var _this = this;
  83458. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  83459. var engine = scene.getEngine();
  83460. 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);
  83461. 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);
  83462. blurX.onActivateObservable.add(function () {
  83463. var dw = blurX.width / engine.getRenderWidth();
  83464. blurX.kernel = _this[blurWidthKey] * dw;
  83465. });
  83466. blurY.onActivateObservable.add(function () {
  83467. var dw = blurY.height / engine.getRenderHeight();
  83468. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  83469. });
  83470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  83471. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  83472. this.blurHPostProcesses.push(blurX);
  83473. this.blurVPostProcesses.push(blurY);
  83474. };
  83475. // Create texture adder post-process
  83476. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  83477. var _this = this;
  83478. 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);
  83479. this.textureAdderPostProcess.onApply = function (effect) {
  83480. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  83481. effect.setTexture("lensSampler", _this.lensTexture);
  83482. effect.setFloat("exposure", _this.exposure);
  83483. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  83484. };
  83485. // Add to pipeline
  83486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  83487. };
  83488. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  83489. var _this = this;
  83490. var geometryRenderer = scene.enableGeometryBufferRenderer();
  83491. geometryRenderer.enablePosition = true;
  83492. var geometry = geometryRenderer.getGBuffer();
  83493. // Base post-process
  83494. 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));
  83495. var depthValues = BABYLON.Vector2.Zero();
  83496. this.volumetricLightPostProcess.onApply = function (effect) {
  83497. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  83498. var generator = _this.sourceLight.getShadowGenerator();
  83499. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  83500. effect.setTexture("positionSampler", geometry.textures[2]);
  83501. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  83502. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  83503. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  83504. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  83505. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  83506. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  83507. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  83508. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  83509. effect.setVector2("depthValues", depthValues);
  83510. }
  83511. };
  83512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  83513. // Smooth
  83514. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  83515. // Merge
  83516. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  83517. this.volumetricLightMergePostProces.onApply = function (effect) {
  83518. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  83519. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  83520. };
  83521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  83522. };
  83523. // Create luminance
  83524. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  83525. var _this = this;
  83526. // Create luminance
  83527. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  83528. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  83529. var offsets = [];
  83530. this.luminancePostProcess.onApply = function (effect) {
  83531. var sU = (1.0 / _this.luminancePostProcess.width);
  83532. var sV = (1.0 / _this.luminancePostProcess.height);
  83533. offsets[0] = -0.5 * sU;
  83534. offsets[1] = 0.5 * sV;
  83535. offsets[2] = 0.5 * sU;
  83536. offsets[3] = 0.5 * sV;
  83537. offsets[4] = -0.5 * sU;
  83538. offsets[5] = -0.5 * sV;
  83539. offsets[6] = 0.5 * sU;
  83540. offsets[7] = -0.5 * sV;
  83541. effect.setArray2("lumOffsets", offsets);
  83542. };
  83543. // Add to pipeline
  83544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  83545. // Create down sample luminance
  83546. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  83547. var size = Math.pow(3, i);
  83548. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  83549. if (i === 0) {
  83550. defines += "#define FINAL_DOWN_SAMPLER";
  83551. }
  83552. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  83553. this.luminanceDownSamplePostProcesses.push(postProcess);
  83554. }
  83555. // Create callbacks and add effects
  83556. var lastLuminance = this.luminancePostProcess;
  83557. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  83558. var downSampleOffsets = new Array(18);
  83559. pp.onApply = function (effect) {
  83560. if (!lastLuminance) {
  83561. return;
  83562. }
  83563. var id = 0;
  83564. for (var x = -1; x < 2; x++) {
  83565. for (var y = -1; y < 2; y++) {
  83566. downSampleOffsets[id] = x / lastLuminance.width;
  83567. downSampleOffsets[id + 1] = y / lastLuminance.height;
  83568. id += 2;
  83569. }
  83570. }
  83571. effect.setArray2("dsOffsets", downSampleOffsets);
  83572. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  83573. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  83574. lastLuminance = _this.luminancePostProcess;
  83575. }
  83576. else {
  83577. lastLuminance = pp;
  83578. }
  83579. };
  83580. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  83581. pp.onAfterRender = function (effect) {
  83582. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  83583. 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);
  83584. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  83585. };
  83586. }
  83587. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  83588. });
  83589. };
  83590. // Create HDR post-process
  83591. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  83592. var _this = this;
  83593. 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);
  83594. var outputLiminance = 1;
  83595. var time = 0;
  83596. var lastTime = 0;
  83597. this.hdrPostProcess.onApply = function (effect) {
  83598. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  83599. time += scene.getEngine().getDeltaTime();
  83600. if (outputLiminance < 0) {
  83601. outputLiminance = _this._hdrCurrentLuminance;
  83602. }
  83603. else {
  83604. var dt = (lastTime - time) / 1000.0;
  83605. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  83606. outputLiminance += _this.hdrDecreaseRate * dt;
  83607. }
  83608. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  83609. outputLiminance -= _this.hdrIncreaseRate * dt;
  83610. }
  83611. else {
  83612. outputLiminance = _this._hdrCurrentLuminance;
  83613. }
  83614. }
  83615. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  83616. effect.setFloat("averageLuminance", outputLiminance);
  83617. lastTime = time;
  83618. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  83619. };
  83620. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  83621. };
  83622. // Create lens flare post-process
  83623. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  83624. var _this = this;
  83625. 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);
  83626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  83627. this._createBlurPostProcesses(scene, ratio / 4, 2);
  83628. 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);
  83629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  83630. var resolution = new BABYLON.Vector2(0, 0);
  83631. // Lens flare
  83632. this.lensFlarePostProcess.onApply = function (effect) {
  83633. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  83634. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  83635. effect.setFloat("strength", _this.lensFlareStrength);
  83636. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  83637. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  83638. // Shift
  83639. resolution.x = _this.lensFlarePostProcess.width;
  83640. resolution.y = _this.lensFlarePostProcess.height;
  83641. effect.setVector2("resolution", resolution);
  83642. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  83643. };
  83644. // Compose
  83645. 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);
  83646. 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);
  83647. this.lensFlareComposePostProcess.onApply = function (effect) {
  83648. if (!_this._scene.activeCamera) {
  83649. return;
  83650. }
  83651. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  83652. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  83653. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  83654. // Lens start rotation matrix
  83655. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  83656. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  83657. 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));
  83658. camRot *= 4.0;
  83659. 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);
  83660. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  83661. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  83662. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  83663. };
  83664. };
  83665. // Create depth-of-field post-process
  83666. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  83667. var _this = this;
  83668. 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);
  83669. this.depthOfFieldPostProcess.onApply = function (effect) {
  83670. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  83671. effect.setTexture("depthSampler", _this._getDepthTexture());
  83672. effect.setFloat("distance", _this.depthOfFieldDistance);
  83673. };
  83674. // Add to pipeline
  83675. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  83676. };
  83677. // Create motion blur post-process
  83678. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  83679. var _this = this;
  83680. 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);
  83681. var motionScale = 0;
  83682. var prevViewProjection = BABYLON.Matrix.Identity();
  83683. var invViewProjection = BABYLON.Matrix.Identity();
  83684. var viewProjection = BABYLON.Matrix.Identity();
  83685. var screenSize = BABYLON.Vector2.Zero();
  83686. this.motionBlurPostProcess.onApply = function (effect) {
  83687. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  83688. viewProjection.invertToRef(invViewProjection);
  83689. effect.setMatrix("inverseViewProjection", invViewProjection);
  83690. effect.setMatrix("prevViewProjection", prevViewProjection);
  83691. prevViewProjection = viewProjection;
  83692. screenSize.x = _this.motionBlurPostProcess.width;
  83693. screenSize.y = _this.motionBlurPostProcess.height;
  83694. effect.setVector2("screenSize", screenSize);
  83695. motionScale = scene.getEngine().getFps() / 60.0;
  83696. effect.setFloat("motionScale", motionScale);
  83697. effect.setFloat("motionStrength", _this.motionStrength);
  83698. effect.setTexture("depthSampler", _this._getDepthTexture());
  83699. };
  83700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  83701. };
  83702. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  83703. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  83704. var renderer = this._scene.enableGeometryBufferRenderer();
  83705. return renderer.getGBuffer().textures[0];
  83706. }
  83707. return this._scene.enableDepthRenderer().getDepthMap();
  83708. };
  83709. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  83710. for (var i = 0; i < this._cameras.length; i++) {
  83711. var camera = this._cameras[i];
  83712. if (this.originalPostProcess) {
  83713. this.originalPostProcess.dispose(camera);
  83714. }
  83715. if (this.downSampleX4PostProcess) {
  83716. this.downSampleX4PostProcess.dispose(camera);
  83717. }
  83718. if (this.brightPassPostProcess) {
  83719. this.brightPassPostProcess.dispose(camera);
  83720. }
  83721. if (this.textureAdderPostProcess) {
  83722. this.textureAdderPostProcess.dispose(camera);
  83723. }
  83724. if (this.textureAdderFinalPostProcess) {
  83725. this.textureAdderFinalPostProcess.dispose(camera);
  83726. }
  83727. if (this.volumetricLightPostProcess) {
  83728. this.volumetricLightPostProcess.dispose(camera);
  83729. }
  83730. if (this.volumetricLightSmoothXPostProcess) {
  83731. this.volumetricLightSmoothXPostProcess.dispose(camera);
  83732. }
  83733. if (this.volumetricLightSmoothYPostProcess) {
  83734. this.volumetricLightSmoothYPostProcess.dispose(camera);
  83735. }
  83736. if (this.volumetricLightMergePostProces) {
  83737. this.volumetricLightMergePostProces.dispose(camera);
  83738. }
  83739. if (this.volumetricLightFinalPostProcess) {
  83740. this.volumetricLightFinalPostProcess.dispose(camera);
  83741. }
  83742. if (this.lensFlarePostProcess) {
  83743. this.lensFlarePostProcess.dispose(camera);
  83744. }
  83745. if (this.lensFlareComposePostProcess) {
  83746. this.lensFlareComposePostProcess.dispose(camera);
  83747. }
  83748. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  83749. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  83750. }
  83751. if (this.luminancePostProcess) {
  83752. this.luminancePostProcess.dispose(camera);
  83753. }
  83754. if (this.hdrPostProcess) {
  83755. this.hdrPostProcess.dispose(camera);
  83756. }
  83757. if (this.hdrFinalPostProcess) {
  83758. this.hdrFinalPostProcess.dispose(camera);
  83759. }
  83760. if (this.depthOfFieldPostProcess) {
  83761. this.depthOfFieldPostProcess.dispose(camera);
  83762. }
  83763. if (this.motionBlurPostProcess) {
  83764. this.motionBlurPostProcess.dispose(camera);
  83765. }
  83766. if (this.fxaaPostProcess) {
  83767. this.fxaaPostProcess.dispose(camera);
  83768. }
  83769. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  83770. this.blurHPostProcesses[j].dispose(camera);
  83771. }
  83772. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  83773. this.blurVPostProcesses[j].dispose(camera);
  83774. }
  83775. }
  83776. this.originalPostProcess = null;
  83777. this.downSampleX4PostProcess = null;
  83778. this.brightPassPostProcess = null;
  83779. this.textureAdderPostProcess = null;
  83780. this.textureAdderFinalPostProcess = null;
  83781. this.volumetricLightPostProcess = null;
  83782. this.volumetricLightSmoothXPostProcess = null;
  83783. this.volumetricLightSmoothYPostProcess = null;
  83784. this.volumetricLightMergePostProces = null;
  83785. this.volumetricLightFinalPostProcess = null;
  83786. this.lensFlarePostProcess = null;
  83787. this.lensFlareComposePostProcess = null;
  83788. this.luminancePostProcess = null;
  83789. this.hdrPostProcess = null;
  83790. this.hdrFinalPostProcess = null;
  83791. this.depthOfFieldPostProcess = null;
  83792. this.motionBlurPostProcess = null;
  83793. this.fxaaPostProcess = null;
  83794. this.luminanceDownSamplePostProcesses = [];
  83795. this.blurHPostProcesses = [];
  83796. this.blurVPostProcesses = [];
  83797. };
  83798. /**
  83799. * Dispose of the pipeline and stop all post processes
  83800. */
  83801. StandardRenderingPipeline.prototype.dispose = function () {
  83802. this._disposePostProcesses();
  83803. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83804. _super.prototype.dispose.call(this);
  83805. };
  83806. /**
  83807. * Serialize the rendering pipeline (Used when exporting)
  83808. * @returns the serialized object
  83809. */
  83810. StandardRenderingPipeline.prototype.serialize = function () {
  83811. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83812. if (this.sourceLight) {
  83813. serializationObject.sourceLightId = this.sourceLight.id;
  83814. }
  83815. serializationObject.customType = "StandardRenderingPipeline";
  83816. return serializationObject;
  83817. };
  83818. /**
  83819. * Parse the serialized pipeline
  83820. * @param source Source pipeline.
  83821. * @param scene The scene to load the pipeline to.
  83822. * @param rootUrl The URL of the serialized pipeline.
  83823. * @returns An instantiated pipeline from the serialized object.
  83824. */
  83825. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83826. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83827. if (source.sourceLightId) {
  83828. p.sourceLight = scene.getLightByID(source.sourceLightId);
  83829. }
  83830. return p;
  83831. };
  83832. // Luminance steps
  83833. StandardRenderingPipeline.LuminanceSteps = 6;
  83834. __decorate([
  83835. BABYLON.serialize()
  83836. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  83837. __decorate([
  83838. BABYLON.serialize()
  83839. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  83840. __decorate([
  83841. BABYLON.serialize()
  83842. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  83843. __decorate([
  83844. BABYLON.serialize()
  83845. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  83846. __decorate([
  83847. BABYLON.serializeAsTexture("lensTexture")
  83848. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  83849. __decorate([
  83850. BABYLON.serialize()
  83851. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  83852. __decorate([
  83853. BABYLON.serialize()
  83854. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  83855. __decorate([
  83856. BABYLON.serialize()
  83857. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  83858. __decorate([
  83859. BABYLON.serialize()
  83860. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  83861. __decorate([
  83862. BABYLON.serialize()
  83863. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  83864. __decorate([
  83865. BABYLON.serialize()
  83866. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  83867. __decorate([
  83868. BABYLON.serializeAsTexture("lensColorTexture")
  83869. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  83870. __decorate([
  83871. BABYLON.serialize()
  83872. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  83873. __decorate([
  83874. BABYLON.serialize()
  83875. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  83876. __decorate([
  83877. BABYLON.serialize()
  83878. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  83879. __decorate([
  83880. BABYLON.serialize()
  83881. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  83882. __decorate([
  83883. BABYLON.serializeAsTexture("lensStarTexture")
  83884. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  83885. __decorate([
  83886. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  83887. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  83888. __decorate([
  83889. BABYLON.serialize()
  83890. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  83891. __decorate([
  83892. BABYLON.serialize()
  83893. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  83894. __decorate([
  83895. BABYLON.serialize()
  83896. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  83897. __decorate([
  83898. BABYLON.serialize()
  83899. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  83900. __decorate([
  83901. BABYLON.serialize()
  83902. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  83903. __decorate([
  83904. BABYLON.serialize()
  83905. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  83906. __decorate([
  83907. BABYLON.serialize()
  83908. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  83909. __decorate([
  83910. BABYLON.serialize()
  83911. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  83912. __decorate([
  83913. BABYLON.serialize()
  83914. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  83915. __decorate([
  83916. BABYLON.serialize()
  83917. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  83918. __decorate([
  83919. BABYLON.serialize()
  83920. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  83921. __decorate([
  83922. BABYLON.serialize()
  83923. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  83924. __decorate([
  83925. BABYLON.serialize()
  83926. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  83927. __decorate([
  83928. BABYLON.serialize()
  83929. ], StandardRenderingPipeline.prototype, "samples", null);
  83930. return StandardRenderingPipeline;
  83931. }(BABYLON.PostProcessRenderPipeline));
  83932. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  83933. })(BABYLON || (BABYLON = {}));
  83934. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  83935. var BABYLON;
  83936. (function (BABYLON) {
  83937. var FxaaPostProcess = /** @class */ (function (_super) {
  83938. __extends(FxaaPostProcess, _super);
  83939. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83940. if (camera === void 0) { camera = null; }
  83941. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83942. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  83943. var defines = _this._getDefines();
  83944. _this.updateEffect(defines);
  83945. _this.onApplyObservable.add(function (effect) {
  83946. var texelSize = _this.texelSize;
  83947. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  83948. });
  83949. return _this;
  83950. }
  83951. FxaaPostProcess.prototype._getDefines = function () {
  83952. var engine = this.getEngine();
  83953. if (!engine) {
  83954. return null;
  83955. }
  83956. var glInfo = engine.getGlInfo();
  83957. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  83958. return "#define MALI 1\n";
  83959. }
  83960. return null;
  83961. };
  83962. return FxaaPostProcess;
  83963. }(BABYLON.PostProcess));
  83964. BABYLON.FxaaPostProcess = FxaaPostProcess;
  83965. })(BABYLON || (BABYLON = {}));
  83966. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  83967. var BABYLON;
  83968. (function (BABYLON) {
  83969. /**
  83970. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  83971. */
  83972. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  83973. __extends(ChromaticAberrationPostProcess, _super);
  83974. /**
  83975. * Creates a new instance ChromaticAberrationPostProcess
  83976. * @param name The name of the effect.
  83977. * @param screenWidth The width of the screen to apply the effect on.
  83978. * @param screenHeight The height of the screen to apply the effect on.
  83979. * @param options The required width/height ratio to downsize to before computing the render pass.
  83980. * @param camera The camera to apply the render pass to.
  83981. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83982. * @param engine The engine which the post process will be applied. (default: current engine)
  83983. * @param reusable If the post process can be reused on the same frame. (default: false)
  83984. * @param textureType Type of textures used when performing the post process. (default: 0)
  83985. * @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)
  83986. */
  83987. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83988. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83989. if (blockCompilation === void 0) { blockCompilation = false; }
  83990. 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;
  83991. /**
  83992. * The amount of seperation of rgb channels (default: 30)
  83993. */
  83994. _this.aberrationAmount = 30;
  83995. /**
  83996. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  83997. */
  83998. _this.radialIntensity = 0;
  83999. /**
  84000. * 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))
  84001. */
  84002. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  84003. /**
  84004. * 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))
  84005. */
  84006. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  84007. _this.onApplyObservable.add(function (effect) {
  84008. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  84009. effect.setFloat('screen_width', screenWidth);
  84010. effect.setFloat('screen_height', screenHeight);
  84011. effect.setFloat('radialIntensity', _this.radialIntensity);
  84012. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  84013. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  84014. });
  84015. return _this;
  84016. }
  84017. return ChromaticAberrationPostProcess;
  84018. }(BABYLON.PostProcess));
  84019. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  84020. })(BABYLON || (BABYLON = {}));
  84021. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  84022. var BABYLON;
  84023. (function (BABYLON) {
  84024. /**
  84025. * The GrainPostProcess adds noise to the image at mid luminance levels
  84026. */
  84027. var GrainPostProcess = /** @class */ (function (_super) {
  84028. __extends(GrainPostProcess, _super);
  84029. /**
  84030. * Creates a new instance of @see GrainPostProcess
  84031. * @param name The name of the effect.
  84032. * @param options The required width/height ratio to downsize to before computing the render pass.
  84033. * @param camera The camera to apply the render pass to.
  84034. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84035. * @param engine The engine which the post process will be applied. (default: current engine)
  84036. * @param reusable If the post process can be reused on the same frame. (default: false)
  84037. * @param textureType Type of textures used when performing the post process. (default: 0)
  84038. * @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)
  84039. */
  84040. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84041. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84042. if (blockCompilation === void 0) { blockCompilation = false; }
  84043. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84044. /**
  84045. * The intensity of the grain added (default: 30)
  84046. */
  84047. _this.intensity = 30;
  84048. /**
  84049. * If the grain should be randomized on every frame
  84050. */
  84051. _this.animated = false;
  84052. _this.onApplyObservable.add(function (effect) {
  84053. effect.setFloat('intensity', _this.intensity);
  84054. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84055. });
  84056. return _this;
  84057. }
  84058. return GrainPostProcess;
  84059. }(BABYLON.PostProcess));
  84060. BABYLON.GrainPostProcess = GrainPostProcess;
  84061. })(BABYLON || (BABYLON = {}));
  84062. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84063. var BABYLON;
  84064. (function (BABYLON) {
  84065. /**
  84066. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84067. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84068. */
  84069. var SharpenPostProcess = /** @class */ (function (_super) {
  84070. __extends(SharpenPostProcess, _super);
  84071. /**
  84072. * Creates a new instance ConvolutionPostProcess
  84073. * @param name The name of the effect.
  84074. * @param options The required width/height ratio to downsize to before computing the render pass.
  84075. * @param camera The camera to apply the render pass to.
  84076. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84077. * @param engine The engine which the post process will be applied. (default: current engine)
  84078. * @param reusable If the post process can be reused on the same frame. (default: false)
  84079. * @param textureType Type of textures used when performing the post process. (default: 0)
  84080. * @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)
  84081. */
  84082. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84083. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84084. if (blockCompilation === void 0) { blockCompilation = false; }
  84085. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84086. /**
  84087. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84088. */
  84089. _this.colorAmount = 1.0;
  84090. /**
  84091. * How much sharpness should be applied (default: 0.3)
  84092. */
  84093. _this.edgeAmount = 0.3;
  84094. _this.onApply = function (effect) {
  84095. effect.setFloat2("screenSize", _this.width, _this.height);
  84096. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84097. };
  84098. return _this;
  84099. }
  84100. return SharpenPostProcess;
  84101. }(BABYLON.PostProcess));
  84102. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84103. })(BABYLON || (BABYLON = {}));
  84104. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84105. var BABYLON;
  84106. (function (BABYLON) {
  84107. /**
  84108. * The Blur Post Process which blurs an image based on a kernel and direction.
  84109. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84110. */
  84111. var BlurPostProcess = /** @class */ (function (_super) {
  84112. __extends(BlurPostProcess, _super);
  84113. /**
  84114. * Creates a new instance BlurPostProcess
  84115. * @param name The name of the effect.
  84116. * @param direction The direction in which to blur the image.
  84117. * @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.
  84118. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84119. * @param camera The camera to apply the render pass to.
  84120. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84121. * @param engine The engine which the post process will be applied. (default: current engine)
  84122. * @param reusable If the post process can be reused on the same frame. (default: false)
  84123. * @param textureType Type of textures used when performing the post process. (default: 0)
  84124. * @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)
  84125. */
  84126. function BlurPostProcess(name,
  84127. /** The direction in which to blur the image. */
  84128. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84130. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84131. if (defines === void 0) { defines = ""; }
  84132. if (blockCompilation === void 0) { blockCompilation = false; }
  84133. 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;
  84134. _this.direction = direction;
  84135. _this.blockCompilation = blockCompilation;
  84136. _this._packedFloat = false;
  84137. _this._staticDefines = "";
  84138. _this._staticDefines = defines;
  84139. _this.onApplyObservable.add(function (effect) {
  84140. if (_this._outputTexture) {
  84141. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84142. }
  84143. else {
  84144. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84145. }
  84146. });
  84147. _this.kernel = kernel;
  84148. return _this;
  84149. }
  84150. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84151. /**
  84152. * Gets the length in pixels of the blur sample region
  84153. */
  84154. get: function () {
  84155. return this._idealKernel;
  84156. },
  84157. /**
  84158. * Sets the length in pixels of the blur sample region
  84159. */
  84160. set: function (v) {
  84161. if (this._idealKernel === v) {
  84162. return;
  84163. }
  84164. v = Math.max(v, 1);
  84165. this._idealKernel = v;
  84166. this._kernel = this._nearestBestKernel(v);
  84167. if (!this.blockCompilation) {
  84168. this._updateParameters();
  84169. }
  84170. },
  84171. enumerable: true,
  84172. configurable: true
  84173. });
  84174. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84175. /**
  84176. * Gets wether or not the blur is unpacking/repacking floats
  84177. */
  84178. get: function () {
  84179. return this._packedFloat;
  84180. },
  84181. /**
  84182. * Sets wether or not the blur needs to unpack/repack floats
  84183. */
  84184. set: function (v) {
  84185. if (this._packedFloat === v) {
  84186. return;
  84187. }
  84188. this._packedFloat = v;
  84189. if (!this.blockCompilation) {
  84190. this._updateParameters();
  84191. }
  84192. },
  84193. enumerable: true,
  84194. configurable: true
  84195. });
  84196. /**
  84197. * Updates the effect with the current post process compile time values and recompiles the shader.
  84198. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84199. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84200. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84201. * @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
  84202. * @param onCompiled Called when the shader has been compiled.
  84203. * @param onError Called if there is an error when compiling a shader.
  84204. */
  84205. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84206. if (defines === void 0) { defines = null; }
  84207. if (uniforms === void 0) { uniforms = null; }
  84208. if (samplers === void 0) { samplers = null; }
  84209. this._updateParameters(onCompiled, onError);
  84210. };
  84211. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84212. // Generate sampling offsets and weights
  84213. var N = this._kernel;
  84214. var centerIndex = (N - 1) / 2;
  84215. // Generate Gaussian sampling weights over kernel
  84216. var offsets = [];
  84217. var weights = [];
  84218. var totalWeight = 0;
  84219. for (var i = 0; i < N; i++) {
  84220. var u = i / (N - 1);
  84221. var w = this._gaussianWeight(u * 2.0 - 1);
  84222. offsets[i] = (i - centerIndex);
  84223. weights[i] = w;
  84224. totalWeight += w;
  84225. }
  84226. // Normalize weights
  84227. for (var i = 0; i < weights.length; i++) {
  84228. weights[i] /= totalWeight;
  84229. }
  84230. // Optimize: combine samples to take advantage of hardware linear sampling
  84231. // Walk from left to center, combining pairs (symmetrically)
  84232. var linearSamplingWeights = [];
  84233. var linearSamplingOffsets = [];
  84234. var linearSamplingMap = [];
  84235. for (var i = 0; i <= centerIndex; i += 2) {
  84236. var j = Math.min(i + 1, Math.floor(centerIndex));
  84237. var singleCenterSample = i === j;
  84238. if (singleCenterSample) {
  84239. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84240. }
  84241. else {
  84242. var sharedCell = j === centerIndex;
  84243. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84244. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84245. if (offsetLinear === 0) {
  84246. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84247. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84248. }
  84249. else {
  84250. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84251. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84252. }
  84253. }
  84254. }
  84255. for (var i = 0; i < linearSamplingMap.length; i++) {
  84256. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84257. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84258. }
  84259. // Replace with optimized
  84260. offsets = linearSamplingOffsets;
  84261. weights = linearSamplingWeights;
  84262. // Generate shaders
  84263. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84264. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84265. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84266. var defines = "";
  84267. defines += this._staticDefines;
  84268. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84269. if (this._staticDefines.indexOf("DOF") != -1) {
  84270. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84271. varyingCount--;
  84272. }
  84273. for (var i = 0; i < varyingCount; i++) {
  84274. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84275. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84276. }
  84277. var depCount = 0;
  84278. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84279. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  84280. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  84281. depCount++;
  84282. }
  84283. if (this.packedFloat) {
  84284. defines += "#define PACKEDFLOAT 1";
  84285. }
  84286. this.blockCompilation = false;
  84287. _super.prototype.updateEffect.call(this, defines, null, null, {
  84288. varyingCount: varyingCount,
  84289. depCount: depCount
  84290. }, onCompiled, onError);
  84291. };
  84292. /**
  84293. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  84294. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  84295. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  84296. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  84297. * The gaps between physical kernels are compensated for in the weighting of the samples
  84298. * @param idealKernel Ideal blur kernel.
  84299. * @return Nearest best kernel.
  84300. */
  84301. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  84302. var v = Math.round(idealKernel);
  84303. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  84304. var k = _a[_i];
  84305. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  84306. return Math.max(k, 3);
  84307. }
  84308. }
  84309. return Math.max(v, 3);
  84310. };
  84311. /**
  84312. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  84313. * @param x The point on the Gaussian distribution to sample.
  84314. * @return the value of the Gaussian function at x.
  84315. */
  84316. BlurPostProcess.prototype._gaussianWeight = function (x) {
  84317. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  84318. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  84319. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  84320. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  84321. // truncated at around 1.3% of peak strength.
  84322. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  84323. var sigma = (1 / 3);
  84324. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  84325. var exponent = -((x * x) / (2.0 * sigma * sigma));
  84326. var weight = (1.0 / denominator) * Math.exp(exponent);
  84327. return weight;
  84328. };
  84329. /**
  84330. * Generates a string that can be used as a floating point number in GLSL.
  84331. * @param x Value to print.
  84332. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  84333. * @return GLSL float string.
  84334. */
  84335. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  84336. if (decimalFigures === void 0) { decimalFigures = 8; }
  84337. return x.toFixed(decimalFigures).replace(/0+$/, '');
  84338. };
  84339. return BlurPostProcess;
  84340. }(BABYLON.PostProcess));
  84341. BABYLON.BlurPostProcess = BlurPostProcess;
  84342. })(BABYLON || (BABYLON = {}));
  84343. //# sourceMappingURL=babylon.blurPostProcess.js.map
  84344. var BABYLON;
  84345. (function (BABYLON) {
  84346. /**
  84347. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  84348. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  84349. * based on samples that have a large difference in distance than the center pixel.
  84350. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  84351. */
  84352. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  84353. __extends(DepthOfFieldBlurPostProcess, _super);
  84354. /**
  84355. * Creates a new instance CircleOfConfusionPostProcess
  84356. * @param name The name of the effect.
  84357. * @param scene The scene the effect belongs to.
  84358. * @param direction The direction the blur should be applied.
  84359. * @param kernel The size of the kernel used to blur.
  84360. * @param options The required width/height ratio to downsize to before computing the render pass.
  84361. * @param camera The camera to apply the render pass to.
  84362. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  84363. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  84364. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84365. * @param engine The engine which the post process will be applied. (default: current engine)
  84366. * @param reusable If the post process can be reused on the same frame. (default: false)
  84367. * @param textureType Type of textures used when performing the post process. (default: 0)
  84368. * @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)
  84369. */
  84370. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  84371. if (imageToBlur === void 0) { imageToBlur = null; }
  84372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84373. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84374. if (blockCompilation === void 0) { blockCompilation = false; }
  84375. 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;
  84376. _this.direction = direction;
  84377. _this.onApplyObservable.add(function (effect) {
  84378. if (imageToBlur != null) {
  84379. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  84380. }
  84381. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  84382. if (scene.activeCamera) {
  84383. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84384. }
  84385. });
  84386. return _this;
  84387. }
  84388. return DepthOfFieldBlurPostProcess;
  84389. }(BABYLON.BlurPostProcess));
  84390. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  84391. })(BABYLON || (BABYLON = {}));
  84392. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  84393. var BABYLON;
  84394. (function (BABYLON) {
  84395. /**
  84396. * Options to be set when merging outputs from the default pipeline.
  84397. */
  84398. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  84399. function DepthOfFieldMergePostProcessOptions() {
  84400. }
  84401. return DepthOfFieldMergePostProcessOptions;
  84402. }());
  84403. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  84404. /**
  84405. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  84406. */
  84407. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  84408. __extends(DepthOfFieldMergePostProcess, _super);
  84409. /**
  84410. * Creates a new instance of DepthOfFieldMergePostProcess
  84411. * @param name The name of the effect.
  84412. * @param originalFromInput Post process which's input will be used for the merge.
  84413. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  84414. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  84415. * @param options The required width/height ratio to downsize to before computing the render pass.
  84416. * @param camera The camera to apply the render pass to.
  84417. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84418. * @param engine The engine which the post process will be applied. (default: current engine)
  84419. * @param reusable If the post process can be reused on the same frame. (default: false)
  84420. * @param textureType Type of textures used when performing the post process. (default: 0)
  84421. * @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)
  84422. */
  84423. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84424. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84425. if (blockCompilation === void 0) { blockCompilation = false; }
  84426. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  84427. _this.blurSteps = blurSteps;
  84428. _this.onApplyObservable.add(function (effect) {
  84429. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  84430. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  84431. blurSteps.forEach(function (step, index) {
  84432. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  84433. });
  84434. });
  84435. if (!blockCompilation) {
  84436. _this.updateEffect();
  84437. }
  84438. return _this;
  84439. }
  84440. /**
  84441. * Updates the effect with the current post process compile time values and recompiles the shader.
  84442. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84443. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84444. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84445. * @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
  84446. * @param onCompiled Called when the shader has been compiled.
  84447. * @param onError Called if there is an error when compiling a shader.
  84448. */
  84449. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84450. if (defines === void 0) { defines = null; }
  84451. if (uniforms === void 0) { uniforms = null; }
  84452. if (samplers === void 0) { samplers = null; }
  84453. if (!defines) {
  84454. defines = "";
  84455. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  84456. }
  84457. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  84458. };
  84459. return DepthOfFieldMergePostProcess;
  84460. }(BABYLON.PostProcess));
  84461. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  84462. })(BABYLON || (BABYLON = {}));
  84463. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  84464. var BABYLON;
  84465. (function (BABYLON) {
  84466. /**
  84467. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  84468. */
  84469. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  84470. __extends(CircleOfConfusionPostProcess, _super);
  84471. /**
  84472. * Creates a new instance CircleOfConfusionPostProcess
  84473. * @param name The name of the effect.
  84474. * @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.
  84475. * @param options The required width/height ratio to downsize to before computing the render pass.
  84476. * @param camera The camera to apply the render pass to.
  84477. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84478. * @param engine The engine which the post process will be applied. (default: current engine)
  84479. * @param reusable If the post process can be reused on the same frame. (default: false)
  84480. * @param textureType Type of textures used when performing the post process. (default: 0)
  84481. * @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)
  84482. */
  84483. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84484. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84485. if (blockCompilation === void 0) { blockCompilation = false; }
  84486. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84487. /**
  84488. * 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.
  84489. */
  84490. _this.lensSize = 50;
  84491. /**
  84492. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  84493. */
  84494. _this.fStop = 1.4;
  84495. /**
  84496. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  84497. */
  84498. _this.focusDistance = 2000;
  84499. /**
  84500. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  84501. */
  84502. _this.focalLength = 50;
  84503. _this._depthTexture = null;
  84504. _this._depthTexture = depthTexture;
  84505. _this.onApplyObservable.add(function (effect) {
  84506. if (!_this._depthTexture) {
  84507. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  84508. return;
  84509. }
  84510. effect.setTexture("depthSampler", _this._depthTexture);
  84511. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  84512. var aperture = _this.lensSize / _this.fStop;
  84513. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  84514. effect.setFloat('focusDistance', _this.focusDistance);
  84515. effect.setFloat('cocPrecalculation', cocPrecalculation);
  84516. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  84517. });
  84518. return _this;
  84519. }
  84520. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  84521. /**
  84522. * 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.
  84523. */
  84524. set: function (value) {
  84525. this._depthTexture = value;
  84526. },
  84527. enumerable: true,
  84528. configurable: true
  84529. });
  84530. return CircleOfConfusionPostProcess;
  84531. }(BABYLON.PostProcess));
  84532. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  84533. })(BABYLON || (BABYLON = {}));
  84534. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  84535. var BABYLON;
  84536. (function (BABYLON) {
  84537. /**
  84538. * Specifies the level of max blur that should be applied when using the depth of field effect
  84539. */
  84540. var DepthOfFieldEffectBlurLevel;
  84541. (function (DepthOfFieldEffectBlurLevel) {
  84542. /**
  84543. * Subtle blur
  84544. */
  84545. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  84546. /**
  84547. * Medium blur
  84548. */
  84549. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  84550. /**
  84551. * Large blur
  84552. */
  84553. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  84554. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  84555. ;
  84556. /**
  84557. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  84558. */
  84559. var DepthOfFieldEffect = /** @class */ (function (_super) {
  84560. __extends(DepthOfFieldEffect, _super);
  84561. /**
  84562. * Creates a new instance DepthOfFieldEffect
  84563. * @param scene The scene the effect belongs to.
  84564. * @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.
  84565. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  84566. * @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)
  84567. */
  84568. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  84569. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  84570. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84571. if (blockCompilation === void 0) { blockCompilation = false; }
  84572. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  84573. return _this._effects;
  84574. }, true) || this;
  84575. /**
  84576. * @hidden Internal post processes in depth of field effect
  84577. */
  84578. _this._effects = [];
  84579. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  84580. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84581. // 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)
  84582. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  84583. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  84584. _this._depthOfFieldBlurY = [];
  84585. _this._depthOfFieldBlurX = [];
  84586. var blurCount = 1;
  84587. var kernelSize = 15;
  84588. switch (blurLevel) {
  84589. case DepthOfFieldEffectBlurLevel.High: {
  84590. blurCount = 3;
  84591. kernelSize = 51;
  84592. break;
  84593. }
  84594. case DepthOfFieldEffectBlurLevel.Medium: {
  84595. blurCount = 2;
  84596. kernelSize = 31;
  84597. break;
  84598. }
  84599. default: {
  84600. kernelSize = 15;
  84601. blurCount = 1;
  84602. break;
  84603. }
  84604. }
  84605. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  84606. var ratio = 1.0;
  84607. for (var i = 0; i < blurCount; i++) {
  84608. 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);
  84609. blurY.autoClear = false;
  84610. ratio = 0.75 / Math.pow(2, i);
  84611. 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);
  84612. blurX.autoClear = false;
  84613. _this._depthOfFieldBlurY.push(blurY);
  84614. _this._depthOfFieldBlurX.push(blurX);
  84615. }
  84616. // Set all post processes on the effect.
  84617. _this._effects = [_this._circleOfConfusion];
  84618. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  84619. _this._effects.push(_this._depthOfFieldBlurY[i]);
  84620. _this._effects.push(_this._depthOfFieldBlurX[i]);
  84621. }
  84622. // Merge blurred images with original image based on circleOfConfusion
  84623. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84624. _this._dofMerge.autoClear = false;
  84625. _this._effects.push(_this._dofMerge);
  84626. return _this;
  84627. }
  84628. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  84629. get: function () {
  84630. return this._circleOfConfusion.focalLength;
  84631. },
  84632. /**
  84633. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  84634. */
  84635. set: function (value) {
  84636. this._circleOfConfusion.focalLength = value;
  84637. },
  84638. enumerable: true,
  84639. configurable: true
  84640. });
  84641. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  84642. get: function () {
  84643. return this._circleOfConfusion.fStop;
  84644. },
  84645. /**
  84646. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  84647. */
  84648. set: function (value) {
  84649. this._circleOfConfusion.fStop = value;
  84650. },
  84651. enumerable: true,
  84652. configurable: true
  84653. });
  84654. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  84655. get: function () {
  84656. return this._circleOfConfusion.focusDistance;
  84657. },
  84658. /**
  84659. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  84660. */
  84661. set: function (value) {
  84662. this._circleOfConfusion.focusDistance = value;
  84663. },
  84664. enumerable: true,
  84665. configurable: true
  84666. });
  84667. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  84668. get: function () {
  84669. return this._circleOfConfusion.lensSize;
  84670. },
  84671. /**
  84672. * 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.
  84673. */
  84674. set: function (value) {
  84675. this._circleOfConfusion.lensSize = value;
  84676. },
  84677. enumerable: true,
  84678. configurable: true
  84679. });
  84680. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  84681. /**
  84682. * 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.
  84683. */
  84684. set: function (value) {
  84685. this._circleOfConfusion.depthTexture = value;
  84686. },
  84687. enumerable: true,
  84688. configurable: true
  84689. });
  84690. /**
  84691. * Disposes each of the internal effects for a given camera.
  84692. * @param camera The camera to dispose the effect on.
  84693. */
  84694. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  84695. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84696. this._effects[effectIndex].dispose(camera);
  84697. }
  84698. };
  84699. /**
  84700. * @hidden Internal
  84701. */
  84702. DepthOfFieldEffect.prototype._updateEffects = function () {
  84703. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84704. this._effects[effectIndex].updateEffect();
  84705. }
  84706. };
  84707. /**
  84708. * Internal
  84709. * @returns if all the contained post processes are ready.
  84710. * @hidden
  84711. */
  84712. DepthOfFieldEffect.prototype._isReady = function () {
  84713. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84714. if (!this._effects[effectIndex].isReady()) {
  84715. return false;
  84716. }
  84717. }
  84718. return true;
  84719. };
  84720. return DepthOfFieldEffect;
  84721. }(BABYLON.PostProcessRenderEffect));
  84722. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  84723. })(BABYLON || (BABYLON = {}));
  84724. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  84725. var BABYLON;
  84726. (function (BABYLON) {
  84727. /**
  84728. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  84729. */
  84730. var BloomMergePostProcess = /** @class */ (function (_super) {
  84731. __extends(BloomMergePostProcess, _super);
  84732. /**
  84733. * Creates a new instance of @see BloomMergePostProcess
  84734. * @param name The name of the effect.
  84735. * @param originalFromInput Post process which's input will be used for the merge.
  84736. * @param blurred Blurred highlights post process which's output will be used.
  84737. * @param weight Weight of the bloom to be added to the original input.
  84738. * @param options The required width/height ratio to downsize to before computing the render pass.
  84739. * @param camera The camera to apply the render pass to.
  84740. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84741. * @param engine The engine which the post process will be applied. (default: current engine)
  84742. * @param reusable If the post process can be reused on the same frame. (default: false)
  84743. * @param textureType Type of textures used when performing the post process. (default: 0)
  84744. * @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)
  84745. */
  84746. function BloomMergePostProcess(name, originalFromInput, blurred,
  84747. /** Weight of the bloom to be added to the original input. */
  84748. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84749. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84750. if (blockCompilation === void 0) { blockCompilation = false; }
  84751. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  84752. _this.weight = weight;
  84753. _this.onApplyObservable.add(function (effect) {
  84754. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  84755. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  84756. effect.setFloat("bloomWeight", _this.weight);
  84757. });
  84758. if (!blockCompilation) {
  84759. _this.updateEffect();
  84760. }
  84761. return _this;
  84762. }
  84763. return BloomMergePostProcess;
  84764. }(BABYLON.PostProcess));
  84765. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  84766. })(BABYLON || (BABYLON = {}));
  84767. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  84768. var BABYLON;
  84769. (function (BABYLON) {
  84770. /**
  84771. * 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.
  84772. */
  84773. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  84774. __extends(ExtractHighlightsPostProcess, _super);
  84775. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84777. if (blockCompilation === void 0) { blockCompilation = false; }
  84778. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84779. /**
  84780. * The luminance threshold, pixels below this value will be set to black.
  84781. */
  84782. _this.threshold = 0.9;
  84783. /** @hidden */
  84784. _this._exposure = 1;
  84785. /**
  84786. * Post process which has the input texture to be used when performing highlight extraction
  84787. * @hidden
  84788. */
  84789. _this._inputPostProcess = null;
  84790. _this.onApplyObservable.add(function (effect) {
  84791. if (_this._inputPostProcess) {
  84792. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  84793. }
  84794. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  84795. effect.setFloat('exposure', _this._exposure);
  84796. });
  84797. return _this;
  84798. }
  84799. return ExtractHighlightsPostProcess;
  84800. }(BABYLON.PostProcess));
  84801. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  84802. })(BABYLON || (BABYLON = {}));
  84803. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  84804. var BABYLON;
  84805. (function (BABYLON) {
  84806. /**
  84807. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  84808. */
  84809. var BloomEffect = /** @class */ (function (_super) {
  84810. __extends(BloomEffect, _super);
  84811. /**
  84812. * Creates a new instance of @see BloomEffect
  84813. * @param scene The scene the effect belongs to.
  84814. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  84815. * @param bloomKernel The size of the kernel to be used when applying the blur.
  84816. * @param bloomWeight The the strength of bloom.
  84817. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  84818. * @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)
  84819. */
  84820. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  84821. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84822. if (blockCompilation === void 0) { blockCompilation = false; }
  84823. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  84824. return _this._effects;
  84825. }, true) || this;
  84826. _this.bloomScale = bloomScale;
  84827. /**
  84828. * @hidden Internal
  84829. */
  84830. _this._effects = [];
  84831. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84832. _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);
  84833. _this._blurX.alwaysForcePOT = true;
  84834. _this._blurX.autoClear = false;
  84835. _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);
  84836. _this._blurY.alwaysForcePOT = true;
  84837. _this._blurY.autoClear = false;
  84838. _this.kernel = bloomKernel;
  84839. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  84840. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84841. _this._merge.autoClear = false;
  84842. _this._effects.push(_this._merge);
  84843. return _this;
  84844. }
  84845. Object.defineProperty(BloomEffect.prototype, "threshold", {
  84846. /**
  84847. * The luminance threshold to find bright areas of the image to bloom.
  84848. */
  84849. get: function () {
  84850. return this._downscale.threshold;
  84851. },
  84852. set: function (value) {
  84853. this._downscale.threshold = value;
  84854. },
  84855. enumerable: true,
  84856. configurable: true
  84857. });
  84858. Object.defineProperty(BloomEffect.prototype, "weight", {
  84859. /**
  84860. * The strength of the bloom.
  84861. */
  84862. get: function () {
  84863. return this._merge.weight;
  84864. },
  84865. set: function (value) {
  84866. this._merge.weight = value;
  84867. },
  84868. enumerable: true,
  84869. configurable: true
  84870. });
  84871. Object.defineProperty(BloomEffect.prototype, "kernel", {
  84872. /**
  84873. * Specifies the size of the bloom blur kernel, relative to the final output size
  84874. */
  84875. get: function () {
  84876. return this._blurX.kernel / this.bloomScale;
  84877. },
  84878. set: function (value) {
  84879. this._blurX.kernel = value * this.bloomScale;
  84880. this._blurY.kernel = value * this.bloomScale;
  84881. },
  84882. enumerable: true,
  84883. configurable: true
  84884. });
  84885. /**
  84886. * Disposes each of the internal effects for a given camera.
  84887. * @param camera The camera to dispose the effect on.
  84888. */
  84889. BloomEffect.prototype.disposeEffects = function (camera) {
  84890. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84891. this._effects[effectIndex].dispose(camera);
  84892. }
  84893. };
  84894. /**
  84895. * @hidden Internal
  84896. */
  84897. BloomEffect.prototype._updateEffects = function () {
  84898. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84899. this._effects[effectIndex].updateEffect();
  84900. }
  84901. };
  84902. /**
  84903. * Internal
  84904. * @returns if all the contained post processes are ready.
  84905. * @hidden
  84906. */
  84907. BloomEffect.prototype._isReady = function () {
  84908. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84909. if (!this._effects[effectIndex].isReady()) {
  84910. return false;
  84911. }
  84912. }
  84913. return true;
  84914. };
  84915. return BloomEffect;
  84916. }(BABYLON.PostProcessRenderEffect));
  84917. BABYLON.BloomEffect = BloomEffect;
  84918. })(BABYLON || (BABYLON = {}));
  84919. //# sourceMappingURL=babylon.bloomEffect.js.map
  84920. var BABYLON;
  84921. (function (BABYLON) {
  84922. /**
  84923. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  84924. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  84925. */
  84926. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  84927. __extends(DefaultRenderingPipeline, _super);
  84928. /**
  84929. * @constructor
  84930. * @param {string} name - The rendering pipeline name (default: "")
  84931. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  84932. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  84933. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  84934. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  84935. */
  84936. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  84937. if (name === void 0) { name = ""; }
  84938. if (hdr === void 0) { hdr = true; }
  84939. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  84940. if (automaticBuild === void 0) { automaticBuild = true; }
  84941. var _this = _super.call(this, scene.getEngine(), name) || this;
  84942. _this._camerasToBeAttached = [];
  84943. /**
  84944. * ID of the sharpen post process,
  84945. */
  84946. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  84947. /**
  84948. * ID of the image processing post process;
  84949. */
  84950. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  84951. /**
  84952. * ID of the Fast Approximate Anti-Aliasing post process;
  84953. */
  84954. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  84955. /**
  84956. * ID of the chromatic aberration post process,
  84957. */
  84958. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  84959. /**
  84960. * ID of the grain post process
  84961. */
  84962. _this.GrainPostProcessId = "GrainPostProcessEffect";
  84963. /**
  84964. * Glow post process which adds a glow to emmisive areas of the image
  84965. */
  84966. _this._glowLayer = null;
  84967. /**
  84968. * Animations which can be used to tweak settings over a period of time
  84969. */
  84970. _this.animations = [];
  84971. _this._imageProcessingConfigurationObserver = null;
  84972. // Values
  84973. _this._sharpenEnabled = false;
  84974. _this._bloomEnabled = false;
  84975. _this._depthOfFieldEnabled = false;
  84976. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  84977. _this._fxaaEnabled = false;
  84978. _this._imageProcessingEnabled = true;
  84979. _this._bloomScale = 0.5;
  84980. _this._chromaticAberrationEnabled = false;
  84981. _this._grainEnabled = false;
  84982. _this._buildAllowed = true;
  84983. _this._resizeObserver = null;
  84984. _this._hardwareScaleLevel = 1.0;
  84985. _this._bloomKernel = 64;
  84986. /**
  84987. * Specifies the weight of the bloom in the final rendering
  84988. */
  84989. _this._bloomWeight = 0.15;
  84990. /**
  84991. * Specifies the luma threshold for the area that will be blurred by the bloom
  84992. */
  84993. _this._bloomThreshold = 0.9;
  84994. _this._samples = 1;
  84995. _this._hasCleared = false;
  84996. _this._prevPostProcess = null;
  84997. _this._prevPrevPostProcess = null;
  84998. _this._depthOfFieldSceneObserver = null;
  84999. _this._cameras = cameras || scene.cameras;
  85000. _this._cameras = _this._cameras.slice();
  85001. _this._camerasToBeAttached = _this._cameras.slice();
  85002. _this._buildAllowed = automaticBuild;
  85003. // Initialize
  85004. _this._scene = scene;
  85005. var caps = _this._scene.getEngine().getCaps();
  85006. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  85007. // Misc
  85008. if (_this._hdr) {
  85009. if (caps.textureHalfFloatRender) {
  85010. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85011. }
  85012. else if (caps.textureFloatRender) {
  85013. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85014. }
  85015. }
  85016. else {
  85017. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85018. }
  85019. // Attach
  85020. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85021. var engine = _this._scene.getEngine();
  85022. // Create post processes before hand so they can be modified before enabled.
  85023. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  85024. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85025. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  85026. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85027. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85028. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85029. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85030. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85031. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85032. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85033. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85034. _this.bloomKernel = _this.bloomKernel;
  85035. });
  85036. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85037. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85038. });
  85039. _this._buildPipeline();
  85040. return _this;
  85041. }
  85042. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85043. get: function () {
  85044. return this._sharpenEnabled;
  85045. },
  85046. /**
  85047. * Enable or disable the sharpen process from the pipeline
  85048. */
  85049. set: function (enabled) {
  85050. if (this._sharpenEnabled === enabled) {
  85051. return;
  85052. }
  85053. this._sharpenEnabled = enabled;
  85054. this._buildPipeline();
  85055. },
  85056. enumerable: true,
  85057. configurable: true
  85058. });
  85059. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85060. /**
  85061. * Specifies the size of the bloom blur kernel, relative to the final output size
  85062. */
  85063. get: function () {
  85064. return this._bloomKernel;
  85065. },
  85066. set: function (value) {
  85067. this._bloomKernel = value;
  85068. this.bloom.kernel = value / this._hardwareScaleLevel;
  85069. },
  85070. enumerable: true,
  85071. configurable: true
  85072. });
  85073. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85074. get: function () {
  85075. return this._bloomWeight;
  85076. },
  85077. /**
  85078. * The strength of the bloom.
  85079. */
  85080. set: function (value) {
  85081. if (this._bloomWeight === value) {
  85082. return;
  85083. }
  85084. this.bloom.weight = value;
  85085. this._bloomWeight = value;
  85086. },
  85087. enumerable: true,
  85088. configurable: true
  85089. });
  85090. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85091. get: function () {
  85092. return this._bloomThreshold;
  85093. },
  85094. /**
  85095. * The strength of the bloom.
  85096. */
  85097. set: function (value) {
  85098. if (this._bloomThreshold === value) {
  85099. return;
  85100. }
  85101. this.bloom.threshold = value;
  85102. this._bloomThreshold = value;
  85103. },
  85104. enumerable: true,
  85105. configurable: true
  85106. });
  85107. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85108. get: function () {
  85109. return this._bloomScale;
  85110. },
  85111. /**
  85112. * The scale of the bloom, lower value will provide better performance.
  85113. */
  85114. set: function (value) {
  85115. if (this._bloomScale === value) {
  85116. return;
  85117. }
  85118. this._bloomScale = value;
  85119. // recreate bloom and dispose old as this setting is not dynamic
  85120. this._rebuildBloom();
  85121. this._buildPipeline();
  85122. },
  85123. enumerable: true,
  85124. configurable: true
  85125. });
  85126. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85127. get: function () {
  85128. return this._bloomEnabled;
  85129. },
  85130. /**
  85131. * Enable or disable the bloom from the pipeline
  85132. */
  85133. set: function (enabled) {
  85134. if (this._bloomEnabled === enabled) {
  85135. return;
  85136. }
  85137. this._bloomEnabled = enabled;
  85138. this._buildPipeline();
  85139. },
  85140. enumerable: true,
  85141. configurable: true
  85142. });
  85143. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85144. // recreate bloom and dispose old as this setting is not dynamic
  85145. var oldBloom = this.bloom;
  85146. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85147. this.bloom.threshold = oldBloom.threshold;
  85148. for (var i = 0; i < this._cameras.length; i++) {
  85149. oldBloom.disposeEffects(this._cameras[i]);
  85150. }
  85151. };
  85152. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85153. /**
  85154. * If the depth of field is enabled.
  85155. */
  85156. get: function () {
  85157. return this._depthOfFieldEnabled;
  85158. },
  85159. set: function (enabled) {
  85160. if (this._depthOfFieldEnabled === enabled) {
  85161. return;
  85162. }
  85163. this._depthOfFieldEnabled = enabled;
  85164. this._buildPipeline();
  85165. },
  85166. enumerable: true,
  85167. configurable: true
  85168. });
  85169. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85170. /**
  85171. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85172. */
  85173. get: function () {
  85174. return this._depthOfFieldBlurLevel;
  85175. },
  85176. set: function (value) {
  85177. if (this._depthOfFieldBlurLevel === value) {
  85178. return;
  85179. }
  85180. this._depthOfFieldBlurLevel = value;
  85181. // recreate dof and dispose old as this setting is not dynamic
  85182. var oldDof = this.depthOfField;
  85183. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85184. this.depthOfField.focalLength = oldDof.focalLength;
  85185. this.depthOfField.focusDistance = oldDof.focusDistance;
  85186. this.depthOfField.fStop = oldDof.fStop;
  85187. this.depthOfField.lensSize = oldDof.lensSize;
  85188. for (var i = 0; i < this._cameras.length; i++) {
  85189. oldDof.disposeEffects(this._cameras[i]);
  85190. }
  85191. this._buildPipeline();
  85192. },
  85193. enumerable: true,
  85194. configurable: true
  85195. });
  85196. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85197. get: function () {
  85198. return this._fxaaEnabled;
  85199. },
  85200. /**
  85201. * If the anti aliasing is enabled.
  85202. */
  85203. set: function (enabled) {
  85204. if (this._fxaaEnabled === enabled) {
  85205. return;
  85206. }
  85207. this._fxaaEnabled = enabled;
  85208. this._buildPipeline();
  85209. },
  85210. enumerable: true,
  85211. configurable: true
  85212. });
  85213. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85214. get: function () {
  85215. return this._samples;
  85216. },
  85217. /**
  85218. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85219. */
  85220. set: function (sampleCount) {
  85221. if (this._samples === sampleCount) {
  85222. return;
  85223. }
  85224. this._samples = sampleCount;
  85225. this._buildPipeline();
  85226. },
  85227. enumerable: true,
  85228. configurable: true
  85229. });
  85230. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85231. get: function () {
  85232. return this._imageProcessingEnabled;
  85233. },
  85234. /**
  85235. * If image processing is enabled.
  85236. */
  85237. set: function (enabled) {
  85238. if (this._imageProcessingEnabled === enabled) {
  85239. return;
  85240. }
  85241. this._imageProcessingEnabled = enabled;
  85242. this._buildPipeline();
  85243. },
  85244. enumerable: true,
  85245. configurable: true
  85246. });
  85247. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85248. get: function () {
  85249. return this._glowLayer == null;
  85250. },
  85251. /**
  85252. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85253. */
  85254. set: function (enabled) {
  85255. if (enabled && !this._glowLayer) {
  85256. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85257. }
  85258. else if (!enabled && this._glowLayer) {
  85259. this._glowLayer.dispose();
  85260. this._glowLayer = null;
  85261. }
  85262. },
  85263. enumerable: true,
  85264. configurable: true
  85265. });
  85266. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85267. get: function () {
  85268. return this._chromaticAberrationEnabled;
  85269. },
  85270. /**
  85271. * Enable or disable the chromaticAberration process from the pipeline
  85272. */
  85273. set: function (enabled) {
  85274. if (this._chromaticAberrationEnabled === enabled) {
  85275. return;
  85276. }
  85277. this._chromaticAberrationEnabled = enabled;
  85278. this._buildPipeline();
  85279. },
  85280. enumerable: true,
  85281. configurable: true
  85282. });
  85283. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  85284. get: function () {
  85285. return this._grainEnabled;
  85286. },
  85287. /**
  85288. * Enable or disable the grain process from the pipeline
  85289. */
  85290. set: function (enabled) {
  85291. if (this._grainEnabled === enabled) {
  85292. return;
  85293. }
  85294. this._grainEnabled = enabled;
  85295. this._buildPipeline();
  85296. },
  85297. enumerable: true,
  85298. configurable: true
  85299. });
  85300. /**
  85301. * Force the compilation of the entire pipeline.
  85302. */
  85303. DefaultRenderingPipeline.prototype.prepare = function () {
  85304. var previousState = this._buildAllowed;
  85305. this._buildAllowed = true;
  85306. this._buildPipeline();
  85307. this._buildAllowed = previousState;
  85308. };
  85309. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  85310. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  85311. if (this._hasCleared) {
  85312. postProcess.autoClear = false;
  85313. }
  85314. else {
  85315. postProcess.autoClear = true;
  85316. this._scene.autoClear = false;
  85317. this._hasCleared = true;
  85318. }
  85319. if (!skipTextureSharing) {
  85320. if (this._prevPrevPostProcess) {
  85321. postProcess.shareOutputWith(this._prevPrevPostProcess);
  85322. }
  85323. else {
  85324. postProcess.useOwnOutput();
  85325. }
  85326. if (this._prevPostProcess) {
  85327. this._prevPrevPostProcess = this._prevPostProcess;
  85328. }
  85329. this._prevPostProcess = postProcess;
  85330. }
  85331. };
  85332. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  85333. var _this = this;
  85334. if (!this._buildAllowed) {
  85335. return;
  85336. }
  85337. this._scene.autoClear = true;
  85338. var engine = this._scene.getEngine();
  85339. this._disposePostProcesses();
  85340. if (this._cameras !== null) {
  85341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85342. // get back cameras to be used to reattach pipeline
  85343. this._cameras = this._camerasToBeAttached.slice();
  85344. }
  85345. this._reset();
  85346. this._prevPostProcess = null;
  85347. this._prevPrevPostProcess = null;
  85348. this._hasCleared = false;
  85349. if (this.depthOfFieldEnabled) {
  85350. // Multi camera suport
  85351. if (this._cameras.length > 1) {
  85352. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  85353. var camera = _a[_i];
  85354. var depthRenderer = this._scene.enableDepthRenderer(camera);
  85355. depthRenderer.useOnlyInActiveCamera = true;
  85356. }
  85357. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  85358. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  85359. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  85360. }
  85361. });
  85362. }
  85363. else {
  85364. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85365. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  85366. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  85367. }
  85368. if (!this.depthOfField._isReady()) {
  85369. this.depthOfField._updateEffects();
  85370. }
  85371. this.addEffect(this.depthOfField);
  85372. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  85373. }
  85374. else {
  85375. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85376. }
  85377. if (this.bloomEnabled) {
  85378. if (!this.bloom._isReady()) {
  85379. this.bloom._updateEffects();
  85380. }
  85381. this.addEffect(this.bloom);
  85382. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  85383. }
  85384. if (this._imageProcessingEnabled) {
  85385. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  85386. if (this._hdr) {
  85387. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  85388. this._setAutoClearAndTextureSharing(this.imageProcessing);
  85389. }
  85390. else {
  85391. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  85392. }
  85393. }
  85394. if (this.sharpenEnabled) {
  85395. if (!this.sharpen.isReady()) {
  85396. this.sharpen.updateEffect();
  85397. }
  85398. this.addEffect(this._sharpenEffect);
  85399. this._setAutoClearAndTextureSharing(this.sharpen);
  85400. }
  85401. if (this.grainEnabled) {
  85402. if (!this.grain.isReady()) {
  85403. this.grain.updateEffect();
  85404. }
  85405. this.addEffect(this._grainEffect);
  85406. this._setAutoClearAndTextureSharing(this.grain);
  85407. }
  85408. if (this.chromaticAberrationEnabled) {
  85409. if (!this.chromaticAberration.isReady()) {
  85410. this.chromaticAberration.updateEffect();
  85411. }
  85412. this.addEffect(this._chromaticAberrationEffect);
  85413. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  85414. }
  85415. if (this.fxaaEnabled) {
  85416. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  85417. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  85418. this._setAutoClearAndTextureSharing(this.fxaa, true);
  85419. }
  85420. if (this._cameras !== null) {
  85421. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85422. }
  85423. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  85424. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85425. }
  85426. };
  85427. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  85428. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  85429. for (var i = 0; i < this._cameras.length; i++) {
  85430. var camera = this._cameras[i];
  85431. if (this.imageProcessing) {
  85432. this.imageProcessing.dispose(camera);
  85433. }
  85434. if (this.fxaa) {
  85435. this.fxaa.dispose(camera);
  85436. }
  85437. // These are created in the constructor and should not be disposed on every pipeline change
  85438. if (disposeNonRecreated) {
  85439. if (this.sharpen) {
  85440. this.sharpen.dispose(camera);
  85441. }
  85442. if (this.depthOfField) {
  85443. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  85444. this.depthOfField.disposeEffects(camera);
  85445. }
  85446. if (this.bloom) {
  85447. this.bloom.disposeEffects(camera);
  85448. }
  85449. if (this.chromaticAberration) {
  85450. this.chromaticAberration.dispose(camera);
  85451. }
  85452. if (this.grain) {
  85453. this.grain.dispose(camera);
  85454. }
  85455. if (this._glowLayer) {
  85456. this._glowLayer.dispose();
  85457. }
  85458. }
  85459. }
  85460. this.imageProcessing = null;
  85461. this.fxaa = null;
  85462. if (disposeNonRecreated) {
  85463. this.sharpen = null;
  85464. this._sharpenEffect = null;
  85465. this.depthOfField = null;
  85466. this.bloom = null;
  85467. this.chromaticAberration = null;
  85468. this._chromaticAberrationEffect = null;
  85469. this.grain = null;
  85470. this._grainEffect = null;
  85471. this._glowLayer = null;
  85472. }
  85473. };
  85474. /**
  85475. * Adds a camera to the pipeline
  85476. * @param camera the camera to be added
  85477. */
  85478. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  85479. this._camerasToBeAttached.push(camera);
  85480. this._buildPipeline();
  85481. };
  85482. /**
  85483. * Removes a camera from the pipeline
  85484. * @param camera the camera to remove
  85485. */
  85486. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  85487. var index = this._camerasToBeAttached.indexOf(camera);
  85488. this._camerasToBeAttached.splice(index, 1);
  85489. this._buildPipeline();
  85490. };
  85491. /**
  85492. * Dispose of the pipeline and stop all post processes
  85493. */
  85494. DefaultRenderingPipeline.prototype.dispose = function () {
  85495. this._disposePostProcesses(true);
  85496. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85497. this._scene.autoClear = true;
  85498. if (this._resizeObserver) {
  85499. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  85500. this._resizeObserver = null;
  85501. }
  85502. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  85503. _super.prototype.dispose.call(this);
  85504. };
  85505. /**
  85506. * Serialize the rendering pipeline (Used when exporting)
  85507. * @returns the serialized object
  85508. */
  85509. DefaultRenderingPipeline.prototype.serialize = function () {
  85510. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85511. serializationObject.customType = "DefaultRenderingPipeline";
  85512. return serializationObject;
  85513. };
  85514. /**
  85515. * Parse the serialized pipeline
  85516. * @param source Source pipeline.
  85517. * @param scene The scene to load the pipeline to.
  85518. * @param rootUrl The URL of the serialized pipeline.
  85519. * @returns An instantiated pipeline from the serialized object.
  85520. */
  85521. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85522. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  85523. };
  85524. __decorate([
  85525. BABYLON.serialize()
  85526. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  85527. __decorate([
  85528. BABYLON.serialize()
  85529. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  85530. __decorate([
  85531. BABYLON.serialize()
  85532. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  85533. __decorate([
  85534. BABYLON.serialize()
  85535. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  85536. __decorate([
  85537. BABYLON.serialize()
  85538. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  85539. __decorate([
  85540. BABYLON.serialize()
  85541. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  85542. __decorate([
  85543. BABYLON.serialize()
  85544. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  85545. __decorate([
  85546. BABYLON.serialize()
  85547. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  85548. __decorate([
  85549. BABYLON.serialize()
  85550. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  85551. __decorate([
  85552. BABYLON.serialize()
  85553. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  85554. __decorate([
  85555. BABYLON.serialize()
  85556. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  85557. __decorate([
  85558. BABYLON.serialize()
  85559. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  85560. __decorate([
  85561. BABYLON.serialize()
  85562. ], DefaultRenderingPipeline.prototype, "samples", null);
  85563. __decorate([
  85564. BABYLON.serialize()
  85565. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  85566. __decorate([
  85567. BABYLON.serialize()
  85568. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  85569. __decorate([
  85570. BABYLON.serialize()
  85571. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  85572. __decorate([
  85573. BABYLON.serialize()
  85574. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  85575. return DefaultRenderingPipeline;
  85576. }(BABYLON.PostProcessRenderPipeline));
  85577. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  85578. })(BABYLON || (BABYLON = {}));
  85579. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  85580. var BABYLON;
  85581. (function (BABYLON) {
  85582. /**
  85583. * @hidden
  85584. */
  85585. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  85586. __extends(ImageProcessingConfigurationDefines, _super);
  85587. function ImageProcessingConfigurationDefines() {
  85588. var _this = _super.call(this) || this;
  85589. _this.IMAGEPROCESSING = false;
  85590. _this.VIGNETTE = false;
  85591. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  85592. _this.VIGNETTEBLENDMODEOPAQUE = false;
  85593. _this.TONEMAPPING = false;
  85594. _this.TONEMAPPING_ACES = false;
  85595. _this.CONTRAST = false;
  85596. _this.COLORCURVES = false;
  85597. _this.COLORGRADING = false;
  85598. _this.COLORGRADING3D = false;
  85599. _this.SAMPLER3DGREENDEPTH = false;
  85600. _this.SAMPLER3DBGRMAP = false;
  85601. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  85602. _this.EXPOSURE = false;
  85603. _this.rebuild();
  85604. return _this;
  85605. }
  85606. return ImageProcessingConfigurationDefines;
  85607. }(BABYLON.MaterialDefines));
  85608. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  85609. /**
  85610. * This groups together the common properties used for image processing either in direct forward pass
  85611. * or through post processing effect depending on the use of the image processing pipeline in your scene
  85612. * or not.
  85613. */
  85614. var ImageProcessingConfiguration = /** @class */ (function () {
  85615. function ImageProcessingConfiguration() {
  85616. /**
  85617. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  85618. */
  85619. this.colorCurves = new BABYLON.ColorCurves();
  85620. this._colorCurvesEnabled = false;
  85621. this._colorGradingEnabled = false;
  85622. this._colorGradingWithGreenDepth = true;
  85623. this._colorGradingBGR = true;
  85624. /** @hidden */
  85625. this._exposure = 1.0;
  85626. this._toneMappingEnabled = false;
  85627. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  85628. this._contrast = 1.0;
  85629. /**
  85630. * Vignette stretch size.
  85631. */
  85632. this.vignetteStretch = 0;
  85633. /**
  85634. * Vignette centre X Offset.
  85635. */
  85636. this.vignetteCentreX = 0;
  85637. /**
  85638. * Vignette centre Y Offset.
  85639. */
  85640. this.vignetteCentreY = 0;
  85641. /**
  85642. * Vignette weight or intensity of the vignette effect.
  85643. */
  85644. this.vignetteWeight = 1.5;
  85645. /**
  85646. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85647. * if vignetteEnabled is set to true.
  85648. */
  85649. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  85650. /**
  85651. * Camera field of view used by the Vignette effect.
  85652. */
  85653. this.vignetteCameraFov = 0.5;
  85654. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  85655. this._vignetteEnabled = false;
  85656. this._applyByPostProcess = false;
  85657. this._isEnabled = true;
  85658. /**
  85659. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  85660. */
  85661. this.onUpdateParameters = new BABYLON.Observable();
  85662. }
  85663. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  85664. /**
  85665. * Gets wether the color curves effect is enabled.
  85666. */
  85667. get: function () {
  85668. return this._colorCurvesEnabled;
  85669. },
  85670. /**
  85671. * Sets wether the color curves effect is enabled.
  85672. */
  85673. set: function (value) {
  85674. if (this._colorCurvesEnabled === value) {
  85675. return;
  85676. }
  85677. this._colorCurvesEnabled = value;
  85678. this._updateParameters();
  85679. },
  85680. enumerable: true,
  85681. configurable: true
  85682. });
  85683. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  85684. /**
  85685. * Gets wether the color grading effect is enabled.
  85686. */
  85687. get: function () {
  85688. return this._colorGradingEnabled;
  85689. },
  85690. /**
  85691. * Sets wether the color grading effect is enabled.
  85692. */
  85693. set: function (value) {
  85694. if (this._colorGradingEnabled === value) {
  85695. return;
  85696. }
  85697. this._colorGradingEnabled = value;
  85698. this._updateParameters();
  85699. },
  85700. enumerable: true,
  85701. configurable: true
  85702. });
  85703. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  85704. /**
  85705. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  85706. */
  85707. get: function () {
  85708. return this._colorGradingWithGreenDepth;
  85709. },
  85710. /**
  85711. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  85712. */
  85713. set: function (value) {
  85714. if (this._colorGradingWithGreenDepth === value) {
  85715. return;
  85716. }
  85717. this._colorGradingWithGreenDepth = value;
  85718. this._updateParameters();
  85719. },
  85720. enumerable: true,
  85721. configurable: true
  85722. });
  85723. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  85724. /**
  85725. * Gets wether the color grading texture contains BGR values.
  85726. */
  85727. get: function () {
  85728. return this._colorGradingBGR;
  85729. },
  85730. /**
  85731. * Sets wether the color grading texture contains BGR values.
  85732. */
  85733. set: function (value) {
  85734. if (this._colorGradingBGR === value) {
  85735. return;
  85736. }
  85737. this._colorGradingBGR = value;
  85738. this._updateParameters();
  85739. },
  85740. enumerable: true,
  85741. configurable: true
  85742. });
  85743. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  85744. /**
  85745. * Gets the Exposure used in the effect.
  85746. */
  85747. get: function () {
  85748. return this._exposure;
  85749. },
  85750. /**
  85751. * Sets the Exposure used in the effect.
  85752. */
  85753. set: function (value) {
  85754. if (this._exposure === value) {
  85755. return;
  85756. }
  85757. this._exposure = value;
  85758. this._updateParameters();
  85759. },
  85760. enumerable: true,
  85761. configurable: true
  85762. });
  85763. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  85764. /**
  85765. * Gets wether the tone mapping effect is enabled.
  85766. */
  85767. get: function () {
  85768. return this._toneMappingEnabled;
  85769. },
  85770. /**
  85771. * Sets wether the tone mapping effect is enabled.
  85772. */
  85773. set: function (value) {
  85774. if (this._toneMappingEnabled === value) {
  85775. return;
  85776. }
  85777. this._toneMappingEnabled = value;
  85778. this._updateParameters();
  85779. },
  85780. enumerable: true,
  85781. configurable: true
  85782. });
  85783. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  85784. /**
  85785. * Gets the type of tone mapping effect.
  85786. */
  85787. get: function () {
  85788. return this._toneMappingType;
  85789. },
  85790. /**
  85791. * Sets the type of tone mapping effect used in BabylonJS.
  85792. */
  85793. set: function (value) {
  85794. if (this._toneMappingType === value) {
  85795. return;
  85796. }
  85797. this._toneMappingType = value;
  85798. this._updateParameters();
  85799. },
  85800. enumerable: true,
  85801. configurable: true
  85802. });
  85803. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  85804. /**
  85805. * Gets the contrast used in the effect.
  85806. */
  85807. get: function () {
  85808. return this._contrast;
  85809. },
  85810. /**
  85811. * Sets the contrast used in the effect.
  85812. */
  85813. set: function (value) {
  85814. if (this._contrast === value) {
  85815. return;
  85816. }
  85817. this._contrast = value;
  85818. this._updateParameters();
  85819. },
  85820. enumerable: true,
  85821. configurable: true
  85822. });
  85823. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  85824. /**
  85825. * Gets the vignette blend mode allowing different kind of effect.
  85826. */
  85827. get: function () {
  85828. return this._vignetteBlendMode;
  85829. },
  85830. /**
  85831. * Sets the vignette blend mode allowing different kind of effect.
  85832. */
  85833. set: function (value) {
  85834. if (this._vignetteBlendMode === value) {
  85835. return;
  85836. }
  85837. this._vignetteBlendMode = value;
  85838. this._updateParameters();
  85839. },
  85840. enumerable: true,
  85841. configurable: true
  85842. });
  85843. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  85844. /**
  85845. * Gets wether the vignette effect is enabled.
  85846. */
  85847. get: function () {
  85848. return this._vignetteEnabled;
  85849. },
  85850. /**
  85851. * Sets wether the vignette effect is enabled.
  85852. */
  85853. set: function (value) {
  85854. if (this._vignetteEnabled === value) {
  85855. return;
  85856. }
  85857. this._vignetteEnabled = value;
  85858. this._updateParameters();
  85859. },
  85860. enumerable: true,
  85861. configurable: true
  85862. });
  85863. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  85864. /**
  85865. * Gets wether the image processing is applied through a post process or not.
  85866. */
  85867. get: function () {
  85868. return this._applyByPostProcess;
  85869. },
  85870. /**
  85871. * Sets wether the image processing is applied through a post process or not.
  85872. */
  85873. set: function (value) {
  85874. if (this._applyByPostProcess === value) {
  85875. return;
  85876. }
  85877. this._applyByPostProcess = value;
  85878. this._updateParameters();
  85879. },
  85880. enumerable: true,
  85881. configurable: true
  85882. });
  85883. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  85884. /**
  85885. * Gets wether the image processing is enabled or not.
  85886. */
  85887. get: function () {
  85888. return this._isEnabled;
  85889. },
  85890. /**
  85891. * Sets wether the image processing is enabled or not.
  85892. */
  85893. set: function (value) {
  85894. if (this._isEnabled === value) {
  85895. return;
  85896. }
  85897. this._isEnabled = value;
  85898. this._updateParameters();
  85899. },
  85900. enumerable: true,
  85901. configurable: true
  85902. });
  85903. /**
  85904. * Method called each time the image processing information changes requires to recompile the effect.
  85905. */
  85906. ImageProcessingConfiguration.prototype._updateParameters = function () {
  85907. this.onUpdateParameters.notifyObservers(this);
  85908. };
  85909. /**
  85910. * Gets the current class name.
  85911. * @return "ImageProcessingConfiguration"
  85912. */
  85913. ImageProcessingConfiguration.prototype.getClassName = function () {
  85914. return "ImageProcessingConfiguration";
  85915. };
  85916. /**
  85917. * Prepare the list of uniforms associated with the Image Processing effects.
  85918. * @param uniforms The list of uniforms used in the effect
  85919. * @param defines the list of defines currently in use
  85920. */
  85921. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  85922. if (defines.EXPOSURE) {
  85923. uniforms.push("exposureLinear");
  85924. }
  85925. if (defines.CONTRAST) {
  85926. uniforms.push("contrast");
  85927. }
  85928. if (defines.COLORGRADING) {
  85929. uniforms.push("colorTransformSettings");
  85930. }
  85931. if (defines.VIGNETTE) {
  85932. uniforms.push("vInverseScreenSize");
  85933. uniforms.push("vignetteSettings1");
  85934. uniforms.push("vignetteSettings2");
  85935. }
  85936. if (defines.COLORCURVES) {
  85937. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  85938. }
  85939. };
  85940. /**
  85941. * Prepare the list of samplers associated with the Image Processing effects.
  85942. * @param samplersList The list of uniforms used in the effect
  85943. * @param defines the list of defines currently in use
  85944. */
  85945. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  85946. if (defines.COLORGRADING) {
  85947. samplersList.push("txColorTransform");
  85948. }
  85949. };
  85950. /**
  85951. * Prepare the list of defines associated to the shader.
  85952. * @param defines the list of defines to complete
  85953. * @param forPostProcess Define if we are currently in post process mode or not
  85954. */
  85955. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  85956. if (forPostProcess === void 0) { forPostProcess = false; }
  85957. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  85958. defines.VIGNETTE = false;
  85959. defines.TONEMAPPING = false;
  85960. defines.TONEMAPPING_ACES = false;
  85961. defines.CONTRAST = false;
  85962. defines.EXPOSURE = false;
  85963. defines.COLORCURVES = false;
  85964. defines.COLORGRADING = false;
  85965. defines.COLORGRADING3D = false;
  85966. defines.IMAGEPROCESSING = false;
  85967. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  85968. return;
  85969. }
  85970. defines.VIGNETTE = this.vignetteEnabled;
  85971. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  85972. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  85973. defines.TONEMAPPING = this.toneMappingEnabled;
  85974. switch (this._toneMappingType) {
  85975. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  85976. defines.TONEMAPPING_ACES = true;
  85977. break;
  85978. }
  85979. defines.CONTRAST = (this.contrast !== 1.0);
  85980. defines.EXPOSURE = (this.exposure !== 1.0);
  85981. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  85982. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  85983. if (defines.COLORGRADING) {
  85984. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  85985. }
  85986. else {
  85987. defines.COLORGRADING3D = false;
  85988. }
  85989. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  85990. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  85991. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  85992. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  85993. };
  85994. /**
  85995. * Returns true if all the image processing information are ready.
  85996. * @returns True if ready, otherwise, false
  85997. */
  85998. ImageProcessingConfiguration.prototype.isReady = function () {
  85999. // Color Grading texure can not be none blocking.
  86000. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  86001. };
  86002. /**
  86003. * Binds the image processing to the shader.
  86004. * @param effect The effect to bind to
  86005. * @param aspectRatio Define the current aspect ratio of the effect
  86006. */
  86007. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  86008. if (aspectRatio === void 0) { aspectRatio = 1; }
  86009. // Color Curves
  86010. if (this._colorCurvesEnabled && this.colorCurves) {
  86011. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  86012. }
  86013. // Vignette
  86014. if (this._vignetteEnabled) {
  86015. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  86016. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  86017. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  86018. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  86019. var vignetteScaleX = vignetteScaleY * aspectRatio;
  86020. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  86021. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  86022. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  86023. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  86024. var vignettePower = -2.0 * this.vignetteWeight;
  86025. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  86026. }
  86027. // Exposure
  86028. effect.setFloat("exposureLinear", this.exposure);
  86029. // Contrast
  86030. effect.setFloat("contrast", this.contrast);
  86031. // Color transform settings
  86032. if (this.colorGradingTexture) {
  86033. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86034. var textureSize = this.colorGradingTexture.getSize().height;
  86035. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86036. 0.5 / textureSize, // textureOffset
  86037. textureSize, // textureSize
  86038. this.colorGradingTexture.level // weight
  86039. );
  86040. }
  86041. };
  86042. /**
  86043. * Clones the current image processing instance.
  86044. * @return The cloned image processing
  86045. */
  86046. ImageProcessingConfiguration.prototype.clone = function () {
  86047. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86048. };
  86049. /**
  86050. * Serializes the current image processing instance to a json representation.
  86051. * @return a JSON representation
  86052. */
  86053. ImageProcessingConfiguration.prototype.serialize = function () {
  86054. return BABYLON.SerializationHelper.Serialize(this);
  86055. };
  86056. /**
  86057. * Parses the image processing from a json representation.
  86058. * @param source the JSON source to parse
  86059. * @return The parsed image processing
  86060. */
  86061. ImageProcessingConfiguration.Parse = function (source) {
  86062. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86063. };
  86064. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86065. /**
  86066. * Used to apply the vignette as a mix with the pixel color.
  86067. */
  86068. get: function () {
  86069. return this._VIGNETTEMODE_MULTIPLY;
  86070. },
  86071. enumerable: true,
  86072. configurable: true
  86073. });
  86074. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86075. /**
  86076. * Used to apply the vignette as a replacement of the pixel color.
  86077. */
  86078. get: function () {
  86079. return this._VIGNETTEMODE_OPAQUE;
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. /**
  86085. * Default tone mapping applied in BabylonJS.
  86086. */
  86087. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86088. /**
  86089. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86090. * to other engines rendering to increase portability.
  86091. */
  86092. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86093. // Static constants associated to the image processing.
  86094. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86095. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86096. __decorate([
  86097. BABYLON.serializeAsColorCurves()
  86098. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86099. __decorate([
  86100. BABYLON.serialize()
  86101. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86102. __decorate([
  86103. BABYLON.serializeAsTexture()
  86104. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86105. __decorate([
  86106. BABYLON.serialize()
  86107. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86108. __decorate([
  86109. BABYLON.serialize()
  86110. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86111. __decorate([
  86112. BABYLON.serialize()
  86113. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86114. __decorate([
  86115. BABYLON.serialize()
  86116. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86117. __decorate([
  86118. BABYLON.serialize()
  86119. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86120. __decorate([
  86121. BABYLON.serialize()
  86122. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86123. __decorate([
  86124. BABYLON.serialize()
  86125. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86126. __decorate([
  86127. BABYLON.serialize()
  86128. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86129. __decorate([
  86130. BABYLON.serialize()
  86131. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86132. __decorate([
  86133. BABYLON.serialize()
  86134. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86135. __decorate([
  86136. BABYLON.serialize()
  86137. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86138. __decorate([
  86139. BABYLON.serializeAsColor4()
  86140. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86141. __decorate([
  86142. BABYLON.serialize()
  86143. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86144. __decorate([
  86145. BABYLON.serialize()
  86146. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86147. __decorate([
  86148. BABYLON.serialize()
  86149. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86150. __decorate([
  86151. BABYLON.serialize()
  86152. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86153. __decorate([
  86154. BABYLON.serialize()
  86155. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86156. return ImageProcessingConfiguration;
  86157. }());
  86158. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86159. })(BABYLON || (BABYLON = {}));
  86160. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86161. var BABYLON;
  86162. (function (BABYLON) {
  86163. /**
  86164. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86165. * It can help converting any input color in a desired output one. This can then be used to create effects
  86166. * from sepia, black and white to sixties or futuristic rendering...
  86167. *
  86168. * The only supported format is currently 3dl.
  86169. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86170. */
  86171. var ColorGradingTexture = /** @class */ (function (_super) {
  86172. __extends(ColorGradingTexture, _super);
  86173. /**
  86174. * Instantiates a ColorGradingTexture from the following parameters.
  86175. *
  86176. * @param url The location of the color gradind data (currently only supporting 3dl)
  86177. * @param scene The scene the texture will be used in
  86178. */
  86179. function ColorGradingTexture(url, scene) {
  86180. var _this = _super.call(this, scene) || this;
  86181. if (!url) {
  86182. return _this;
  86183. }
  86184. _this._engine = scene.getEngine();
  86185. _this._textureMatrix = BABYLON.Matrix.Identity();
  86186. _this.name = url;
  86187. _this.url = url;
  86188. _this.hasAlpha = false;
  86189. _this.isCube = false;
  86190. _this.is3D = _this._engine.webGLVersion > 1;
  86191. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86192. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86193. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86194. _this.anisotropicFilteringLevel = 1;
  86195. _this._texture = _this._getFromCache(url, true);
  86196. if (!_this._texture) {
  86197. if (!scene.useDelayedTextureLoading) {
  86198. _this.loadTexture();
  86199. }
  86200. else {
  86201. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86202. }
  86203. }
  86204. return _this;
  86205. }
  86206. /**
  86207. * Returns the texture matrix used in most of the material.
  86208. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86209. */
  86210. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86211. return this._textureMatrix;
  86212. };
  86213. /**
  86214. * Occurs when the file being loaded is a .3dl LUT file.
  86215. */
  86216. ColorGradingTexture.prototype.load3dlTexture = function () {
  86217. var engine = this._engine;
  86218. var texture;
  86219. if (engine.webGLVersion === 1) {
  86220. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86221. }
  86222. else {
  86223. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86224. }
  86225. this._texture = texture;
  86226. var callback = function (text) {
  86227. if (typeof text !== "string") {
  86228. return;
  86229. }
  86230. var data = null;
  86231. var tempData = null;
  86232. var line;
  86233. var lines = text.split('\n');
  86234. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86235. var maxColor = 0;
  86236. for (var i = 0; i < lines.length; i++) {
  86237. line = lines[i];
  86238. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86239. continue;
  86240. if (line.indexOf('#') === 0)
  86241. continue;
  86242. var words = line.split(" ");
  86243. if (size === 0) {
  86244. // Number of space + one
  86245. size = words.length;
  86246. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86247. tempData = new Float32Array(size * size * size * 4);
  86248. continue;
  86249. }
  86250. if (size != 0) {
  86251. var r = Math.max(parseInt(words[0]), 0);
  86252. var g = Math.max(parseInt(words[1]), 0);
  86253. var b = Math.max(parseInt(words[2]), 0);
  86254. maxColor = Math.max(r, maxColor);
  86255. maxColor = Math.max(g, maxColor);
  86256. maxColor = Math.max(b, maxColor);
  86257. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86258. if (tempData) {
  86259. tempData[pixelStorageIndex + 0] = r;
  86260. tempData[pixelStorageIndex + 1] = g;
  86261. tempData[pixelStorageIndex + 2] = b;
  86262. }
  86263. pixelIndexSlice++;
  86264. if (pixelIndexSlice % size == 0) {
  86265. pixelIndexH++;
  86266. pixelIndexSlice = 0;
  86267. if (pixelIndexH % size == 0) {
  86268. pixelIndexW++;
  86269. pixelIndexH = 0;
  86270. }
  86271. }
  86272. }
  86273. }
  86274. if (tempData && data) {
  86275. for (var i = 0; i < tempData.length; i++) {
  86276. if (i > 0 && (i + 1) % 4 === 0) {
  86277. data[i] = 255;
  86278. }
  86279. else {
  86280. var value = tempData[i];
  86281. data[i] = (value / maxColor * 255);
  86282. }
  86283. }
  86284. }
  86285. if (texture.is3D) {
  86286. texture.updateSize(size, size, size);
  86287. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86288. }
  86289. else {
  86290. texture.updateSize(size * size, size);
  86291. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86292. }
  86293. };
  86294. var scene = this.getScene();
  86295. if (scene) {
  86296. scene._loadFile(this.url, callback);
  86297. }
  86298. else {
  86299. this._engine._loadFile(this.url, callback);
  86300. }
  86301. return this._texture;
  86302. };
  86303. /**
  86304. * Starts the loading process of the texture.
  86305. */
  86306. ColorGradingTexture.prototype.loadTexture = function () {
  86307. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  86308. this.load3dlTexture();
  86309. }
  86310. };
  86311. /**
  86312. * Clones the color gradind texture.
  86313. */
  86314. ColorGradingTexture.prototype.clone = function () {
  86315. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  86316. // Base texture
  86317. newTexture.level = this.level;
  86318. return newTexture;
  86319. };
  86320. /**
  86321. * Called during delayed load for textures.
  86322. */
  86323. ColorGradingTexture.prototype.delayLoad = function () {
  86324. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86325. return;
  86326. }
  86327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86328. this._texture = this._getFromCache(this.url, true);
  86329. if (!this._texture) {
  86330. this.loadTexture();
  86331. }
  86332. };
  86333. /**
  86334. * Parses a color grading texture serialized by Babylon.
  86335. * @param parsedTexture The texture information being parsedTexture
  86336. * @param scene The scene to load the texture in
  86337. * @param rootUrl The root url of the data assets to load
  86338. * @return A color gradind texture
  86339. */
  86340. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86341. var texture = null;
  86342. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86343. texture = new ColorGradingTexture(parsedTexture.name, scene);
  86344. texture.name = parsedTexture.name;
  86345. texture.level = parsedTexture.level;
  86346. }
  86347. return texture;
  86348. };
  86349. /**
  86350. * Serializes the LUT texture to json format.
  86351. */
  86352. ColorGradingTexture.prototype.serialize = function () {
  86353. if (!this.name) {
  86354. return null;
  86355. }
  86356. var serializationObject = {};
  86357. serializationObject.name = this.name;
  86358. serializationObject.level = this.level;
  86359. serializationObject.customType = "BABYLON.ColorGradingTexture";
  86360. return serializationObject;
  86361. };
  86362. /**
  86363. * Empty line regex stored for GC.
  86364. */
  86365. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  86366. return ColorGradingTexture;
  86367. }(BABYLON.BaseTexture));
  86368. BABYLON.ColorGradingTexture = ColorGradingTexture;
  86369. })(BABYLON || (BABYLON = {}));
  86370. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  86371. var BABYLON;
  86372. (function (BABYLON) {
  86373. /**
  86374. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86375. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86376. * 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;
  86377. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86378. */
  86379. var ColorCurves = /** @class */ (function () {
  86380. function ColorCurves() {
  86381. this._dirty = true;
  86382. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  86383. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  86384. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  86385. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  86386. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  86387. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  86388. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  86389. this._globalHue = 30;
  86390. this._globalDensity = 0;
  86391. this._globalSaturation = 0;
  86392. this._globalExposure = 0;
  86393. this._highlightsHue = 30;
  86394. this._highlightsDensity = 0;
  86395. this._highlightsSaturation = 0;
  86396. this._highlightsExposure = 0;
  86397. this._midtonesHue = 30;
  86398. this._midtonesDensity = 0;
  86399. this._midtonesSaturation = 0;
  86400. this._midtonesExposure = 0;
  86401. this._shadowsHue = 30;
  86402. this._shadowsDensity = 0;
  86403. this._shadowsSaturation = 0;
  86404. this._shadowsExposure = 0;
  86405. }
  86406. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  86407. /**
  86408. * Gets the global Hue value.
  86409. * 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).
  86410. */
  86411. get: function () {
  86412. return this._globalHue;
  86413. },
  86414. /**
  86415. * Sets the global Hue value.
  86416. * 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).
  86417. */
  86418. set: function (value) {
  86419. this._globalHue = value;
  86420. this._dirty = true;
  86421. },
  86422. enumerable: true,
  86423. configurable: true
  86424. });
  86425. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  86426. /**
  86427. * Gets the global Density value.
  86428. * 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.
  86429. * Values less than zero provide a filter of opposite hue.
  86430. */
  86431. get: function () {
  86432. return this._globalDensity;
  86433. },
  86434. /**
  86435. * Sets the global Density value.
  86436. * 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.
  86437. * Values less than zero provide a filter of opposite hue.
  86438. */
  86439. set: function (value) {
  86440. this._globalDensity = value;
  86441. this._dirty = true;
  86442. },
  86443. enumerable: true,
  86444. configurable: true
  86445. });
  86446. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  86447. /**
  86448. * Gets the global Saturation value.
  86449. * 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.
  86450. */
  86451. get: function () {
  86452. return this._globalSaturation;
  86453. },
  86454. /**
  86455. * Sets the global Saturation value.
  86456. * 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.
  86457. */
  86458. set: function (value) {
  86459. this._globalSaturation = value;
  86460. this._dirty = true;
  86461. },
  86462. enumerable: true,
  86463. configurable: true
  86464. });
  86465. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  86466. /**
  86467. * Gets the global Exposure value.
  86468. * 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.
  86469. */
  86470. get: function () {
  86471. return this._globalExposure;
  86472. },
  86473. /**
  86474. * Sets the global Exposure value.
  86475. * 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.
  86476. */
  86477. set: function (value) {
  86478. this._globalExposure = value;
  86479. this._dirty = true;
  86480. },
  86481. enumerable: true,
  86482. configurable: true
  86483. });
  86484. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  86485. /**
  86486. * Gets the highlights Hue value.
  86487. * 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).
  86488. */
  86489. get: function () {
  86490. return this._highlightsHue;
  86491. },
  86492. /**
  86493. * Sets the highlights Hue value.
  86494. * 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).
  86495. */
  86496. set: function (value) {
  86497. this._highlightsHue = value;
  86498. this._dirty = true;
  86499. },
  86500. enumerable: true,
  86501. configurable: true
  86502. });
  86503. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  86504. /**
  86505. * Gets the highlights Density value.
  86506. * 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.
  86507. * Values less than zero provide a filter of opposite hue.
  86508. */
  86509. get: function () {
  86510. return this._highlightsDensity;
  86511. },
  86512. /**
  86513. * Sets the highlights Density value.
  86514. * 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.
  86515. * Values less than zero provide a filter of opposite hue.
  86516. */
  86517. set: function (value) {
  86518. this._highlightsDensity = value;
  86519. this._dirty = true;
  86520. },
  86521. enumerable: true,
  86522. configurable: true
  86523. });
  86524. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  86525. /**
  86526. * Gets the highlights Saturation value.
  86527. * 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.
  86528. */
  86529. get: function () {
  86530. return this._highlightsSaturation;
  86531. },
  86532. /**
  86533. * Sets the highlights Saturation value.
  86534. * 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.
  86535. */
  86536. set: function (value) {
  86537. this._highlightsSaturation = value;
  86538. this._dirty = true;
  86539. },
  86540. enumerable: true,
  86541. configurable: true
  86542. });
  86543. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  86544. /**
  86545. * Gets the highlights Exposure value.
  86546. * 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.
  86547. */
  86548. get: function () {
  86549. return this._highlightsExposure;
  86550. },
  86551. /**
  86552. * Sets the highlights Exposure value.
  86553. * 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.
  86554. */
  86555. set: function (value) {
  86556. this._highlightsExposure = value;
  86557. this._dirty = true;
  86558. },
  86559. enumerable: true,
  86560. configurable: true
  86561. });
  86562. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  86563. /**
  86564. * Gets the midtones Hue value.
  86565. * 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).
  86566. */
  86567. get: function () {
  86568. return this._midtonesHue;
  86569. },
  86570. /**
  86571. * Sets the midtones Hue value.
  86572. * 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).
  86573. */
  86574. set: function (value) {
  86575. this._midtonesHue = value;
  86576. this._dirty = true;
  86577. },
  86578. enumerable: true,
  86579. configurable: true
  86580. });
  86581. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  86582. /**
  86583. * Gets the midtones Density value.
  86584. * 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.
  86585. * Values less than zero provide a filter of opposite hue.
  86586. */
  86587. get: function () {
  86588. return this._midtonesDensity;
  86589. },
  86590. /**
  86591. * Sets the midtones Density value.
  86592. * 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.
  86593. * Values less than zero provide a filter of opposite hue.
  86594. */
  86595. set: function (value) {
  86596. this._midtonesDensity = value;
  86597. this._dirty = true;
  86598. },
  86599. enumerable: true,
  86600. configurable: true
  86601. });
  86602. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  86603. /**
  86604. * Gets the midtones Saturation value.
  86605. * 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.
  86606. */
  86607. get: function () {
  86608. return this._midtonesSaturation;
  86609. },
  86610. /**
  86611. * Sets the midtones Saturation value.
  86612. * 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.
  86613. */
  86614. set: function (value) {
  86615. this._midtonesSaturation = value;
  86616. this._dirty = true;
  86617. },
  86618. enumerable: true,
  86619. configurable: true
  86620. });
  86621. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  86622. /**
  86623. * Gets the midtones Exposure value.
  86624. * 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.
  86625. */
  86626. get: function () {
  86627. return this._midtonesExposure;
  86628. },
  86629. /**
  86630. * Sets the midtones Exposure value.
  86631. * 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.
  86632. */
  86633. set: function (value) {
  86634. this._midtonesExposure = value;
  86635. this._dirty = true;
  86636. },
  86637. enumerable: true,
  86638. configurable: true
  86639. });
  86640. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  86641. /**
  86642. * Gets the shadows Hue value.
  86643. * 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).
  86644. */
  86645. get: function () {
  86646. return this._shadowsHue;
  86647. },
  86648. /**
  86649. * Sets the shadows Hue value.
  86650. * 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).
  86651. */
  86652. set: function (value) {
  86653. this._shadowsHue = value;
  86654. this._dirty = true;
  86655. },
  86656. enumerable: true,
  86657. configurable: true
  86658. });
  86659. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  86660. /**
  86661. * Gets the shadows Density value.
  86662. * 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.
  86663. * Values less than zero provide a filter of opposite hue.
  86664. */
  86665. get: function () {
  86666. return this._shadowsDensity;
  86667. },
  86668. /**
  86669. * Sets the shadows Density value.
  86670. * 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.
  86671. * Values less than zero provide a filter of opposite hue.
  86672. */
  86673. set: function (value) {
  86674. this._shadowsDensity = value;
  86675. this._dirty = true;
  86676. },
  86677. enumerable: true,
  86678. configurable: true
  86679. });
  86680. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  86681. /**
  86682. * Gets the shadows Saturation value.
  86683. * 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.
  86684. */
  86685. get: function () {
  86686. return this._shadowsSaturation;
  86687. },
  86688. /**
  86689. * Sets the shadows Saturation value.
  86690. * 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.
  86691. */
  86692. set: function (value) {
  86693. this._shadowsSaturation = value;
  86694. this._dirty = true;
  86695. },
  86696. enumerable: true,
  86697. configurable: true
  86698. });
  86699. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  86700. /**
  86701. * Gets the shadows Exposure value.
  86702. * 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.
  86703. */
  86704. get: function () {
  86705. return this._shadowsExposure;
  86706. },
  86707. /**
  86708. * Sets the shadows Exposure value.
  86709. * 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.
  86710. */
  86711. set: function (value) {
  86712. this._shadowsExposure = value;
  86713. this._dirty = true;
  86714. },
  86715. enumerable: true,
  86716. configurable: true
  86717. });
  86718. /**
  86719. * Returns the class name
  86720. * @returns The class name
  86721. */
  86722. ColorCurves.prototype.getClassName = function () {
  86723. return "ColorCurves";
  86724. };
  86725. /**
  86726. * Binds the color curves to the shader.
  86727. * @param colorCurves The color curve to bind
  86728. * @param effect The effect to bind to
  86729. * @param positiveUniform The positive uniform shader parameter
  86730. * @param neutralUniform The neutral uniform shader parameter
  86731. * @param negativeUniform The negative uniform shader parameter
  86732. */
  86733. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  86734. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  86735. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  86736. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  86737. if (colorCurves._dirty) {
  86738. colorCurves._dirty = false;
  86739. // Fill in global info.
  86740. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  86741. // Compute highlights info.
  86742. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  86743. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  86744. // Compute midtones info.
  86745. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  86746. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  86747. // Compute shadows info.
  86748. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  86749. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  86750. // Compute deltas (neutral is midtones).
  86751. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  86752. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  86753. }
  86754. if (effect) {
  86755. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  86756. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  86757. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  86758. }
  86759. };
  86760. /**
  86761. * Prepare the list of uniforms associated with the ColorCurves effects.
  86762. * @param uniformsList The list of uniforms used in the effect
  86763. */
  86764. ColorCurves.PrepareUniforms = function (uniformsList) {
  86765. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  86766. };
  86767. /**
  86768. * Returns color grading data based on a hue, density, saturation and exposure value.
  86769. * @param filterHue The hue of the color filter.
  86770. * @param filterDensity The density of the color filter.
  86771. * @param saturation The saturation.
  86772. * @param exposure The exposure.
  86773. * @param result The result data container.
  86774. */
  86775. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  86776. if (hue == null) {
  86777. return;
  86778. }
  86779. hue = ColorCurves.clamp(hue, 0, 360);
  86780. density = ColorCurves.clamp(density, -100, 100);
  86781. saturation = ColorCurves.clamp(saturation, -100, 100);
  86782. exposure = ColorCurves.clamp(exposure, -100, 100);
  86783. // Remap the slider/config filter density with non-linear mapping and also scale by half
  86784. // so that the maximum filter density is only 50% control. This provides fine control
  86785. // for small values and reasonable range.
  86786. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  86787. density *= 0.5;
  86788. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  86789. if (density < 0) {
  86790. density *= -1;
  86791. hue = (hue + 180) % 360;
  86792. }
  86793. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  86794. result.scaleToRef(2, result);
  86795. result.a = 1 + 0.01 * saturation;
  86796. };
  86797. /**
  86798. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  86799. * @param value The input slider value in range [-100,100].
  86800. * @returns Adjusted value.
  86801. */
  86802. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  86803. value /= 100;
  86804. var x = Math.abs(value);
  86805. x = Math.pow(x, 2);
  86806. if (value < 0) {
  86807. x *= -1;
  86808. }
  86809. x *= 100;
  86810. return x;
  86811. };
  86812. /**
  86813. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  86814. * @param hue The hue (H) input.
  86815. * @param saturation The saturation (S) input.
  86816. * @param brightness The brightness (B) input.
  86817. * @result An RGBA color represented as Vector4.
  86818. */
  86819. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  86820. var h = ColorCurves.clamp(hue, 0, 360);
  86821. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  86822. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  86823. if (s === 0) {
  86824. result.r = v;
  86825. result.g = v;
  86826. result.b = v;
  86827. }
  86828. else {
  86829. // sector 0 to 5
  86830. h /= 60;
  86831. var i = Math.floor(h);
  86832. // fractional part of h
  86833. var f = h - i;
  86834. var p = v * (1 - s);
  86835. var q = v * (1 - s * f);
  86836. var t = v * (1 - s * (1 - f));
  86837. switch (i) {
  86838. case 0:
  86839. result.r = v;
  86840. result.g = t;
  86841. result.b = p;
  86842. break;
  86843. case 1:
  86844. result.r = q;
  86845. result.g = v;
  86846. result.b = p;
  86847. break;
  86848. case 2:
  86849. result.r = p;
  86850. result.g = v;
  86851. result.b = t;
  86852. break;
  86853. case 3:
  86854. result.r = p;
  86855. result.g = q;
  86856. result.b = v;
  86857. break;
  86858. case 4:
  86859. result.r = t;
  86860. result.g = p;
  86861. result.b = v;
  86862. break;
  86863. default: // case 5:
  86864. result.r = v;
  86865. result.g = p;
  86866. result.b = q;
  86867. break;
  86868. }
  86869. }
  86870. result.a = 1;
  86871. };
  86872. /**
  86873. * Returns a value clamped between min and max
  86874. * @param value The value to clamp
  86875. * @param min The minimum of value
  86876. * @param max The maximum of value
  86877. * @returns The clamped value.
  86878. */
  86879. ColorCurves.clamp = function (value, min, max) {
  86880. return Math.min(Math.max(value, min), max);
  86881. };
  86882. /**
  86883. * Clones the current color curve instance.
  86884. * @return The cloned curves
  86885. */
  86886. ColorCurves.prototype.clone = function () {
  86887. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  86888. };
  86889. /**
  86890. * Serializes the current color curve instance to a json representation.
  86891. * @return a JSON representation
  86892. */
  86893. ColorCurves.prototype.serialize = function () {
  86894. return BABYLON.SerializationHelper.Serialize(this);
  86895. };
  86896. /**
  86897. * Parses the color curve from a json representation.
  86898. * @param source the JSON source to parse
  86899. * @return The parsed curves
  86900. */
  86901. ColorCurves.Parse = function (source) {
  86902. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  86903. };
  86904. __decorate([
  86905. BABYLON.serialize()
  86906. ], ColorCurves.prototype, "_globalHue", void 0);
  86907. __decorate([
  86908. BABYLON.serialize()
  86909. ], ColorCurves.prototype, "_globalDensity", void 0);
  86910. __decorate([
  86911. BABYLON.serialize()
  86912. ], ColorCurves.prototype, "_globalSaturation", void 0);
  86913. __decorate([
  86914. BABYLON.serialize()
  86915. ], ColorCurves.prototype, "_globalExposure", void 0);
  86916. __decorate([
  86917. BABYLON.serialize()
  86918. ], ColorCurves.prototype, "_highlightsHue", void 0);
  86919. __decorate([
  86920. BABYLON.serialize()
  86921. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  86922. __decorate([
  86923. BABYLON.serialize()
  86924. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  86925. __decorate([
  86926. BABYLON.serialize()
  86927. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  86928. __decorate([
  86929. BABYLON.serialize()
  86930. ], ColorCurves.prototype, "_midtonesHue", void 0);
  86931. __decorate([
  86932. BABYLON.serialize()
  86933. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  86934. __decorate([
  86935. BABYLON.serialize()
  86936. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  86937. __decorate([
  86938. BABYLON.serialize()
  86939. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  86940. return ColorCurves;
  86941. }());
  86942. BABYLON.ColorCurves = ColorCurves;
  86943. })(BABYLON || (BABYLON = {}));
  86944. //# sourceMappingURL=babylon.colorCurves.js.map
  86945. var BABYLON;
  86946. (function (BABYLON) {
  86947. var RefractionPostProcess = /** @class */ (function (_super) {
  86948. __extends(RefractionPostProcess, _super);
  86949. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  86950. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  86951. _this.color = color;
  86952. _this.depth = depth;
  86953. _this.colorLevel = colorLevel;
  86954. _this._ownRefractionTexture = true;
  86955. _this.onActivateObservable.add(function (cam) {
  86956. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  86957. });
  86958. _this.onApplyObservable.add(function (effect) {
  86959. effect.setColor3("baseColor", _this.color);
  86960. effect.setFloat("depth", _this.depth);
  86961. effect.setFloat("colorLevel", _this.colorLevel);
  86962. effect.setTexture("refractionSampler", _this._refTexture);
  86963. });
  86964. return _this;
  86965. }
  86966. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  86967. /**
  86968. * Gets or sets the refraction texture
  86969. * Please note that you are responsible for disposing the texture if you set it manually
  86970. */
  86971. get: function () {
  86972. return this._refTexture;
  86973. },
  86974. set: function (value) {
  86975. if (this._refTexture && this._ownRefractionTexture) {
  86976. this._refTexture.dispose();
  86977. }
  86978. this._refTexture = value;
  86979. this._ownRefractionTexture = false;
  86980. },
  86981. enumerable: true,
  86982. configurable: true
  86983. });
  86984. // Methods
  86985. RefractionPostProcess.prototype.dispose = function (camera) {
  86986. if (this._refTexture && this._ownRefractionTexture) {
  86987. this._refTexture.dispose();
  86988. this._refTexture = null;
  86989. }
  86990. _super.prototype.dispose.call(this, camera);
  86991. };
  86992. return RefractionPostProcess;
  86993. }(BABYLON.PostProcess));
  86994. BABYLON.RefractionPostProcess = RefractionPostProcess;
  86995. })(BABYLON || (BABYLON = {}));
  86996. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  86997. var BABYLON;
  86998. (function (BABYLON) {
  86999. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  87000. __extends(BlackAndWhitePostProcess, _super);
  87001. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  87002. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  87003. _this.degree = 1;
  87004. _this.onApplyObservable.add(function (effect) {
  87005. effect.setFloat("degree", _this.degree);
  87006. });
  87007. return _this;
  87008. }
  87009. return BlackAndWhitePostProcess;
  87010. }(BABYLON.PostProcess));
  87011. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  87012. })(BABYLON || (BABYLON = {}));
  87013. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  87014. var BABYLON;
  87015. (function (BABYLON) {
  87016. /**
  87017. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  87018. * input texture to perform effects such as edge detection or sharpening
  87019. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87020. */
  87021. var ConvolutionPostProcess = /** @class */ (function (_super) {
  87022. __extends(ConvolutionPostProcess, _super);
  87023. /**
  87024. * Creates a new instance ConvolutionPostProcess
  87025. * @param name The name of the effect.
  87026. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87027. * @param options The required width/height ratio to downsize to before computing the render pass.
  87028. * @param camera The camera to apply the render pass to.
  87029. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87030. * @param engine The engine which the post process will be applied. (default: current engine)
  87031. * @param reusable If the post process can be reused on the same frame. (default: false)
  87032. * @param textureType Type of textures used when performing the post process. (default: 0)
  87033. */
  87034. function ConvolutionPostProcess(name,
  87035. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87036. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87037. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87038. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87039. _this.kernel = kernel;
  87040. _this.onApply = function (effect) {
  87041. effect.setFloat2("screenSize", _this.width, _this.height);
  87042. effect.setArray("kernel", _this.kernel);
  87043. };
  87044. return _this;
  87045. }
  87046. // Statics
  87047. /**
  87048. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87049. */
  87050. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87051. /**
  87052. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87053. */
  87054. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87055. /**
  87056. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87057. */
  87058. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87059. /**
  87060. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87061. */
  87062. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87063. /**
  87064. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87065. */
  87066. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87067. /**
  87068. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87069. */
  87070. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87071. return ConvolutionPostProcess;
  87072. }(BABYLON.PostProcess));
  87073. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87074. })(BABYLON || (BABYLON = {}));
  87075. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87076. var BABYLON;
  87077. (function (BABYLON) {
  87078. var FilterPostProcess = /** @class */ (function (_super) {
  87079. __extends(FilterPostProcess, _super);
  87080. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87081. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87082. _this.kernelMatrix = kernelMatrix;
  87083. _this.onApply = function (effect) {
  87084. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87085. };
  87086. return _this;
  87087. }
  87088. return FilterPostProcess;
  87089. }(BABYLON.PostProcess));
  87090. BABYLON.FilterPostProcess = FilterPostProcess;
  87091. })(BABYLON || (BABYLON = {}));
  87092. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87093. var BABYLON;
  87094. (function (BABYLON) {
  87095. /**
  87096. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87097. */
  87098. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87099. __extends(VolumetricLightScatteringPostProcess, _super);
  87100. /**
  87101. * @constructor
  87102. * @param {string} name - The post-process name
  87103. * @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)
  87104. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87105. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87106. * @param {number} samples - The post-process quality, default 100
  87107. * @param {number} samplingMode - The post-process filtering mode
  87108. * @param {BABYLON.Engine} engine - The babylon engine
  87109. * @param {boolean} reusable - If the post-process is reusable
  87110. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87111. */
  87112. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87113. if (samples === void 0) { samples = 100; }
  87114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87115. 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;
  87116. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87117. /**
  87118. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87119. */
  87120. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87121. /**
  87122. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87123. */
  87124. _this.useCustomMeshPosition = false;
  87125. /**
  87126. * If the post-process should inverse the light scattering direction
  87127. */
  87128. _this.invert = true;
  87129. /**
  87130. * Array containing the excluded meshes not rendered in the internal pass
  87131. */
  87132. _this.excludedMeshes = new Array();
  87133. /**
  87134. * Controls the overall intensity of the post-process
  87135. */
  87136. _this.exposure = 0.3;
  87137. /**
  87138. * Dissipates each sample's contribution in range [0, 1]
  87139. */
  87140. _this.decay = 0.96815;
  87141. /**
  87142. * Controls the overall intensity of each sample
  87143. */
  87144. _this.weight = 0.58767;
  87145. /**
  87146. * Controls the density of each sample
  87147. */
  87148. _this.density = 0.926;
  87149. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87150. engine = scene.getEngine();
  87151. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87152. // Configure mesh
  87153. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87154. // Configure
  87155. _this._createPass(scene, ratio.passRatio || ratio);
  87156. _this.onActivate = function (camera) {
  87157. if (!_this.isSupported) {
  87158. _this.dispose(camera);
  87159. }
  87160. _this.onActivate = null;
  87161. };
  87162. _this.onApplyObservable.add(function (effect) {
  87163. _this._updateMeshScreenCoordinates(scene);
  87164. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87165. effect.setFloat("exposure", _this.exposure);
  87166. effect.setFloat("decay", _this.decay);
  87167. effect.setFloat("weight", _this.weight);
  87168. effect.setFloat("density", _this.density);
  87169. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87170. });
  87171. return _this;
  87172. }
  87173. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87174. /**
  87175. * @hidden
  87176. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87177. */
  87178. get: function () {
  87179. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87180. return false;
  87181. },
  87182. set: function (useDiffuseColor) {
  87183. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87184. },
  87185. enumerable: true,
  87186. configurable: true
  87187. });
  87188. /**
  87189. * Returns the string "VolumetricLightScatteringPostProcess"
  87190. * @returns "VolumetricLightScatteringPostProcess"
  87191. */
  87192. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87193. return "VolumetricLightScatteringPostProcess";
  87194. };
  87195. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87196. var mesh = subMesh.getMesh();
  87197. // Render this.mesh as default
  87198. if (mesh === this.mesh && mesh.material) {
  87199. return mesh.material.isReady(mesh);
  87200. }
  87201. var defines = [];
  87202. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87203. var material = subMesh.getMaterial();
  87204. // Alpha test
  87205. if (material) {
  87206. if (material.needAlphaTesting()) {
  87207. defines.push("#define ALPHATEST");
  87208. }
  87209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87210. attribs.push(BABYLON.VertexBuffer.UVKind);
  87211. defines.push("#define UV1");
  87212. }
  87213. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87214. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87215. defines.push("#define UV2");
  87216. }
  87217. }
  87218. // Bones
  87219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87222. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87223. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87224. }
  87225. else {
  87226. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87227. }
  87228. // Instances
  87229. if (useInstances) {
  87230. defines.push("#define INSTANCES");
  87231. attribs.push("world0");
  87232. attribs.push("world1");
  87233. attribs.push("world2");
  87234. attribs.push("world3");
  87235. }
  87236. // Get correct effect
  87237. var join = defines.join("\n");
  87238. if (this._cachedDefines !== join) {
  87239. this._cachedDefines = join;
  87240. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  87241. }
  87242. return this._volumetricLightScatteringPass.isReady();
  87243. };
  87244. /**
  87245. * Sets the new light position for light scattering effect
  87246. * @param position The new custom light position
  87247. */
  87248. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  87249. this.customMeshPosition = position;
  87250. };
  87251. /**
  87252. * Returns the light position for light scattering effect
  87253. * @return {BABYLON.Vector3} The custom light position
  87254. */
  87255. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  87256. return this.customMeshPosition;
  87257. };
  87258. /**
  87259. * Disposes the internal assets and detaches the post-process from the camera
  87260. */
  87261. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  87262. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  87263. if (rttIndex !== -1) {
  87264. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  87265. }
  87266. this._volumetricLightScatteringRTT.dispose();
  87267. _super.prototype.dispose.call(this, camera);
  87268. };
  87269. /**
  87270. * Returns the render target texture used by the post-process
  87271. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  87272. */
  87273. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  87274. return this._volumetricLightScatteringRTT;
  87275. };
  87276. // Private methods
  87277. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  87278. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  87279. return true;
  87280. }
  87281. return false;
  87282. };
  87283. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  87284. var _this = this;
  87285. var engine = scene.getEngine();
  87286. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87287. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87288. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87289. this._volumetricLightScatteringRTT.renderList = null;
  87290. this._volumetricLightScatteringRTT.renderParticles = false;
  87291. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  87292. var camera = this.getCamera();
  87293. if (camera) {
  87294. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87295. }
  87296. else {
  87297. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  87298. }
  87299. // Custom render function for submeshes
  87300. var renderSubMesh = function (subMesh) {
  87301. var mesh = subMesh.getRenderingMesh();
  87302. if (_this._meshExcluded(mesh)) {
  87303. return;
  87304. }
  87305. var material = subMesh.getMaterial();
  87306. if (!material) {
  87307. return;
  87308. }
  87309. var scene = mesh.getScene();
  87310. var engine = scene.getEngine();
  87311. // Culling
  87312. engine.setState(material.backFaceCulling);
  87313. // Managing instances
  87314. var batch = mesh._getInstancesRenderList(subMesh._id);
  87315. if (batch.mustReturn) {
  87316. return;
  87317. }
  87318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  87319. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  87320. var effect = _this._volumetricLightScatteringPass;
  87321. if (mesh === _this.mesh) {
  87322. if (subMesh.effect) {
  87323. effect = subMesh.effect;
  87324. }
  87325. else {
  87326. effect = material.getEffect();
  87327. }
  87328. }
  87329. engine.enableEffect(effect);
  87330. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  87331. if (mesh === _this.mesh) {
  87332. material.bind(mesh.getWorldMatrix(), mesh);
  87333. }
  87334. else {
  87335. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  87336. // Alpha test
  87337. if (material && material.needAlphaTesting()) {
  87338. var alphaTexture = material.getAlphaTestTexture();
  87339. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  87340. if (alphaTexture) {
  87341. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  87342. }
  87343. }
  87344. // Bones
  87345. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87346. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87347. }
  87348. }
  87349. // Draw
  87350. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  87351. }
  87352. };
  87353. // Render target texture callbacks
  87354. var savedSceneClearColor;
  87355. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  87356. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  87357. savedSceneClearColor = scene.clearColor;
  87358. scene.clearColor = sceneClearColor;
  87359. });
  87360. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  87361. scene.clearColor = savedSceneClearColor;
  87362. });
  87363. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  87364. var engine = scene.getEngine();
  87365. var index;
  87366. if (depthOnlySubMeshes.length) {
  87367. engine.setColorWrite(false);
  87368. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  87369. renderSubMesh(depthOnlySubMeshes.data[index]);
  87370. }
  87371. engine.setColorWrite(true);
  87372. }
  87373. for (index = 0; index < opaqueSubMeshes.length; index++) {
  87374. renderSubMesh(opaqueSubMeshes.data[index]);
  87375. }
  87376. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  87377. renderSubMesh(alphaTestSubMeshes.data[index]);
  87378. }
  87379. if (transparentSubMeshes.length) {
  87380. // Sort sub meshes
  87381. for (index = 0; index < transparentSubMeshes.length; index++) {
  87382. var submesh = transparentSubMeshes.data[index];
  87383. var boundingInfo = submesh.getBoundingInfo();
  87384. if (boundingInfo && scene.activeCamera) {
  87385. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  87386. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  87387. }
  87388. }
  87389. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  87390. sortedArray.sort(function (a, b) {
  87391. // Alpha index first
  87392. if (a._alphaIndex > b._alphaIndex) {
  87393. return 1;
  87394. }
  87395. if (a._alphaIndex < b._alphaIndex) {
  87396. return -1;
  87397. }
  87398. // Then distance to camera
  87399. if (a._distanceToCamera < b._distanceToCamera) {
  87400. return 1;
  87401. }
  87402. if (a._distanceToCamera > b._distanceToCamera) {
  87403. return -1;
  87404. }
  87405. return 0;
  87406. });
  87407. // Render sub meshes
  87408. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  87409. for (index = 0; index < sortedArray.length; index++) {
  87410. renderSubMesh(sortedArray[index]);
  87411. }
  87412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87413. }
  87414. };
  87415. };
  87416. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  87417. var transform = scene.getTransformMatrix();
  87418. var meshPosition;
  87419. if (this.useCustomMeshPosition) {
  87420. meshPosition = this.customMeshPosition;
  87421. }
  87422. else if (this.attachedNode) {
  87423. meshPosition = this.attachedNode.position;
  87424. }
  87425. else {
  87426. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  87427. }
  87428. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  87429. this._screenCoordinates.x = pos.x / this._viewPort.width;
  87430. this._screenCoordinates.y = pos.y / this._viewPort.height;
  87431. if (this.invert)
  87432. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  87433. };
  87434. // Static methods
  87435. /**
  87436. * Creates a default mesh for the Volumeric Light Scattering post-process
  87437. * @param name The mesh name
  87438. * @param scene The scene where to create the mesh
  87439. * @return {BABYLON.Mesh} the default mesh
  87440. */
  87441. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  87442. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  87443. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  87444. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  87445. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  87446. mesh.material = material;
  87447. return mesh;
  87448. };
  87449. __decorate([
  87450. BABYLON.serializeAsVector3()
  87451. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  87452. __decorate([
  87453. BABYLON.serialize()
  87454. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  87455. __decorate([
  87456. BABYLON.serialize()
  87457. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  87458. __decorate([
  87459. BABYLON.serializeAsMeshReference()
  87460. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  87461. __decorate([
  87462. BABYLON.serialize()
  87463. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  87464. __decorate([
  87465. BABYLON.serialize()
  87466. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  87467. __decorate([
  87468. BABYLON.serialize()
  87469. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  87470. __decorate([
  87471. BABYLON.serialize()
  87472. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  87473. __decorate([
  87474. BABYLON.serialize()
  87475. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  87476. return VolumetricLightScatteringPostProcess;
  87477. }(BABYLON.PostProcess));
  87478. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  87479. })(BABYLON || (BABYLON = {}));
  87480. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  87481. var BABYLON;
  87482. (function (BABYLON) {
  87483. /**
  87484. *
  87485. * This post-process allows the modification of rendered colors by using
  87486. * a 'look-up table' (LUT). This effect is also called Color Grading.
  87487. *
  87488. * The object needs to be provided an url to a texture containing the color
  87489. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  87490. * Use an image editing software to tweak the LUT to match your needs.
  87491. *
  87492. * For an example of a color LUT, see here:
  87493. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  87494. * For explanations on color grading, see here:
  87495. * @see http://udn.epicgames.com/Three/ColorGrading.html
  87496. *
  87497. */
  87498. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  87499. __extends(ColorCorrectionPostProcess, _super);
  87500. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  87501. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  87502. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87503. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  87504. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87505. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87506. _this.onApply = function (effect) {
  87507. effect.setTexture("colorTable", _this._colorTableTexture);
  87508. };
  87509. return _this;
  87510. }
  87511. return ColorCorrectionPostProcess;
  87512. }(BABYLON.PostProcess));
  87513. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  87514. })(BABYLON || (BABYLON = {}));
  87515. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  87516. var BABYLON;
  87517. (function (BABYLON) {
  87518. /** Defines operator used for tonemapping */
  87519. var TonemappingOperator;
  87520. (function (TonemappingOperator) {
  87521. /** Hable */
  87522. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  87523. /** Reinhard */
  87524. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  87525. /** HejiDawson */
  87526. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  87527. /** Photographic */
  87528. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  87529. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  87530. ;
  87531. /**
  87532. * Defines a post process to apply tone mapping
  87533. */
  87534. var TonemapPostProcess = /** @class */ (function (_super) {
  87535. __extends(TonemapPostProcess, _super);
  87536. /**
  87537. * Creates a new TonemapPostProcess
  87538. * @param name defines the name of the postprocess
  87539. * @param _operator defines the operator to use
  87540. * @param exposureAdjustment defines the required exposure adjustement
  87541. * @param camera defines the camera to use (can be null)
  87542. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  87543. * @param engine defines the hosting engine (can be ignore if camera is set)
  87544. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  87545. */
  87546. function TonemapPostProcess(name, _operator,
  87547. /** Defines the required exposure adjustement */
  87548. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  87549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87550. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87551. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  87552. _this._operator = _operator;
  87553. _this.exposureAdjustment = exposureAdjustment;
  87554. var defines = "#define ";
  87555. if (_this._operator === TonemappingOperator.Hable)
  87556. defines += "HABLE_TONEMAPPING";
  87557. else if (_this._operator === TonemappingOperator.Reinhard)
  87558. defines += "REINHARD_TONEMAPPING";
  87559. else if (_this._operator === TonemappingOperator.HejiDawson)
  87560. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  87561. else if (_this._operator === TonemappingOperator.Photographic)
  87562. defines += "PHOTOGRAPHIC_TONEMAPPING";
  87563. //sadly a second call to create the effect.
  87564. _this.updateEffect(defines);
  87565. _this.onApply = function (effect) {
  87566. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  87567. };
  87568. return _this;
  87569. }
  87570. return TonemapPostProcess;
  87571. }(BABYLON.PostProcess));
  87572. BABYLON.TonemapPostProcess = TonemapPostProcess;
  87573. })(BABYLON || (BABYLON = {}));
  87574. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  87575. var BABYLON;
  87576. (function (BABYLON) {
  87577. var DisplayPassPostProcess = /** @class */ (function (_super) {
  87578. __extends(DisplayPassPostProcess, _super);
  87579. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  87580. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  87581. }
  87582. return DisplayPassPostProcess;
  87583. }(BABYLON.PostProcess));
  87584. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  87585. })(BABYLON || (BABYLON = {}));
  87586. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  87587. var BABYLON;
  87588. (function (BABYLON) {
  87589. var HighlightsPostProcess = /** @class */ (function (_super) {
  87590. __extends(HighlightsPostProcess, _super);
  87591. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87592. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87593. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87594. }
  87595. return HighlightsPostProcess;
  87596. }(BABYLON.PostProcess));
  87597. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  87598. })(BABYLON || (BABYLON = {}));
  87599. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  87600. var BABYLON;
  87601. (function (BABYLON) {
  87602. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  87603. __extends(ImageProcessingPostProcess, _super);
  87604. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  87605. if (camera === void 0) { camera = null; }
  87606. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87607. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  87608. _this._fromLinearSpace = true;
  87609. /**
  87610. * Defines cache preventing GC.
  87611. */
  87612. _this._defines = {
  87613. IMAGEPROCESSING: false,
  87614. VIGNETTE: false,
  87615. VIGNETTEBLENDMODEMULTIPLY: false,
  87616. VIGNETTEBLENDMODEOPAQUE: false,
  87617. TONEMAPPING: false,
  87618. TONEMAPPING_ACES: false,
  87619. CONTRAST: false,
  87620. COLORCURVES: false,
  87621. COLORGRADING: false,
  87622. COLORGRADING3D: false,
  87623. FROMLINEARSPACE: false,
  87624. SAMPLER3DGREENDEPTH: false,
  87625. SAMPLER3DBGRMAP: false,
  87626. IMAGEPROCESSINGPOSTPROCESS: false,
  87627. EXPOSURE: false,
  87628. };
  87629. // Setup the configuration as forced by the constructor. This would then not force the
  87630. // scene materials output in linear space and let untouched the default forward pass.
  87631. if (imageProcessingConfiguration) {
  87632. imageProcessingConfiguration.applyByPostProcess = true;
  87633. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  87634. // This will cause the shader to be compiled
  87635. _this.fromLinearSpace = false;
  87636. }
  87637. // Setup the default processing configuration to the scene.
  87638. else {
  87639. _this._attachImageProcessingConfiguration(null, true);
  87640. _this.imageProcessingConfiguration.applyByPostProcess = true;
  87641. }
  87642. _this.onApply = function (effect) {
  87643. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  87644. };
  87645. return _this;
  87646. }
  87647. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  87648. /**
  87649. * Gets the image processing configuration used either in this material.
  87650. */
  87651. get: function () {
  87652. return this._imageProcessingConfiguration;
  87653. },
  87654. /**
  87655. * Sets the Default image processing configuration used either in the this material.
  87656. *
  87657. * If sets to null, the scene one is in use.
  87658. */
  87659. set: function (value) {
  87660. this._attachImageProcessingConfiguration(value);
  87661. },
  87662. enumerable: true,
  87663. configurable: true
  87664. });
  87665. /**
  87666. * Attaches a new image processing configuration to the PBR Material.
  87667. * @param configuration
  87668. */
  87669. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  87670. var _this = this;
  87671. if (doNotBuild === void 0) { doNotBuild = false; }
  87672. if (configuration === this._imageProcessingConfiguration) {
  87673. return;
  87674. }
  87675. // Detaches observer.
  87676. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87677. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87678. }
  87679. // Pick the scene configuration if needed.
  87680. if (!configuration) {
  87681. var scene = null;
  87682. var engine = this.getEngine();
  87683. var camera = this.getCamera();
  87684. if (camera) {
  87685. scene = camera.getScene();
  87686. }
  87687. else if (engine && engine.scenes) {
  87688. var scenes = engine.scenes;
  87689. scene = scenes[scenes.length - 1];
  87690. }
  87691. else {
  87692. scene = BABYLON.Engine.LastCreatedScene;
  87693. }
  87694. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  87695. }
  87696. else {
  87697. this._imageProcessingConfiguration = configuration;
  87698. }
  87699. // Attaches observer.
  87700. if (this._imageProcessingConfiguration) {
  87701. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87702. _this._updateParameters();
  87703. });
  87704. }
  87705. // Ensure the effect will be rebuilt.
  87706. if (!doNotBuild) {
  87707. this._updateParameters();
  87708. }
  87709. };
  87710. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  87711. /**
  87712. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  87713. */
  87714. get: function () {
  87715. return this.imageProcessingConfiguration.colorCurves;
  87716. },
  87717. /**
  87718. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  87719. */
  87720. set: function (value) {
  87721. this.imageProcessingConfiguration.colorCurves = value;
  87722. },
  87723. enumerable: true,
  87724. configurable: true
  87725. });
  87726. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  87727. /**
  87728. * Gets wether the color curves effect is enabled.
  87729. */
  87730. get: function () {
  87731. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87732. },
  87733. /**
  87734. * Sets wether the color curves effect is enabled.
  87735. */
  87736. set: function (value) {
  87737. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87738. },
  87739. enumerable: true,
  87740. configurable: true
  87741. });
  87742. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  87743. /**
  87744. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  87745. */
  87746. get: function () {
  87747. return this.imageProcessingConfiguration.colorGradingTexture;
  87748. },
  87749. /**
  87750. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  87751. */
  87752. set: function (value) {
  87753. this.imageProcessingConfiguration.colorGradingTexture = value;
  87754. },
  87755. enumerable: true,
  87756. configurable: true
  87757. });
  87758. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  87759. /**
  87760. * Gets wether the color grading effect is enabled.
  87761. */
  87762. get: function () {
  87763. return this.imageProcessingConfiguration.colorGradingEnabled;
  87764. },
  87765. /**
  87766. * Gets wether the color grading effect is enabled.
  87767. */
  87768. set: function (value) {
  87769. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87770. },
  87771. enumerable: true,
  87772. configurable: true
  87773. });
  87774. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  87775. /**
  87776. * Gets exposure used in the effect.
  87777. */
  87778. get: function () {
  87779. return this.imageProcessingConfiguration.exposure;
  87780. },
  87781. /**
  87782. * Sets exposure used in the effect.
  87783. */
  87784. set: function (value) {
  87785. this.imageProcessingConfiguration.exposure = value;
  87786. },
  87787. enumerable: true,
  87788. configurable: true
  87789. });
  87790. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  87791. /**
  87792. * Gets wether tonemapping is enabled or not.
  87793. */
  87794. get: function () {
  87795. return this._imageProcessingConfiguration.toneMappingEnabled;
  87796. },
  87797. /**
  87798. * Sets wether tonemapping is enabled or not
  87799. */
  87800. set: function (value) {
  87801. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87802. },
  87803. enumerable: true,
  87804. configurable: true
  87805. });
  87806. ;
  87807. ;
  87808. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  87809. /**
  87810. * Gets contrast used in the effect.
  87811. */
  87812. get: function () {
  87813. return this.imageProcessingConfiguration.contrast;
  87814. },
  87815. /**
  87816. * Sets contrast used in the effect.
  87817. */
  87818. set: function (value) {
  87819. this.imageProcessingConfiguration.contrast = value;
  87820. },
  87821. enumerable: true,
  87822. configurable: true
  87823. });
  87824. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  87825. /**
  87826. * Gets Vignette stretch size.
  87827. */
  87828. get: function () {
  87829. return this.imageProcessingConfiguration.vignetteStretch;
  87830. },
  87831. /**
  87832. * Sets Vignette stretch size.
  87833. */
  87834. set: function (value) {
  87835. this.imageProcessingConfiguration.vignetteStretch = value;
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  87841. /**
  87842. * Gets Vignette centre X Offset.
  87843. */
  87844. get: function () {
  87845. return this.imageProcessingConfiguration.vignetteCentreX;
  87846. },
  87847. /**
  87848. * Sets Vignette centre X Offset.
  87849. */
  87850. set: function (value) {
  87851. this.imageProcessingConfiguration.vignetteCentreX = value;
  87852. },
  87853. enumerable: true,
  87854. configurable: true
  87855. });
  87856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  87857. /**
  87858. * Gets Vignette centre Y Offset.
  87859. */
  87860. get: function () {
  87861. return this.imageProcessingConfiguration.vignetteCentreY;
  87862. },
  87863. /**
  87864. * Sets Vignette centre Y Offset.
  87865. */
  87866. set: function (value) {
  87867. this.imageProcessingConfiguration.vignetteCentreY = value;
  87868. },
  87869. enumerable: true,
  87870. configurable: true
  87871. });
  87872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  87873. /**
  87874. * Gets Vignette weight or intensity of the vignette effect.
  87875. */
  87876. get: function () {
  87877. return this.imageProcessingConfiguration.vignetteWeight;
  87878. },
  87879. /**
  87880. * Sets Vignette weight or intensity of the vignette effect.
  87881. */
  87882. set: function (value) {
  87883. this.imageProcessingConfiguration.vignetteWeight = value;
  87884. },
  87885. enumerable: true,
  87886. configurable: true
  87887. });
  87888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  87889. /**
  87890. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87891. * if vignetteEnabled is set to true.
  87892. */
  87893. get: function () {
  87894. return this.imageProcessingConfiguration.vignetteColor;
  87895. },
  87896. /**
  87897. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87898. * if vignetteEnabled is set to true.
  87899. */
  87900. set: function (value) {
  87901. this.imageProcessingConfiguration.vignetteColor = value;
  87902. },
  87903. enumerable: true,
  87904. configurable: true
  87905. });
  87906. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  87907. /**
  87908. * Gets Camera field of view used by the Vignette effect.
  87909. */
  87910. get: function () {
  87911. return this.imageProcessingConfiguration.vignetteCameraFov;
  87912. },
  87913. /**
  87914. * Sets Camera field of view used by the Vignette effect.
  87915. */
  87916. set: function (value) {
  87917. this.imageProcessingConfiguration.vignetteCameraFov = value;
  87918. },
  87919. enumerable: true,
  87920. configurable: true
  87921. });
  87922. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  87923. /**
  87924. * Gets the vignette blend mode allowing different kind of effect.
  87925. */
  87926. get: function () {
  87927. return this.imageProcessingConfiguration.vignetteBlendMode;
  87928. },
  87929. /**
  87930. * Sets the vignette blend mode allowing different kind of effect.
  87931. */
  87932. set: function (value) {
  87933. this.imageProcessingConfiguration.vignetteBlendMode = value;
  87934. },
  87935. enumerable: true,
  87936. configurable: true
  87937. });
  87938. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  87939. /**
  87940. * Gets wether the vignette effect is enabled.
  87941. */
  87942. get: function () {
  87943. return this.imageProcessingConfiguration.vignetteEnabled;
  87944. },
  87945. /**
  87946. * Sets wether the vignette effect is enabled.
  87947. */
  87948. set: function (value) {
  87949. this.imageProcessingConfiguration.vignetteEnabled = value;
  87950. },
  87951. enumerable: true,
  87952. configurable: true
  87953. });
  87954. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  87955. /**
  87956. * Gets wether the input of the processing is in Gamma or Linear Space.
  87957. */
  87958. get: function () {
  87959. return this._fromLinearSpace;
  87960. },
  87961. /**
  87962. * Sets wether the input of the processing is in Gamma or Linear Space.
  87963. */
  87964. set: function (value) {
  87965. if (this._fromLinearSpace === value) {
  87966. return;
  87967. }
  87968. this._fromLinearSpace = value;
  87969. this._updateParameters();
  87970. },
  87971. enumerable: true,
  87972. configurable: true
  87973. });
  87974. ImageProcessingPostProcess.prototype.getClassName = function () {
  87975. return "ImageProcessingPostProcess";
  87976. };
  87977. ImageProcessingPostProcess.prototype._updateParameters = function () {
  87978. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  87979. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  87980. var defines = "";
  87981. for (var define in this._defines) {
  87982. if (this._defines[define]) {
  87983. defines += "#define " + define + ";\r\n";
  87984. }
  87985. }
  87986. var samplers = ["textureSampler"];
  87987. var uniforms = ["scale"];
  87988. if (BABYLON.ImageProcessingConfiguration) {
  87989. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  87990. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  87991. }
  87992. this.updateEffect(defines, uniforms, samplers);
  87993. };
  87994. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  87995. _super.prototype.dispose.call(this, camera);
  87996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87998. }
  87999. if (this._imageProcessingConfiguration) {
  88000. this.imageProcessingConfiguration.applyByPostProcess = false;
  88001. }
  88002. };
  88003. __decorate([
  88004. BABYLON.serialize()
  88005. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  88006. return ImageProcessingPostProcess;
  88007. }(BABYLON.PostProcess));
  88008. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  88009. })(BABYLON || (BABYLON = {}));
  88010. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  88011. var BABYLON;
  88012. (function (BABYLON) {
  88013. /**
  88014. * Class used to store bone information
  88015. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88016. */
  88017. var Bone = /** @class */ (function (_super) {
  88018. __extends(Bone, _super);
  88019. /**
  88020. * Create a new bone
  88021. * @param name defines the bone name
  88022. * @param skeleton defines the parent skeleton
  88023. * @param parentBone defines the parent (can be null if the bone is the root)
  88024. * @param localMatrix defines the local matrix
  88025. * @param restPose defines the rest pose matrix
  88026. * @param baseMatrix defines the base matrix
  88027. * @param index defines index of the bone in the hiearchy
  88028. */
  88029. function Bone(
  88030. /**
  88031. * defines the bone name
  88032. */
  88033. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88034. if (parentBone === void 0) { parentBone = null; }
  88035. if (localMatrix === void 0) { localMatrix = null; }
  88036. if (restPose === void 0) { restPose = null; }
  88037. if (baseMatrix === void 0) { baseMatrix = null; }
  88038. if (index === void 0) { index = null; }
  88039. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88040. _this.name = name;
  88041. /**
  88042. * Gets the list of child bones
  88043. */
  88044. _this.children = new Array();
  88045. /** Gets the animations associated with this bone */
  88046. _this.animations = new Array();
  88047. /**
  88048. * @hidden Internal only
  88049. * Set this value to map this bone to a different index in the transform matrices
  88050. * Set this value to -1 to exclude the bone from the transform matrices
  88051. */
  88052. _this._index = null;
  88053. _this._absoluteTransform = new BABYLON.Matrix();
  88054. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88055. _this._scalingDeterminant = 1;
  88056. _this._worldTransform = new BABYLON.Matrix();
  88057. _this._needToDecompose = true;
  88058. _this._needToCompose = false;
  88059. _this._skeleton = skeleton;
  88060. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88061. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88062. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88063. _this._index = index;
  88064. skeleton.bones.push(_this);
  88065. _this.setParent(parentBone, false);
  88066. if (baseMatrix || localMatrix) {
  88067. _this._updateDifferenceMatrix();
  88068. }
  88069. return _this;
  88070. }
  88071. Object.defineProperty(Bone.prototype, "_matrix", {
  88072. /** @hidden */
  88073. get: function () {
  88074. this._compose();
  88075. return this._localMatrix;
  88076. },
  88077. /** @hidden */
  88078. set: function (value) {
  88079. this._localMatrix.copyFrom(value);
  88080. this._needToDecompose = true;
  88081. },
  88082. enumerable: true,
  88083. configurable: true
  88084. });
  88085. // Members
  88086. /**
  88087. * Gets the parent skeleton
  88088. * @returns a skeleton
  88089. */
  88090. Bone.prototype.getSkeleton = function () {
  88091. return this._skeleton;
  88092. };
  88093. /**
  88094. * Gets parent bone
  88095. * @returns a bone or null if the bone is the root of the bone hierarchy
  88096. */
  88097. Bone.prototype.getParent = function () {
  88098. return this._parent;
  88099. };
  88100. /**
  88101. * Sets the parent bone
  88102. * @param parent defines the parent (can be null if the bone is the root)
  88103. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88104. */
  88105. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88106. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88107. if (this._parent === parent) {
  88108. return;
  88109. }
  88110. if (this._parent) {
  88111. var index = this._parent.children.indexOf(this);
  88112. if (index !== -1) {
  88113. this._parent.children.splice(index, 1);
  88114. }
  88115. }
  88116. this._parent = parent;
  88117. if (this._parent) {
  88118. this._parent.children.push(this);
  88119. }
  88120. if (updateDifferenceMatrix) {
  88121. this._updateDifferenceMatrix();
  88122. }
  88123. this.markAsDirty();
  88124. };
  88125. /**
  88126. * Gets the local matrix
  88127. * @returns a matrix
  88128. */
  88129. Bone.prototype.getLocalMatrix = function () {
  88130. this._compose();
  88131. return this._localMatrix;
  88132. };
  88133. /**
  88134. * Gets the base matrix (initial matrix which remains unchanged)
  88135. * @returns a matrix
  88136. */
  88137. Bone.prototype.getBaseMatrix = function () {
  88138. return this._baseMatrix;
  88139. };
  88140. /**
  88141. * Gets the rest pose matrix
  88142. * @returns a matrix
  88143. */
  88144. Bone.prototype.getRestPose = function () {
  88145. return this._restPose;
  88146. };
  88147. /**
  88148. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88149. */
  88150. Bone.prototype.getWorldMatrix = function () {
  88151. return this._worldTransform;
  88152. };
  88153. /**
  88154. * Sets the local matrix to rest pose matrix
  88155. */
  88156. Bone.prototype.returnToRest = function () {
  88157. this.updateMatrix(this._restPose.clone());
  88158. };
  88159. /**
  88160. * Gets the inverse of the absolute transform matrix.
  88161. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88162. * @returns a matrix
  88163. */
  88164. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88165. return this._invertedAbsoluteTransform;
  88166. };
  88167. /**
  88168. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88169. * @returns a matrix
  88170. */
  88171. Bone.prototype.getAbsoluteTransform = function () {
  88172. return this._absoluteTransform;
  88173. };
  88174. Object.defineProperty(Bone.prototype, "position", {
  88175. // Properties (matches AbstractMesh properties)
  88176. /** Gets or sets current position (in local space) */
  88177. get: function () {
  88178. this._decompose();
  88179. return this._localPosition;
  88180. },
  88181. set: function (newPosition) {
  88182. this._decompose();
  88183. this._localPosition.copyFrom(newPosition);
  88184. this._markAsDirtyAndCompose();
  88185. },
  88186. enumerable: true,
  88187. configurable: true
  88188. });
  88189. Object.defineProperty(Bone.prototype, "rotation", {
  88190. /** Gets or sets current rotation (in local space) */
  88191. get: function () {
  88192. return this.getRotation();
  88193. },
  88194. set: function (newRotation) {
  88195. this.setRotation(newRotation);
  88196. },
  88197. enumerable: true,
  88198. configurable: true
  88199. });
  88200. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  88201. /** Gets or sets current rotation quaternion (in local space) */
  88202. get: function () {
  88203. this._decompose();
  88204. return this._localRotation;
  88205. },
  88206. set: function (newRotation) {
  88207. this.setRotationQuaternion(newRotation);
  88208. },
  88209. enumerable: true,
  88210. configurable: true
  88211. });
  88212. Object.defineProperty(Bone.prototype, "scaling", {
  88213. /** Gets or sets current scaling (in local space) */
  88214. get: function () {
  88215. return this.getScale();
  88216. },
  88217. set: function (newScaling) {
  88218. this.setScale(newScaling);
  88219. },
  88220. enumerable: true,
  88221. configurable: true
  88222. });
  88223. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  88224. /**
  88225. * Gets the animation properties override
  88226. */
  88227. get: function () {
  88228. return this._skeleton.animationPropertiesOverride;
  88229. },
  88230. enumerable: true,
  88231. configurable: true
  88232. });
  88233. // Methods
  88234. Bone.prototype._decompose = function () {
  88235. if (!this._needToDecompose) {
  88236. return;
  88237. }
  88238. this._needToDecompose = false;
  88239. if (!this._localScaling) {
  88240. this._localScaling = BABYLON.Vector3.Zero();
  88241. this._localRotation = BABYLON.Quaternion.Zero();
  88242. this._localPosition = BABYLON.Vector3.Zero();
  88243. }
  88244. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  88245. };
  88246. Bone.prototype._compose = function () {
  88247. if (!this._needToCompose) {
  88248. return;
  88249. }
  88250. this._needToCompose = false;
  88251. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  88252. };
  88253. /**
  88254. * Update the base and local matrices
  88255. * @param matrix defines the new base or local matrix
  88256. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88257. * @param updateLocalMatrix defines if the local matrix should be updated
  88258. */
  88259. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  88260. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88261. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  88262. this._baseMatrix.copyFrom(matrix);
  88263. if (updateDifferenceMatrix) {
  88264. this._updateDifferenceMatrix();
  88265. }
  88266. if (updateLocalMatrix) {
  88267. this._localMatrix.copyFrom(matrix);
  88268. this._markAsDirtyAndDecompose();
  88269. }
  88270. else {
  88271. this.markAsDirty();
  88272. }
  88273. };
  88274. /** @hidden */
  88275. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  88276. if (updateChildren === void 0) { updateChildren = true; }
  88277. if (!rootMatrix) {
  88278. rootMatrix = this._baseMatrix;
  88279. }
  88280. if (this._parent) {
  88281. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  88282. }
  88283. else {
  88284. this._absoluteTransform.copyFrom(rootMatrix);
  88285. }
  88286. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  88287. if (updateChildren) {
  88288. for (var index = 0; index < this.children.length; index++) {
  88289. this.children[index]._updateDifferenceMatrix();
  88290. }
  88291. }
  88292. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  88293. };
  88294. /**
  88295. * Flag the bone as dirty (Forcing it to update everything)
  88296. */
  88297. Bone.prototype.markAsDirty = function () {
  88298. this._currentRenderId++;
  88299. this._childRenderId++;
  88300. this._skeleton._markAsDirty();
  88301. };
  88302. Bone.prototype._markAsDirtyAndCompose = function () {
  88303. this.markAsDirty();
  88304. this._needToCompose = true;
  88305. };
  88306. Bone.prototype._markAsDirtyAndDecompose = function () {
  88307. this.markAsDirty();
  88308. this._needToDecompose = true;
  88309. };
  88310. /**
  88311. * Copy an animation range from another bone
  88312. * @param source defines the source bone
  88313. * @param rangeName defines the range name to copy
  88314. * @param frameOffset defines the frame offset
  88315. * @param rescaleAsRequired defines if rescaling must be applied if required
  88316. * @param skelDimensionsRatio defines the scaling ratio
  88317. * @returns true if operation was successful
  88318. */
  88319. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  88320. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88321. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  88322. // all animation may be coming from a library skeleton, so may need to create animation
  88323. if (this.animations.length === 0) {
  88324. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  88325. this.animations[0].setKeys([]);
  88326. }
  88327. // get animation info / verify there is such a range from the source bone
  88328. var sourceRange = source.animations[0].getRange(rangeName);
  88329. if (!sourceRange) {
  88330. return false;
  88331. }
  88332. var from = sourceRange.from;
  88333. var to = sourceRange.to;
  88334. var sourceKeys = source.animations[0].getKeys();
  88335. // rescaling prep
  88336. var sourceBoneLength = source.length;
  88337. var sourceParent = source.getParent();
  88338. var parent = this.getParent();
  88339. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  88340. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  88341. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  88342. var destKeys = this.animations[0].getKeys();
  88343. // loop vars declaration
  88344. var orig;
  88345. var origTranslation;
  88346. var mat;
  88347. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  88348. orig = sourceKeys[key];
  88349. if (orig.frame >= from && orig.frame <= to) {
  88350. if (rescaleAsRequired) {
  88351. mat = orig.value.clone();
  88352. // scale based on parent ratio, when bone has parent
  88353. if (parentScalingReqd) {
  88354. origTranslation = mat.getTranslation();
  88355. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  88356. // scale based on skeleton dimension ratio when root bone, and value is passed
  88357. }
  88358. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  88359. origTranslation = mat.getTranslation();
  88360. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  88361. // use original when root bone, and no data for skelDimensionsRatio
  88362. }
  88363. else {
  88364. mat = orig.value;
  88365. }
  88366. }
  88367. else {
  88368. mat = orig.value;
  88369. }
  88370. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  88371. }
  88372. }
  88373. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  88374. return true;
  88375. };
  88376. /**
  88377. * Translate the bone in local or world space
  88378. * @param vec The amount to translate the bone
  88379. * @param space The space that the translation is in
  88380. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88381. */
  88382. Bone.prototype.translate = function (vec, space, mesh) {
  88383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88384. var lm = this.getLocalMatrix();
  88385. if (space == BABYLON.Space.LOCAL) {
  88386. lm.m[12] += vec.x;
  88387. lm.m[13] += vec.y;
  88388. lm.m[14] += vec.z;
  88389. }
  88390. else {
  88391. var wm = null;
  88392. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88393. if (mesh) {
  88394. wm = mesh.getWorldMatrix();
  88395. }
  88396. this._skeleton.computeAbsoluteTransforms();
  88397. var tmat = Bone._tmpMats[0];
  88398. var tvec = Bone._tmpVecs[0];
  88399. if (this._parent) {
  88400. if (mesh && wm) {
  88401. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88402. tmat.multiplyToRef(wm, tmat);
  88403. }
  88404. else {
  88405. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88406. }
  88407. }
  88408. tmat.m[12] = 0;
  88409. tmat.m[13] = 0;
  88410. tmat.m[14] = 0;
  88411. tmat.invert();
  88412. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  88413. lm.m[12] += tvec.x;
  88414. lm.m[13] += tvec.y;
  88415. lm.m[14] += tvec.z;
  88416. }
  88417. this._markAsDirtyAndDecompose();
  88418. };
  88419. /**
  88420. * Set the postion of the bone in local or world space
  88421. * @param position The position to set the bone
  88422. * @param space The space that the position is in
  88423. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88424. */
  88425. Bone.prototype.setPosition = function (position, space, mesh) {
  88426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88427. var lm = this.getLocalMatrix();
  88428. if (space == BABYLON.Space.LOCAL) {
  88429. lm.m[12] = position.x;
  88430. lm.m[13] = position.y;
  88431. lm.m[14] = position.z;
  88432. }
  88433. else {
  88434. var wm = null;
  88435. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88436. if (mesh) {
  88437. wm = mesh.getWorldMatrix();
  88438. }
  88439. this._skeleton.computeAbsoluteTransforms();
  88440. var tmat = Bone._tmpMats[0];
  88441. var vec = Bone._tmpVecs[0];
  88442. if (this._parent) {
  88443. if (mesh && wm) {
  88444. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88445. tmat.multiplyToRef(wm, tmat);
  88446. }
  88447. else {
  88448. tmat.copyFrom(this._parent.getAbsoluteTransform());
  88449. }
  88450. }
  88451. tmat.invert();
  88452. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  88453. lm.m[12] = vec.x;
  88454. lm.m[13] = vec.y;
  88455. lm.m[14] = vec.z;
  88456. }
  88457. this._markAsDirtyAndDecompose();
  88458. };
  88459. /**
  88460. * Set the absolute position of the bone (world space)
  88461. * @param position The position to set the bone
  88462. * @param mesh The mesh that this bone is attached to
  88463. */
  88464. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  88465. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  88466. };
  88467. /**
  88468. * Scale the bone on the x, y and z axes (in local space)
  88469. * @param x The amount to scale the bone on the x axis
  88470. * @param y The amount to scale the bone on the y axis
  88471. * @param z The amount to scale the bone on the z axis
  88472. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  88473. */
  88474. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  88475. if (scaleChildren === void 0) { scaleChildren = false; }
  88476. var locMat = this.getLocalMatrix();
  88477. // Apply new scaling on top of current local matrix
  88478. var scaleMat = Bone._tmpMats[0];
  88479. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  88480. scaleMat.multiplyToRef(locMat, locMat);
  88481. // Invert scaling matrix and apply the inverse to all children
  88482. scaleMat.invert();
  88483. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  88484. var child = _a[_i];
  88485. var cm = child.getLocalMatrix();
  88486. cm.multiplyToRef(scaleMat, cm);
  88487. cm.m[12] *= x;
  88488. cm.m[13] *= y;
  88489. cm.m[14] *= z;
  88490. child._markAsDirtyAndDecompose();
  88491. }
  88492. this._markAsDirtyAndDecompose();
  88493. if (scaleChildren) {
  88494. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  88495. var child = _c[_b];
  88496. child.scale(x, y, z, scaleChildren);
  88497. }
  88498. }
  88499. };
  88500. /**
  88501. * Set the bone scaling in local space
  88502. * @param scale defines the scaling vector
  88503. */
  88504. Bone.prototype.setScale = function (scale) {
  88505. this._decompose();
  88506. this._localScaling.copyFrom(scale);
  88507. this._markAsDirtyAndCompose();
  88508. };
  88509. /**
  88510. * Gets the current scaling in local space
  88511. * @returns the current scaling vector
  88512. */
  88513. Bone.prototype.getScale = function () {
  88514. this._decompose();
  88515. return this._localScaling;
  88516. };
  88517. /**
  88518. * Gets the current scaling in local space and stores it in a target vector
  88519. * @param result defines the target vector
  88520. */
  88521. Bone.prototype.getScaleToRef = function (result) {
  88522. this._decompose();
  88523. result.copyFrom(this._localScaling);
  88524. };
  88525. /**
  88526. * Set the yaw, pitch, and roll of the bone in local or world space
  88527. * @param yaw The rotation of the bone on the y axis
  88528. * @param pitch The rotation of the bone on the x axis
  88529. * @param roll The rotation of the bone on the z axis
  88530. * @param space The space that the axes of rotation are in
  88531. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88532. */
  88533. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  88534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88535. if (space === BABYLON.Space.LOCAL) {
  88536. var quat = Bone._tmpQuat;
  88537. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  88538. this.setRotationQuaternion(quat, space, mesh);
  88539. return;
  88540. }
  88541. var rotMatInv = Bone._tmpMats[0];
  88542. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88543. return;
  88544. }
  88545. var rotMat = Bone._tmpMats[1];
  88546. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  88547. rotMatInv.multiplyToRef(rotMat, rotMat);
  88548. this._rotateWithMatrix(rotMat, space, mesh);
  88549. };
  88550. /**
  88551. * Add a rotation to the bone on an axis in local or world space
  88552. * @param axis The axis to rotate the bone on
  88553. * @param amount The amount to rotate the bone
  88554. * @param space The space that the axis is in
  88555. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88556. */
  88557. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  88558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88559. var rmat = Bone._tmpMats[0];
  88560. rmat.m[12] = 0;
  88561. rmat.m[13] = 0;
  88562. rmat.m[14] = 0;
  88563. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  88564. this._rotateWithMatrix(rmat, space, mesh);
  88565. };
  88566. /**
  88567. * Set the rotation of the bone to a particular axis angle in local or world space
  88568. * @param axis The axis to rotate the bone on
  88569. * @param angle The angle that the bone should be rotated to
  88570. * @param space The space that the axis is in
  88571. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88572. */
  88573. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  88574. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88575. if (space === BABYLON.Space.LOCAL) {
  88576. var quat = Bone._tmpQuat;
  88577. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  88578. this.setRotationQuaternion(quat, space, mesh);
  88579. return;
  88580. }
  88581. var rotMatInv = Bone._tmpMats[0];
  88582. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88583. return;
  88584. }
  88585. var rotMat = Bone._tmpMats[1];
  88586. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  88587. rotMatInv.multiplyToRef(rotMat, rotMat);
  88588. this._rotateWithMatrix(rotMat, space, mesh);
  88589. };
  88590. /**
  88591. * Set the euler rotation of the bone in local of world space
  88592. * @param rotation The euler rotation that the bone should be set to
  88593. * @param space The space that the rotation is in
  88594. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88595. */
  88596. Bone.prototype.setRotation = function (rotation, space, mesh) {
  88597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88598. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  88599. };
  88600. /**
  88601. * Set the quaternion rotation of the bone in local of world space
  88602. * @param quat The quaternion rotation that the bone should be set to
  88603. * @param space The space that the rotation is in
  88604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88605. */
  88606. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  88607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88608. if (space === BABYLON.Space.LOCAL) {
  88609. this._decompose();
  88610. this._localRotation.copyFrom(quat);
  88611. this._markAsDirtyAndCompose();
  88612. return;
  88613. }
  88614. var rotMatInv = Bone._tmpMats[0];
  88615. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88616. return;
  88617. }
  88618. var rotMat = Bone._tmpMats[1];
  88619. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  88620. rotMatInv.multiplyToRef(rotMat, rotMat);
  88621. this._rotateWithMatrix(rotMat, space, mesh);
  88622. };
  88623. /**
  88624. * Set the rotation matrix of the bone in local of world space
  88625. * @param rotMat The rotation matrix that the bone should be set to
  88626. * @param space The space that the rotation is in
  88627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88628. */
  88629. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  88630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88631. if (space === BABYLON.Space.LOCAL) {
  88632. var quat = Bone._tmpQuat;
  88633. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  88634. this.setRotationQuaternion(quat, space, mesh);
  88635. return;
  88636. }
  88637. var rotMatInv = Bone._tmpMats[0];
  88638. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  88639. return;
  88640. }
  88641. var rotMat2 = Bone._tmpMats[1];
  88642. rotMat2.copyFrom(rotMat);
  88643. rotMatInv.multiplyToRef(rotMat, rotMat2);
  88644. this._rotateWithMatrix(rotMat2, space, mesh);
  88645. };
  88646. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  88647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88648. var lmat = this.getLocalMatrix();
  88649. var lx = lmat.m[12];
  88650. var ly = lmat.m[13];
  88651. var lz = lmat.m[14];
  88652. var parent = this.getParent();
  88653. var parentScale = Bone._tmpMats[3];
  88654. var parentScaleInv = Bone._tmpMats[4];
  88655. if (parent && space == BABYLON.Space.WORLD) {
  88656. if (mesh) {
  88657. parentScale.copyFrom(mesh.getWorldMatrix());
  88658. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  88659. }
  88660. else {
  88661. parentScale.copyFrom(parent.getAbsoluteTransform());
  88662. }
  88663. parentScaleInv.copyFrom(parentScale);
  88664. parentScaleInv.invert();
  88665. lmat.multiplyToRef(parentScale, lmat);
  88666. lmat.multiplyToRef(rmat, lmat);
  88667. lmat.multiplyToRef(parentScaleInv, lmat);
  88668. }
  88669. else {
  88670. if (space == BABYLON.Space.WORLD && mesh) {
  88671. parentScale.copyFrom(mesh.getWorldMatrix());
  88672. parentScaleInv.copyFrom(parentScale);
  88673. parentScaleInv.invert();
  88674. lmat.multiplyToRef(parentScale, lmat);
  88675. lmat.multiplyToRef(rmat, lmat);
  88676. lmat.multiplyToRef(parentScaleInv, lmat);
  88677. }
  88678. else {
  88679. lmat.multiplyToRef(rmat, lmat);
  88680. }
  88681. }
  88682. lmat.m[12] = lx;
  88683. lmat.m[13] = ly;
  88684. lmat.m[14] = lz;
  88685. this.computeAbsoluteTransforms();
  88686. this._markAsDirtyAndDecompose();
  88687. };
  88688. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  88689. var scaleMatrix = Bone._tmpMats[2];
  88690. rotMatInv.copyFrom(this.getAbsoluteTransform());
  88691. if (mesh) {
  88692. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  88693. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  88694. }
  88695. rotMatInv.invert();
  88696. if (isNaN(rotMatInv.m[0])) {
  88697. // Matrix failed to invert.
  88698. // This can happen if scale is zero for example.
  88699. return false;
  88700. }
  88701. scaleMatrix.m[0] *= this._scalingDeterminant;
  88702. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  88703. return true;
  88704. };
  88705. /**
  88706. * Get the position of the bone in local or world space
  88707. * @param space The space that the returned position is in
  88708. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88709. * @returns The position of the bone
  88710. */
  88711. Bone.prototype.getPosition = function (space, mesh) {
  88712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88713. if (mesh === void 0) { mesh = null; }
  88714. var pos = BABYLON.Vector3.Zero();
  88715. this.getPositionToRef(space, mesh, pos);
  88716. return pos;
  88717. };
  88718. /**
  88719. * Copy the position of the bone to a vector3 in local or world space
  88720. * @param space The space that the returned position is in
  88721. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88722. * @param result The vector3 to copy the position to
  88723. */
  88724. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  88725. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88726. if (space == BABYLON.Space.LOCAL) {
  88727. var lm = this.getLocalMatrix();
  88728. result.x = lm.m[12];
  88729. result.y = lm.m[13];
  88730. result.z = lm.m[14];
  88731. }
  88732. else {
  88733. var wm = null;
  88734. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88735. if (mesh) {
  88736. wm = mesh.getWorldMatrix();
  88737. }
  88738. this._skeleton.computeAbsoluteTransforms();
  88739. var tmat = Bone._tmpMats[0];
  88740. if (mesh && wm) {
  88741. tmat.copyFrom(this.getAbsoluteTransform());
  88742. tmat.multiplyToRef(wm, tmat);
  88743. }
  88744. else {
  88745. tmat = this.getAbsoluteTransform();
  88746. }
  88747. result.x = tmat.m[12];
  88748. result.y = tmat.m[13];
  88749. result.z = tmat.m[14];
  88750. }
  88751. };
  88752. /**
  88753. * Get the absolute position of the bone (world space)
  88754. * @param mesh The mesh that this bone is attached to
  88755. * @returns The absolute position of the bone
  88756. */
  88757. Bone.prototype.getAbsolutePosition = function (mesh) {
  88758. if (mesh === void 0) { mesh = null; }
  88759. var pos = BABYLON.Vector3.Zero();
  88760. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  88761. return pos;
  88762. };
  88763. /**
  88764. * Copy the absolute position of the bone (world space) to the result param
  88765. * @param mesh The mesh that this bone is attached to
  88766. * @param result The vector3 to copy the absolute position to
  88767. */
  88768. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  88769. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  88770. };
  88771. /**
  88772. * Compute the absolute transforms of this bone and its children
  88773. */
  88774. Bone.prototype.computeAbsoluteTransforms = function () {
  88775. this._compose();
  88776. if (this._parent) {
  88777. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  88778. }
  88779. else {
  88780. this._absoluteTransform.copyFrom(this._localMatrix);
  88781. var poseMatrix = this._skeleton.getPoseMatrix();
  88782. if (poseMatrix) {
  88783. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  88784. }
  88785. }
  88786. var children = this.children;
  88787. var len = children.length;
  88788. for (var i = 0; i < len; i++) {
  88789. children[i].computeAbsoluteTransforms();
  88790. }
  88791. };
  88792. /**
  88793. * Get the world direction from an axis that is in the local space of the bone
  88794. * @param localAxis The local direction that is used to compute the world direction
  88795. * @param mesh The mesh that this bone is attached to
  88796. * @returns The world direction
  88797. */
  88798. Bone.prototype.getDirection = function (localAxis, mesh) {
  88799. if (mesh === void 0) { mesh = null; }
  88800. var result = BABYLON.Vector3.Zero();
  88801. this.getDirectionToRef(localAxis, mesh, result);
  88802. return result;
  88803. };
  88804. /**
  88805. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  88806. * @param localAxis The local direction that is used to compute the world direction
  88807. * @param mesh The mesh that this bone is attached to
  88808. * @param result The vector3 that the world direction will be copied to
  88809. */
  88810. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  88811. if (mesh === void 0) { mesh = null; }
  88812. var wm = null;
  88813. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88814. if (mesh) {
  88815. wm = mesh.getWorldMatrix();
  88816. }
  88817. this._skeleton.computeAbsoluteTransforms();
  88818. var mat = Bone._tmpMats[0];
  88819. mat.copyFrom(this.getAbsoluteTransform());
  88820. if (mesh && wm) {
  88821. mat.multiplyToRef(wm, mat);
  88822. }
  88823. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  88824. result.normalize();
  88825. };
  88826. /**
  88827. * Get the euler rotation of the bone in local or world space
  88828. * @param space The space that the rotation should be in
  88829. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88830. * @returns The euler rotation
  88831. */
  88832. Bone.prototype.getRotation = function (space, mesh) {
  88833. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88834. if (mesh === void 0) { mesh = null; }
  88835. var result = BABYLON.Vector3.Zero();
  88836. this.getRotationToRef(space, mesh, result);
  88837. return result;
  88838. };
  88839. /**
  88840. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  88841. * @param space The space that the rotation should be in
  88842. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88843. * @param result The vector3 that the rotation should be copied to
  88844. */
  88845. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  88846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88847. if (mesh === void 0) { mesh = null; }
  88848. var quat = Bone._tmpQuat;
  88849. this.getRotationQuaternionToRef(space, mesh, quat);
  88850. quat.toEulerAnglesToRef(result);
  88851. };
  88852. /**
  88853. * Get the quaternion rotation of the bone in either local or world space
  88854. * @param space The space that the rotation should be in
  88855. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88856. * @returns The quaternion rotation
  88857. */
  88858. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  88859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88860. if (mesh === void 0) { mesh = null; }
  88861. var result = BABYLON.Quaternion.Identity();
  88862. this.getRotationQuaternionToRef(space, mesh, result);
  88863. return result;
  88864. };
  88865. /**
  88866. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  88867. * @param space The space that the rotation should be in
  88868. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88869. * @param result The quaternion that the rotation should be copied to
  88870. */
  88871. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  88872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88873. if (mesh === void 0) { mesh = null; }
  88874. if (space == BABYLON.Space.LOCAL) {
  88875. this._decompose();
  88876. result.copyFrom(this._localRotation);
  88877. }
  88878. else {
  88879. var mat = Bone._tmpMats[0];
  88880. var amat = this.getAbsoluteTransform();
  88881. if (mesh) {
  88882. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88883. }
  88884. else {
  88885. mat.copyFrom(amat);
  88886. }
  88887. mat.m[0] *= this._scalingDeterminant;
  88888. mat.m[1] *= this._scalingDeterminant;
  88889. mat.m[2] *= this._scalingDeterminant;
  88890. mat.decompose(undefined, result, undefined);
  88891. }
  88892. };
  88893. /**
  88894. * Get the rotation matrix of the bone in local or world space
  88895. * @param space The space that the rotation should be in
  88896. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88897. * @returns The rotation matrix
  88898. */
  88899. Bone.prototype.getRotationMatrix = function (space, mesh) {
  88900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88901. var result = BABYLON.Matrix.Identity();
  88902. this.getRotationMatrixToRef(space, mesh, result);
  88903. return result;
  88904. };
  88905. /**
  88906. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  88907. * @param space The space that the rotation should be in
  88908. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88909. * @param result The quaternion that the rotation should be copied to
  88910. */
  88911. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  88912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88913. if (space == BABYLON.Space.LOCAL) {
  88914. this.getLocalMatrix().getRotationMatrixToRef(result);
  88915. }
  88916. else {
  88917. var mat = Bone._tmpMats[0];
  88918. var amat = this.getAbsoluteTransform();
  88919. if (mesh) {
  88920. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88921. }
  88922. else {
  88923. mat.copyFrom(amat);
  88924. }
  88925. mat.m[0] *= this._scalingDeterminant;
  88926. mat.m[1] *= this._scalingDeterminant;
  88927. mat.m[2] *= this._scalingDeterminant;
  88928. mat.getRotationMatrixToRef(result);
  88929. }
  88930. };
  88931. /**
  88932. * Get the world position of a point that is in the local space of the bone
  88933. * @param position The local position
  88934. * @param mesh The mesh that this bone is attached to
  88935. * @returns The world position
  88936. */
  88937. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  88938. if (mesh === void 0) { mesh = null; }
  88939. var result = BABYLON.Vector3.Zero();
  88940. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  88941. return result;
  88942. };
  88943. /**
  88944. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  88945. * @param position The local position
  88946. * @param mesh The mesh that this bone is attached to
  88947. * @param result The vector3 that the world position should be copied to
  88948. */
  88949. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  88950. if (mesh === void 0) { mesh = null; }
  88951. var wm = null;
  88952. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88953. if (mesh) {
  88954. wm = mesh.getWorldMatrix();
  88955. }
  88956. this._skeleton.computeAbsoluteTransforms();
  88957. var tmat = Bone._tmpMats[0];
  88958. if (mesh && wm) {
  88959. tmat.copyFrom(this.getAbsoluteTransform());
  88960. tmat.multiplyToRef(wm, tmat);
  88961. }
  88962. else {
  88963. tmat = this.getAbsoluteTransform();
  88964. }
  88965. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88966. };
  88967. /**
  88968. * Get the local position of a point that is in world space
  88969. * @param position The world position
  88970. * @param mesh The mesh that this bone is attached to
  88971. * @returns The local position
  88972. */
  88973. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  88974. if (mesh === void 0) { mesh = null; }
  88975. var result = BABYLON.Vector3.Zero();
  88976. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  88977. return result;
  88978. };
  88979. /**
  88980. * Get the local position of a point that is in world space and copy it to the result param
  88981. * @param position The world position
  88982. * @param mesh The mesh that this bone is attached to
  88983. * @param result The vector3 that the local position should be copied to
  88984. */
  88985. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  88986. if (mesh === void 0) { mesh = null; }
  88987. var wm = null;
  88988. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88989. if (mesh) {
  88990. wm = mesh.getWorldMatrix();
  88991. }
  88992. this._skeleton.computeAbsoluteTransforms();
  88993. var tmat = Bone._tmpMats[0];
  88994. tmat.copyFrom(this.getAbsoluteTransform());
  88995. if (mesh && wm) {
  88996. tmat.multiplyToRef(wm, tmat);
  88997. }
  88998. tmat.invert();
  88999. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89000. };
  89001. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89002. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  89003. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89004. return Bone;
  89005. }(BABYLON.Node));
  89006. BABYLON.Bone = Bone;
  89007. })(BABYLON || (BABYLON = {}));
  89008. //# sourceMappingURL=babylon.bone.js.map
  89009. var BABYLON;
  89010. (function (BABYLON) {
  89011. /**
  89012. * Class used to apply inverse kinematics to bones
  89013. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  89014. */
  89015. var BoneIKController = /** @class */ (function () {
  89016. /**
  89017. * Creates a new BoneIKController
  89018. * @param mesh defines the mesh to control
  89019. * @param bone defines the bone to control
  89020. * @param options defines options to set up the controller
  89021. */
  89022. function BoneIKController(mesh, bone, options) {
  89023. /**
  89024. * Gets or sets the target position
  89025. */
  89026. this.targetPosition = BABYLON.Vector3.Zero();
  89027. /**
  89028. * Gets or sets the pole target position
  89029. */
  89030. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89031. /**
  89032. * Gets or sets the pole target local offset
  89033. */
  89034. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89035. /**
  89036. * Gets or sets the pole angle
  89037. */
  89038. this.poleAngle = 0;
  89039. /**
  89040. * 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)
  89041. */
  89042. this.slerpAmount = 1;
  89043. this._bone1Quat = BABYLON.Quaternion.Identity();
  89044. this._bone1Mat = BABYLON.Matrix.Identity();
  89045. this._bone2Ang = Math.PI;
  89046. this._maxAngle = Math.PI;
  89047. this._rightHandedSystem = false;
  89048. this._bendAxis = BABYLON.Vector3.Right();
  89049. this._slerping = false;
  89050. this._adjustRoll = 0;
  89051. this._bone2 = bone;
  89052. this._bone1 = bone.getParent();
  89053. if (!this._bone1) {
  89054. return;
  89055. }
  89056. this.mesh = mesh;
  89057. var bonePos = bone.getPosition();
  89058. if (bone.getAbsoluteTransform().determinant() > 0) {
  89059. this._rightHandedSystem = true;
  89060. this._bendAxis.x = 0;
  89061. this._bendAxis.y = 0;
  89062. this._bendAxis.z = -1;
  89063. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89064. this._adjustRoll = Math.PI * .5;
  89065. this._bendAxis.z = 1;
  89066. }
  89067. }
  89068. if (this._bone1.length) {
  89069. var boneScale1 = this._bone1.getScale();
  89070. var boneScale2 = this._bone2.getScale();
  89071. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89072. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89073. }
  89074. else if (this._bone1.children[0]) {
  89075. mesh.computeWorldMatrix(true);
  89076. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89077. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89078. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89079. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89080. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89081. }
  89082. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89083. this.maxAngle = Math.PI;
  89084. if (options) {
  89085. if (options.targetMesh) {
  89086. this.targetMesh = options.targetMesh;
  89087. this.targetMesh.computeWorldMatrix(true);
  89088. }
  89089. if (options.poleTargetMesh) {
  89090. this.poleTargetMesh = options.poleTargetMesh;
  89091. this.poleTargetMesh.computeWorldMatrix(true);
  89092. }
  89093. else if (options.poleTargetBone) {
  89094. this.poleTargetBone = options.poleTargetBone;
  89095. }
  89096. else if (this._bone1.getParent()) {
  89097. this.poleTargetBone = this._bone1.getParent();
  89098. }
  89099. if (options.poleTargetLocalOffset) {
  89100. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89101. }
  89102. if (options.poleAngle) {
  89103. this.poleAngle = options.poleAngle;
  89104. }
  89105. if (options.bendAxis) {
  89106. this._bendAxis.copyFrom(options.bendAxis);
  89107. }
  89108. if (options.maxAngle) {
  89109. this.maxAngle = options.maxAngle;
  89110. }
  89111. if (options.slerpAmount) {
  89112. this.slerpAmount = options.slerpAmount;
  89113. }
  89114. }
  89115. }
  89116. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89117. /**
  89118. * Gets or sets maximum allowed angle
  89119. */
  89120. get: function () {
  89121. return this._maxAngle;
  89122. },
  89123. set: function (value) {
  89124. this._setMaxAngle(value);
  89125. },
  89126. enumerable: true,
  89127. configurable: true
  89128. });
  89129. BoneIKController.prototype._setMaxAngle = function (ang) {
  89130. if (ang < 0) {
  89131. ang = 0;
  89132. }
  89133. if (ang > Math.PI || ang == undefined) {
  89134. ang = Math.PI;
  89135. }
  89136. this._maxAngle = ang;
  89137. var a = this._bone1Length;
  89138. var b = this._bone2Length;
  89139. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89140. };
  89141. /**
  89142. * Force the controller to update the bones
  89143. */
  89144. BoneIKController.prototype.update = function () {
  89145. var bone1 = this._bone1;
  89146. if (!bone1) {
  89147. return;
  89148. }
  89149. var target = this.targetPosition;
  89150. var poleTarget = this.poleTargetPosition;
  89151. var mat1 = BoneIKController._tmpMats[0];
  89152. var mat2 = BoneIKController._tmpMats[1];
  89153. if (this.targetMesh) {
  89154. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89155. }
  89156. if (this.poleTargetBone) {
  89157. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89158. }
  89159. else if (this.poleTargetMesh) {
  89160. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89161. }
  89162. var bonePos = BoneIKController._tmpVecs[0];
  89163. var zaxis = BoneIKController._tmpVecs[1];
  89164. var xaxis = BoneIKController._tmpVecs[2];
  89165. var yaxis = BoneIKController._tmpVecs[3];
  89166. var upAxis = BoneIKController._tmpVecs[4];
  89167. var _tmpQuat = BoneIKController._tmpQuat;
  89168. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89169. poleTarget.subtractToRef(bonePos, upAxis);
  89170. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89171. upAxis.y = 1;
  89172. }
  89173. else {
  89174. upAxis.normalize();
  89175. }
  89176. target.subtractToRef(bonePos, yaxis);
  89177. yaxis.normalize();
  89178. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89179. zaxis.normalize();
  89180. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89181. xaxis.normalize();
  89182. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89183. var a = this._bone1Length;
  89184. var b = this._bone2Length;
  89185. var c = BABYLON.Vector3.Distance(bonePos, target);
  89186. if (this._maxReach > 0) {
  89187. c = Math.min(this._maxReach, c);
  89188. }
  89189. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  89190. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  89191. if (acosa > 1) {
  89192. acosa = 1;
  89193. }
  89194. if (acosb > 1) {
  89195. acosb = 1;
  89196. }
  89197. if (acosa < -1) {
  89198. acosa = -1;
  89199. }
  89200. if (acosb < -1) {
  89201. acosb = -1;
  89202. }
  89203. var angA = Math.acos(acosa);
  89204. var angB = Math.acos(acosb);
  89205. var angC = -angA - angB;
  89206. if (this._rightHandedSystem) {
  89207. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  89208. mat2.multiplyToRef(mat1, mat1);
  89209. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  89210. mat2.multiplyToRef(mat1, mat1);
  89211. }
  89212. else {
  89213. var _tmpVec = BoneIKController._tmpVecs[5];
  89214. _tmpVec.copyFrom(this._bendAxis);
  89215. _tmpVec.x *= -1;
  89216. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  89217. mat2.multiplyToRef(mat1, mat1);
  89218. }
  89219. if (this.poleAngle) {
  89220. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  89221. mat1.multiplyToRef(mat2, mat1);
  89222. }
  89223. if (this._bone1) {
  89224. if (this.slerpAmount < 1) {
  89225. if (!this._slerping) {
  89226. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  89227. }
  89228. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  89229. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  89230. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  89231. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  89232. this._slerping = true;
  89233. }
  89234. else {
  89235. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  89236. this._bone1Mat.copyFrom(mat1);
  89237. this._slerping = false;
  89238. }
  89239. }
  89240. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  89241. this._bone2Ang = angC;
  89242. };
  89243. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89244. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  89245. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89246. return BoneIKController;
  89247. }());
  89248. BABYLON.BoneIKController = BoneIKController;
  89249. })(BABYLON || (BABYLON = {}));
  89250. //# sourceMappingURL=babylon.boneIKController.js.map
  89251. var BABYLON;
  89252. (function (BABYLON) {
  89253. /**
  89254. * Class used to make a bone look toward a point in space
  89255. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  89256. */
  89257. var BoneLookController = /** @class */ (function () {
  89258. /**
  89259. * Create a BoneLookController
  89260. * @param mesh the mesh that the bone belongs to
  89261. * @param bone the bone that will be looking to the target
  89262. * @param target the target Vector3 to look at
  89263. * @param settings optional settings:
  89264. * * maxYaw: the maximum angle the bone will yaw to
  89265. * * minYaw: the minimum angle the bone will yaw to
  89266. * * maxPitch: the maximum angle the bone will pitch to
  89267. * * minPitch: the minimum angle the bone will yaw to
  89268. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  89269. * * upAxis: the up axis of the coordinate system
  89270. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  89271. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  89272. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  89273. * * adjustYaw: used to make an adjustment to the yaw of the bone
  89274. * * adjustPitch: used to make an adjustment to the pitch of the bone
  89275. * * adjustRoll: used to make an adjustment to the roll of the bone
  89276. **/
  89277. function BoneLookController(mesh, bone, target, options) {
  89278. /**
  89279. * The up axis of the coordinate system that is used when the bone is rotated
  89280. */
  89281. this.upAxis = BABYLON.Vector3.Up();
  89282. /**
  89283. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  89284. */
  89285. this.upAxisSpace = BABYLON.Space.LOCAL;
  89286. /**
  89287. * Used to make an adjustment to the yaw of the bone
  89288. */
  89289. this.adjustYaw = 0;
  89290. /**
  89291. * Used to make an adjustment to the pitch of the bone
  89292. */
  89293. this.adjustPitch = 0;
  89294. /**
  89295. * Used to make an adjustment to the roll of the bone
  89296. */
  89297. this.adjustRoll = 0;
  89298. /**
  89299. * 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)
  89300. */
  89301. this.slerpAmount = 1;
  89302. this._boneQuat = BABYLON.Quaternion.Identity();
  89303. this._slerping = false;
  89304. this._firstFrameSkipped = false;
  89305. this._fowardAxis = BABYLON.Vector3.Forward();
  89306. this.mesh = mesh;
  89307. this.bone = bone;
  89308. this.target = target;
  89309. if (options) {
  89310. if (options.adjustYaw) {
  89311. this.adjustYaw = options.adjustYaw;
  89312. }
  89313. if (options.adjustPitch) {
  89314. this.adjustPitch = options.adjustPitch;
  89315. }
  89316. if (options.adjustRoll) {
  89317. this.adjustRoll = options.adjustRoll;
  89318. }
  89319. if (options.maxYaw != null) {
  89320. this.maxYaw = options.maxYaw;
  89321. }
  89322. else {
  89323. this.maxYaw = Math.PI;
  89324. }
  89325. if (options.minYaw != null) {
  89326. this.minYaw = options.minYaw;
  89327. }
  89328. else {
  89329. this.minYaw = -Math.PI;
  89330. }
  89331. if (options.maxPitch != null) {
  89332. this.maxPitch = options.maxPitch;
  89333. }
  89334. else {
  89335. this.maxPitch = Math.PI;
  89336. }
  89337. if (options.minPitch != null) {
  89338. this.minPitch = options.minPitch;
  89339. }
  89340. else {
  89341. this.minPitch = -Math.PI;
  89342. }
  89343. if (options.slerpAmount != null) {
  89344. this.slerpAmount = options.slerpAmount;
  89345. }
  89346. if (options.upAxis != null) {
  89347. this.upAxis = options.upAxis;
  89348. }
  89349. if (options.upAxisSpace != null) {
  89350. this.upAxisSpace = options.upAxisSpace;
  89351. }
  89352. if (options.yawAxis != null || options.pitchAxis != null) {
  89353. var newYawAxis = BABYLON.Axis.Y;
  89354. var newPitchAxis = BABYLON.Axis.X;
  89355. if (options.yawAxis != null) {
  89356. newYawAxis = options.yawAxis.clone();
  89357. newYawAxis.normalize();
  89358. }
  89359. if (options.pitchAxis != null) {
  89360. newPitchAxis = options.pitchAxis.clone();
  89361. newPitchAxis.normalize();
  89362. }
  89363. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  89364. this._transformYawPitch = BABYLON.Matrix.Identity();
  89365. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  89366. this._transformYawPitchInv = this._transformYawPitch.clone();
  89367. this._transformYawPitch.invert();
  89368. }
  89369. }
  89370. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  89371. this.upAxisSpace = BABYLON.Space.LOCAL;
  89372. }
  89373. }
  89374. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  89375. /**
  89376. * Gets or sets the minimum yaw angle that the bone can look to
  89377. */
  89378. get: function () {
  89379. return this._minYaw;
  89380. },
  89381. set: function (value) {
  89382. this._minYaw = value;
  89383. this._minYawSin = Math.sin(value);
  89384. this._minYawCos = Math.cos(value);
  89385. if (this._maxYaw != null) {
  89386. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  89387. this._yawRange = this._maxYaw - this._minYaw;
  89388. }
  89389. },
  89390. enumerable: true,
  89391. configurable: true
  89392. });
  89393. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  89394. /**
  89395. * Gets or sets the maximum yaw angle that the bone can look to
  89396. */
  89397. get: function () {
  89398. return this._maxYaw;
  89399. },
  89400. set: function (value) {
  89401. this._maxYaw = value;
  89402. this._maxYawSin = Math.sin(value);
  89403. this._maxYawCos = Math.cos(value);
  89404. if (this._minYaw != null) {
  89405. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  89406. this._yawRange = this._maxYaw - this._minYaw;
  89407. }
  89408. },
  89409. enumerable: true,
  89410. configurable: true
  89411. });
  89412. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  89413. /**
  89414. * Gets or sets the minimum pitch angle that the bone can look to
  89415. */
  89416. get: function () {
  89417. return this._minPitch;
  89418. },
  89419. set: function (value) {
  89420. this._minPitch = value;
  89421. this._minPitchTan = Math.tan(value);
  89422. },
  89423. enumerable: true,
  89424. configurable: true
  89425. });
  89426. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  89427. /**
  89428. * Gets or sets the maximum pitch angle that the bone can look to
  89429. */
  89430. get: function () {
  89431. return this._maxPitch;
  89432. },
  89433. set: function (value) {
  89434. this._maxPitch = value;
  89435. this._maxPitchTan = Math.tan(value);
  89436. },
  89437. enumerable: true,
  89438. configurable: true
  89439. });
  89440. /**
  89441. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  89442. */
  89443. BoneLookController.prototype.update = function () {
  89444. //skip the first frame when slerping so that the mesh rotation is correct
  89445. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  89446. this._firstFrameSkipped = true;
  89447. return;
  89448. }
  89449. var bone = this.bone;
  89450. var bonePos = BoneLookController._tmpVecs[0];
  89451. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  89452. var target = this.target;
  89453. var _tmpMat1 = BoneLookController._tmpMats[0];
  89454. var _tmpMat2 = BoneLookController._tmpMats[1];
  89455. var mesh = this.mesh;
  89456. var parentBone = bone.getParent();
  89457. var upAxis = BoneLookController._tmpVecs[1];
  89458. upAxis.copyFrom(this.upAxis);
  89459. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  89460. if (this._transformYawPitch) {
  89461. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  89462. }
  89463. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  89464. }
  89465. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  89466. mesh.getDirectionToRef(upAxis, upAxis);
  89467. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  89468. upAxis.normalize();
  89469. }
  89470. }
  89471. var checkYaw = false;
  89472. var checkPitch = false;
  89473. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  89474. checkYaw = true;
  89475. }
  89476. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  89477. checkPitch = true;
  89478. }
  89479. if (checkYaw || checkPitch) {
  89480. var spaceMat = BoneLookController._tmpMats[2];
  89481. var spaceMatInv = BoneLookController._tmpMats[3];
  89482. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  89483. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  89484. }
  89485. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  89486. spaceMat.copyFrom(mesh.getWorldMatrix());
  89487. }
  89488. else {
  89489. var forwardAxis = BoneLookController._tmpVecs[2];
  89490. forwardAxis.copyFrom(this._fowardAxis);
  89491. if (this._transformYawPitch) {
  89492. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  89493. }
  89494. if (parentBone) {
  89495. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  89496. }
  89497. else {
  89498. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  89499. }
  89500. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  89501. rightAxis.normalize();
  89502. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  89503. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  89504. }
  89505. spaceMat.invertToRef(spaceMatInv);
  89506. var xzlen = null;
  89507. if (checkPitch) {
  89508. var localTarget = BoneLookController._tmpVecs[3];
  89509. target.subtractToRef(bonePos, localTarget);
  89510. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  89511. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89512. var pitch = Math.atan2(localTarget.y, xzlen);
  89513. var newPitch = pitch;
  89514. if (pitch > this._maxPitch) {
  89515. localTarget.y = this._maxPitchTan * xzlen;
  89516. newPitch = this._maxPitch;
  89517. }
  89518. else if (pitch < this._minPitch) {
  89519. localTarget.y = this._minPitchTan * xzlen;
  89520. newPitch = this._minPitch;
  89521. }
  89522. if (pitch != newPitch) {
  89523. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  89524. localTarget.addInPlace(bonePos);
  89525. target = localTarget;
  89526. }
  89527. }
  89528. if (checkYaw) {
  89529. var localTarget = BoneLookController._tmpVecs[4];
  89530. target.subtractToRef(bonePos, localTarget);
  89531. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  89532. var yaw = Math.atan2(localTarget.x, localTarget.z);
  89533. var newYaw = yaw;
  89534. if (yaw > this._maxYaw || yaw < this._minYaw) {
  89535. if (xzlen == null) {
  89536. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89537. }
  89538. if (this._yawRange > Math.PI) {
  89539. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  89540. localTarget.z = this._maxYawCos * xzlen;
  89541. localTarget.x = this._maxYawSin * xzlen;
  89542. newYaw = this._maxYaw;
  89543. }
  89544. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  89545. localTarget.z = this._minYawCos * xzlen;
  89546. localTarget.x = this._minYawSin * xzlen;
  89547. newYaw = this._minYaw;
  89548. }
  89549. }
  89550. else {
  89551. if (yaw > this._maxYaw) {
  89552. localTarget.z = this._maxYawCos * xzlen;
  89553. localTarget.x = this._maxYawSin * xzlen;
  89554. newYaw = this._maxYaw;
  89555. }
  89556. else if (yaw < this._minYaw) {
  89557. localTarget.z = this._minYawCos * xzlen;
  89558. localTarget.x = this._minYawSin * xzlen;
  89559. newYaw = this._minYaw;
  89560. }
  89561. }
  89562. }
  89563. if (this._slerping && this._yawRange > Math.PI) {
  89564. //are we going to be crossing into the min/max region?
  89565. var boneFwd = BoneLookController._tmpVecs[8];
  89566. boneFwd.copyFrom(BABYLON.Axis.Z);
  89567. if (this._transformYawPitch) {
  89568. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  89569. }
  89570. var boneRotMat = BoneLookController._tmpMats[4];
  89571. this._boneQuat.toRotationMatrix(boneRotMat);
  89572. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  89573. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  89574. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  89575. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  89576. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  89577. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  89578. if (angBtwTar > angBtwMidYaw) {
  89579. if (xzlen == null) {
  89580. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  89581. }
  89582. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  89583. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  89584. if (angBtwMin < angBtwMax) {
  89585. newYaw = boneYaw + Math.PI * .75;
  89586. localTarget.z = Math.cos(newYaw) * xzlen;
  89587. localTarget.x = Math.sin(newYaw) * xzlen;
  89588. }
  89589. else {
  89590. newYaw = boneYaw - Math.PI * .75;
  89591. localTarget.z = Math.cos(newYaw) * xzlen;
  89592. localTarget.x = Math.sin(newYaw) * xzlen;
  89593. }
  89594. }
  89595. }
  89596. if (yaw != newYaw) {
  89597. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  89598. localTarget.addInPlace(bonePos);
  89599. target = localTarget;
  89600. }
  89601. }
  89602. }
  89603. var zaxis = BoneLookController._tmpVecs[5];
  89604. var xaxis = BoneLookController._tmpVecs[6];
  89605. var yaxis = BoneLookController._tmpVecs[7];
  89606. var _tmpQuat = BoneLookController._tmpQuat;
  89607. target.subtractToRef(bonePos, zaxis);
  89608. zaxis.normalize();
  89609. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  89610. xaxis.normalize();
  89611. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  89612. yaxis.normalize();
  89613. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  89614. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  89615. return;
  89616. }
  89617. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  89618. return;
  89619. }
  89620. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  89621. return;
  89622. }
  89623. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  89624. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  89625. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  89626. }
  89627. if (this.slerpAmount < 1) {
  89628. if (!this._slerping) {
  89629. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  89630. }
  89631. if (this._transformYawPitch) {
  89632. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  89633. }
  89634. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  89635. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  89636. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  89637. this._slerping = true;
  89638. }
  89639. else {
  89640. if (this._transformYawPitch) {
  89641. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  89642. }
  89643. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  89644. this._slerping = false;
  89645. }
  89646. };
  89647. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  89648. var angDiff = ang2 - ang1;
  89649. angDiff %= Math.PI * 2;
  89650. if (angDiff > Math.PI) {
  89651. angDiff -= Math.PI * 2;
  89652. }
  89653. else if (angDiff < -Math.PI) {
  89654. angDiff += Math.PI * 2;
  89655. }
  89656. return angDiff;
  89657. };
  89658. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  89659. ang1 %= (2 * Math.PI);
  89660. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  89661. ang2 %= (2 * Math.PI);
  89662. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  89663. var ab = 0;
  89664. if (ang1 < ang2) {
  89665. ab = ang2 - ang1;
  89666. }
  89667. else {
  89668. ab = ang1 - ang2;
  89669. }
  89670. if (ab > Math.PI) {
  89671. ab = Math.PI * 2 - ab;
  89672. }
  89673. return ab;
  89674. };
  89675. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  89676. ang %= (2 * Math.PI);
  89677. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  89678. ang1 %= (2 * Math.PI);
  89679. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  89680. ang2 %= (2 * Math.PI);
  89681. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  89682. if (ang1 < ang2) {
  89683. if (ang > ang1 && ang < ang2) {
  89684. return true;
  89685. }
  89686. }
  89687. else {
  89688. if (ang > ang2 && ang < ang1) {
  89689. return true;
  89690. }
  89691. }
  89692. return false;
  89693. };
  89694. 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()];
  89695. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  89696. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89697. return BoneLookController;
  89698. }());
  89699. BABYLON.BoneLookController = BoneLookController;
  89700. })(BABYLON || (BABYLON = {}));
  89701. //# sourceMappingURL=babylon.boneLookController.js.map
  89702. var BABYLON;
  89703. (function (BABYLON) {
  89704. /**
  89705. * Class used to handle skinning animations
  89706. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  89707. */
  89708. var Skeleton = /** @class */ (function () {
  89709. /**
  89710. * Creates a new skeleton
  89711. * @param name defines the skeleton name
  89712. * @param id defines the skeleton Id
  89713. * @param scene defines the hosting scene
  89714. */
  89715. function Skeleton(
  89716. /** defines the skeleton name */
  89717. name,
  89718. /** defines the skeleton Id */
  89719. id, scene) {
  89720. this.name = name;
  89721. this.id = id;
  89722. /**
  89723. * Gets the list of child bones
  89724. */
  89725. this.bones = new Array();
  89726. /**
  89727. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  89728. */
  89729. this.needInitialSkinMatrix = false;
  89730. this._isDirty = true;
  89731. this._meshesWithPoseMatrix = new Array();
  89732. this._identity = BABYLON.Matrix.Identity();
  89733. this._ranges = {};
  89734. this._lastAbsoluteTransformsUpdateId = -1;
  89735. /**
  89736. * Specifies if the skeleton should be serialized
  89737. */
  89738. this.doNotSerialize = false;
  89739. this._animationPropertiesOverride = null;
  89740. // Events
  89741. /**
  89742. * An observable triggered before computing the skeleton's matrices
  89743. */
  89744. this.onBeforeComputeObservable = new BABYLON.Observable();
  89745. this.bones = [];
  89746. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89747. scene.skeletons.push(this);
  89748. //make sure it will recalculate the matrix next time prepare is called.
  89749. this._isDirty = true;
  89750. }
  89751. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  89752. /**
  89753. * Gets or sets the animation properties override
  89754. */
  89755. get: function () {
  89756. if (!this._animationPropertiesOverride) {
  89757. return this._scene.animationPropertiesOverride;
  89758. }
  89759. return this._animationPropertiesOverride;
  89760. },
  89761. set: function (value) {
  89762. this._animationPropertiesOverride = value;
  89763. },
  89764. enumerable: true,
  89765. configurable: true
  89766. });
  89767. // Members
  89768. /**
  89769. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  89770. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  89771. * @returns a Float32Array containing matrices data
  89772. */
  89773. Skeleton.prototype.getTransformMatrices = function (mesh) {
  89774. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  89775. return mesh._bonesTransformMatrices;
  89776. }
  89777. if (!this._transformMatrices) {
  89778. this.prepare();
  89779. }
  89780. return this._transformMatrices;
  89781. };
  89782. /**
  89783. * Gets the current hosting scene
  89784. * @returns a scene object
  89785. */
  89786. Skeleton.prototype.getScene = function () {
  89787. return this._scene;
  89788. };
  89789. // Methods
  89790. /**
  89791. * Gets a string representing the current skeleton data
  89792. * @param fullDetails defines a boolean indicating if we want a verbose version
  89793. * @returns a string representing the current skeleton data
  89794. */
  89795. Skeleton.prototype.toString = function (fullDetails) {
  89796. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  89797. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  89798. if (fullDetails) {
  89799. ret += ", Ranges: {";
  89800. var first = true;
  89801. for (var name_1 in this._ranges) {
  89802. if (first) {
  89803. ret += ", ";
  89804. first = false;
  89805. }
  89806. ret += name_1;
  89807. }
  89808. ret += "}";
  89809. }
  89810. return ret;
  89811. };
  89812. /**
  89813. * Get bone's index searching by name
  89814. * @param name defines bone's name to search for
  89815. * @return the indice of the bone. Returns -1 if not found
  89816. */
  89817. Skeleton.prototype.getBoneIndexByName = function (name) {
  89818. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  89819. if (this.bones[boneIndex].name === name) {
  89820. return boneIndex;
  89821. }
  89822. }
  89823. return -1;
  89824. };
  89825. /**
  89826. * Creater a new animation range
  89827. * @param name defines the name of the range
  89828. * @param from defines the start key
  89829. * @param to defines the end key
  89830. */
  89831. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  89832. // check name not already in use
  89833. if (!this._ranges[name]) {
  89834. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  89835. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89836. if (this.bones[i].animations[0]) {
  89837. this.bones[i].animations[0].createRange(name, from, to);
  89838. }
  89839. }
  89840. }
  89841. };
  89842. /**
  89843. * Delete a specific animation range
  89844. * @param name defines the name of the range
  89845. * @param deleteFrames defines if frames must be removed as well
  89846. */
  89847. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  89848. if (deleteFrames === void 0) { deleteFrames = true; }
  89849. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89850. if (this.bones[i].animations[0]) {
  89851. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  89852. }
  89853. }
  89854. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  89855. };
  89856. /**
  89857. * Gets a specific animation range
  89858. * @param name defines the name of the range to look for
  89859. * @returns the requested animation range or null if not found
  89860. */
  89861. Skeleton.prototype.getAnimationRange = function (name) {
  89862. return this._ranges[name];
  89863. };
  89864. /**
  89865. * Gets the list of all animation ranges defined on this skeleton
  89866. * @returns an array
  89867. */
  89868. Skeleton.prototype.getAnimationRanges = function () {
  89869. var animationRanges = [];
  89870. var name;
  89871. var i = 0;
  89872. for (name in this._ranges) {
  89873. animationRanges[i] = this._ranges[name];
  89874. i++;
  89875. }
  89876. return animationRanges;
  89877. };
  89878. /**
  89879. * Copy animation range from a source skeleton.
  89880. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  89881. * @param source defines the source skeleton
  89882. * @param name defines the name of the range to copy
  89883. * @param rescaleAsRequired defines if rescaling must be applied if required
  89884. * @returns true if operation was successful
  89885. */
  89886. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  89887. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89888. if (this._ranges[name] || !source.getAnimationRange(name)) {
  89889. return false;
  89890. }
  89891. var ret = true;
  89892. var frameOffset = this._getHighestAnimationFrame() + 1;
  89893. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  89894. var boneDict = {};
  89895. var sourceBones = source.bones;
  89896. var nBones;
  89897. var i;
  89898. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  89899. boneDict[sourceBones[i].name] = sourceBones[i];
  89900. }
  89901. if (this.bones.length !== sourceBones.length) {
  89902. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  89903. ret = false;
  89904. }
  89905. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  89906. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  89907. var boneName = this.bones[i].name;
  89908. var sourceBone = boneDict[boneName];
  89909. if (sourceBone) {
  89910. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  89911. }
  89912. else {
  89913. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  89914. ret = false;
  89915. }
  89916. }
  89917. // do not call createAnimationRange(), since it also is done to bones, which was already done
  89918. var range = source.getAnimationRange(name);
  89919. if (range) {
  89920. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  89921. }
  89922. return ret;
  89923. };
  89924. /**
  89925. * Forces the skeleton to go to rest pose
  89926. */
  89927. Skeleton.prototype.returnToRest = function () {
  89928. for (var index = 0; index < this.bones.length; index++) {
  89929. this.bones[index].returnToRest();
  89930. }
  89931. };
  89932. Skeleton.prototype._getHighestAnimationFrame = function () {
  89933. var ret = 0;
  89934. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89935. if (this.bones[i].animations[0]) {
  89936. var highest = this.bones[i].animations[0].getHighestFrame();
  89937. if (ret < highest) {
  89938. ret = highest;
  89939. }
  89940. }
  89941. }
  89942. return ret;
  89943. };
  89944. /**
  89945. * Begin a specific animation range
  89946. * @param name defines the name of the range to start
  89947. * @param loop defines if looping must be turned on (false by default)
  89948. * @param speedRatio defines the speed ratio to apply (1 by default)
  89949. * @param onAnimationEnd defines a callback which will be called when animation will end
  89950. * @returns a new animatable
  89951. */
  89952. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  89953. var range = this.getAnimationRange(name);
  89954. if (!range) {
  89955. return null;
  89956. }
  89957. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  89958. };
  89959. /** @hidden */
  89960. Skeleton.prototype._markAsDirty = function () {
  89961. this._isDirty = true;
  89962. };
  89963. /** @hidden */
  89964. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  89965. this._meshesWithPoseMatrix.push(mesh);
  89966. };
  89967. /** @hidden */
  89968. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  89969. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  89970. if (index > -1) {
  89971. this._meshesWithPoseMatrix.splice(index, 1);
  89972. }
  89973. };
  89974. /** @hidden */
  89975. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  89976. this.onBeforeComputeObservable.notifyObservers(this);
  89977. for (var index = 0; index < this.bones.length; index++) {
  89978. var bone = this.bones[index];
  89979. var parentBone = bone.getParent();
  89980. if (parentBone) {
  89981. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  89982. }
  89983. else {
  89984. if (initialSkinMatrix) {
  89985. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  89986. }
  89987. else {
  89988. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  89989. }
  89990. }
  89991. if (bone._index !== -1) {
  89992. var mappedIndex = bone._index === null ? index : bone._index;
  89993. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  89994. }
  89995. }
  89996. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  89997. };
  89998. /**
  89999. * Build all resources required to render a skeleton
  90000. */
  90001. Skeleton.prototype.prepare = function () {
  90002. if (!this._isDirty) {
  90003. return;
  90004. }
  90005. if (this.needInitialSkinMatrix) {
  90006. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  90007. var mesh = this._meshesWithPoseMatrix[index];
  90008. var poseMatrix = mesh.getPoseMatrix();
  90009. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  90010. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90011. }
  90012. if (this._synchronizedWithMesh !== mesh) {
  90013. this._synchronizedWithMesh = mesh;
  90014. // Prepare bones
  90015. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  90016. var bone = this.bones[boneIndex];
  90017. if (!bone.getParent()) {
  90018. var matrix = bone.getBaseMatrix();
  90019. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  90020. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  90021. }
  90022. }
  90023. }
  90024. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  90025. }
  90026. }
  90027. else {
  90028. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90029. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90030. }
  90031. this._computeTransformMatrices(this._transformMatrices, null);
  90032. }
  90033. this._isDirty = false;
  90034. this._scene._activeBones.addCount(this.bones.length, false);
  90035. };
  90036. /**
  90037. * Gets the list of animatables currently running for this skeleton
  90038. * @returns an array of animatables
  90039. */
  90040. Skeleton.prototype.getAnimatables = function () {
  90041. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90042. this._animatables = [];
  90043. for (var index = 0; index < this.bones.length; index++) {
  90044. this._animatables.push(this.bones[index]);
  90045. }
  90046. }
  90047. return this._animatables;
  90048. };
  90049. /**
  90050. * Clone the current skeleton
  90051. * @param name defines the name of the new skeleton
  90052. * @param id defines the id of the enw skeleton
  90053. * @returns the new skeleton
  90054. */
  90055. Skeleton.prototype.clone = function (name, id) {
  90056. var result = new Skeleton(name, id || name, this._scene);
  90057. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90058. for (var index = 0; index < this.bones.length; index++) {
  90059. var source = this.bones[index];
  90060. var parentBone = null;
  90061. var parent_1 = source.getParent();
  90062. if (parent_1) {
  90063. var parentIndex = this.bones.indexOf(parent_1);
  90064. parentBone = result.bones[parentIndex];
  90065. }
  90066. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90067. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90068. }
  90069. if (this._ranges) {
  90070. result._ranges = {};
  90071. for (var rangeName in this._ranges) {
  90072. var range = this._ranges[rangeName];
  90073. if (range) {
  90074. result._ranges[rangeName] = range.clone();
  90075. }
  90076. }
  90077. }
  90078. this._isDirty = true;
  90079. return result;
  90080. };
  90081. /**
  90082. * Enable animation blending for this skeleton
  90083. * @param blendingSpeed defines the blending speed to apply
  90084. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90085. */
  90086. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90087. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90088. this.bones.forEach(function (bone) {
  90089. bone.animations.forEach(function (animation) {
  90090. animation.enableBlending = true;
  90091. animation.blendingSpeed = blendingSpeed;
  90092. });
  90093. });
  90094. };
  90095. /**
  90096. * Releases all resources associated with the current skeleton
  90097. */
  90098. Skeleton.prototype.dispose = function () {
  90099. this._meshesWithPoseMatrix = [];
  90100. // Animations
  90101. this.getScene().stopAnimation(this);
  90102. // Remove from scene
  90103. this.getScene().removeSkeleton(this);
  90104. };
  90105. /**
  90106. * Serialize the skeleton in a JSON object
  90107. * @returns a JSON object
  90108. */
  90109. Skeleton.prototype.serialize = function () {
  90110. var serializationObject = {};
  90111. serializationObject.name = this.name;
  90112. serializationObject.id = this.id;
  90113. if (this.dimensionsAtRest) {
  90114. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90115. }
  90116. serializationObject.bones = [];
  90117. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90118. for (var index = 0; index < this.bones.length; index++) {
  90119. var bone = this.bones[index];
  90120. var parent_2 = bone.getParent();
  90121. var serializedBone = {
  90122. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90123. name: bone.name,
  90124. matrix: bone.getBaseMatrix().toArray(),
  90125. rest: bone.getRestPose().toArray()
  90126. };
  90127. serializationObject.bones.push(serializedBone);
  90128. if (bone.length) {
  90129. serializedBone.length = bone.length;
  90130. }
  90131. if (bone.metadata) {
  90132. serializedBone.metadata = bone.metadata;
  90133. }
  90134. if (bone.animations && bone.animations.length > 0) {
  90135. serializedBone.animation = bone.animations[0].serialize();
  90136. }
  90137. serializationObject.ranges = [];
  90138. for (var name in this._ranges) {
  90139. var source = this._ranges[name];
  90140. if (!source) {
  90141. continue;
  90142. }
  90143. var range = {};
  90144. range.name = name;
  90145. range.from = source.from;
  90146. range.to = source.to;
  90147. serializationObject.ranges.push(range);
  90148. }
  90149. }
  90150. return serializationObject;
  90151. };
  90152. /**
  90153. * Creates a new skeleton from serialized data
  90154. * @param parsedSkeleton defines the serialized data
  90155. * @param scene defines the hosting scene
  90156. * @returns a new skeleton
  90157. */
  90158. Skeleton.Parse = function (parsedSkeleton, scene) {
  90159. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90160. if (parsedSkeleton.dimensionsAtRest) {
  90161. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90162. }
  90163. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90164. var index;
  90165. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90166. var parsedBone = parsedSkeleton.bones[index];
  90167. var parentBone = null;
  90168. if (parsedBone.parentBoneIndex > -1) {
  90169. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90170. }
  90171. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90172. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90173. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90174. bone.id = parsedBone.id;
  90175. }
  90176. if (parsedBone.length) {
  90177. bone.length = parsedBone.length;
  90178. }
  90179. if (parsedBone.metadata) {
  90180. bone.metadata = parsedBone.metadata;
  90181. }
  90182. if (parsedBone.animation) {
  90183. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  90184. }
  90185. }
  90186. // placed after bones, so createAnimationRange can cascade down
  90187. if (parsedSkeleton.ranges) {
  90188. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  90189. var data = parsedSkeleton.ranges[index];
  90190. skeleton.createAnimationRange(data.name, data.from, data.to);
  90191. }
  90192. }
  90193. return skeleton;
  90194. };
  90195. /**
  90196. * Compute all node absolute transforms
  90197. * @param forceUpdate defines if computation must be done even if cache is up to date
  90198. */
  90199. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  90200. if (forceUpdate === void 0) { forceUpdate = false; }
  90201. var renderId = this._scene.getRenderId();
  90202. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  90203. this.bones[0].computeAbsoluteTransforms();
  90204. this._lastAbsoluteTransformsUpdateId = renderId;
  90205. }
  90206. };
  90207. /**
  90208. * Gets the root pose matrix
  90209. * @returns a matrix
  90210. */
  90211. Skeleton.prototype.getPoseMatrix = function () {
  90212. var poseMatrix = null;
  90213. if (this._meshesWithPoseMatrix.length > 0) {
  90214. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  90215. }
  90216. return poseMatrix;
  90217. };
  90218. /**
  90219. * Sorts bones per internal index
  90220. */
  90221. Skeleton.prototype.sortBones = function () {
  90222. var bones = new Array();
  90223. var visited = new Array(this.bones.length);
  90224. for (var index = 0; index < this.bones.length; index++) {
  90225. this._sortBones(index, bones, visited);
  90226. }
  90227. this.bones = bones;
  90228. };
  90229. Skeleton.prototype._sortBones = function (index, bones, visited) {
  90230. if (visited[index]) {
  90231. return;
  90232. }
  90233. visited[index] = true;
  90234. var bone = this.bones[index];
  90235. if (bone._index === undefined) {
  90236. bone._index = index;
  90237. }
  90238. var parentBone = bone.getParent();
  90239. if (parentBone) {
  90240. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  90241. }
  90242. bones.push(bone);
  90243. };
  90244. return Skeleton;
  90245. }());
  90246. BABYLON.Skeleton = Skeleton;
  90247. })(BABYLON || (BABYLON = {}));
  90248. //# sourceMappingURL=babylon.skeleton.js.map
  90249. var BABYLON;
  90250. (function (BABYLON) {
  90251. ;
  90252. /**
  90253. * This groups tools to convert HDR texture to native colors array.
  90254. */
  90255. var HDRTools = /** @class */ (function () {
  90256. function HDRTools() {
  90257. }
  90258. HDRTools.Ldexp = function (mantissa, exponent) {
  90259. if (exponent > 1023) {
  90260. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  90261. }
  90262. if (exponent < -1074) {
  90263. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  90264. }
  90265. return mantissa * Math.pow(2, exponent);
  90266. };
  90267. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  90268. if (exponent > 0) { /*nonzero pixel*/
  90269. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  90270. float32array[index + 0] = red * exponent;
  90271. float32array[index + 1] = green * exponent;
  90272. float32array[index + 2] = blue * exponent;
  90273. }
  90274. else {
  90275. float32array[index + 0] = 0;
  90276. float32array[index + 1] = 0;
  90277. float32array[index + 2] = 0;
  90278. }
  90279. };
  90280. HDRTools.readStringLine = function (uint8array, startIndex) {
  90281. var line = "";
  90282. var character = "";
  90283. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  90284. character = String.fromCharCode(uint8array[i]);
  90285. if (character == "\n") {
  90286. break;
  90287. }
  90288. line += character;
  90289. }
  90290. return line;
  90291. };
  90292. /**
  90293. * Reads header information from an RGBE texture stored in a native array.
  90294. * More information on this format are available here:
  90295. * https://en.wikipedia.org/wiki/RGBE_image_format
  90296. *
  90297. * @param uint8array The binary file stored in native array.
  90298. * @return The header information.
  90299. */
  90300. HDRTools.RGBE_ReadHeader = function (uint8array) {
  90301. var height = 0;
  90302. var width = 0;
  90303. var line = this.readStringLine(uint8array, 0);
  90304. if (line[0] != '#' || line[1] != '?') {
  90305. throw "Bad HDR Format.";
  90306. }
  90307. var endOfHeader = false;
  90308. var findFormat = false;
  90309. var lineIndex = 0;
  90310. do {
  90311. lineIndex += (line.length + 1);
  90312. line = this.readStringLine(uint8array, lineIndex);
  90313. if (line == "FORMAT=32-bit_rle_rgbe") {
  90314. findFormat = true;
  90315. }
  90316. else if (line.length == 0) {
  90317. endOfHeader = true;
  90318. }
  90319. } while (!endOfHeader);
  90320. if (!findFormat) {
  90321. throw "HDR Bad header format, unsupported FORMAT";
  90322. }
  90323. lineIndex += (line.length + 1);
  90324. line = this.readStringLine(uint8array, lineIndex);
  90325. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  90326. var match = sizeRegexp.exec(line);
  90327. // TODO. Support +Y and -X if needed.
  90328. if (!match || match.length < 3) {
  90329. throw "HDR Bad header format, no size";
  90330. }
  90331. width = parseInt(match[2]);
  90332. height = parseInt(match[1]);
  90333. if (width < 8 || width > 0x7fff) {
  90334. throw "HDR Bad header format, unsupported size";
  90335. }
  90336. lineIndex += (line.length + 1);
  90337. return {
  90338. height: height,
  90339. width: width,
  90340. dataPosition: lineIndex
  90341. };
  90342. };
  90343. /**
  90344. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  90345. * This RGBE texture needs to store the information as a panorama.
  90346. *
  90347. * More information on this format are available here:
  90348. * https://en.wikipedia.org/wiki/RGBE_image_format
  90349. *
  90350. * @param buffer The binary file stored in an array buffer.
  90351. * @param size The expected size of the extracted cubemap.
  90352. * @return The Cube Map information.
  90353. */
  90354. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  90355. var uint8array = new Uint8Array(buffer);
  90356. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  90357. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  90358. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  90359. return cubeMapData;
  90360. };
  90361. /**
  90362. * Returns the pixels data extracted from an RGBE texture.
  90363. * This pixels will be stored left to right up to down in the R G B order in one array.
  90364. *
  90365. * More information on this format are available here:
  90366. * https://en.wikipedia.org/wiki/RGBE_image_format
  90367. *
  90368. * @param uint8array The binary file stored in an array buffer.
  90369. * @param hdrInfo The header information of the file.
  90370. * @return The pixels data in RGB right to left up to down order.
  90371. */
  90372. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  90373. // Keep for multi format supports.
  90374. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  90375. };
  90376. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  90377. var num_scanlines = hdrInfo.height;
  90378. var scanline_width = hdrInfo.width;
  90379. var a, b, c, d, count;
  90380. var dataIndex = hdrInfo.dataPosition;
  90381. var index = 0, endIndex = 0, i = 0;
  90382. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  90383. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  90384. // 3 channels of 4 bytes per pixel in float.
  90385. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  90386. var resultArray = new Float32Array(resultBuffer);
  90387. // read in each successive scanline
  90388. while (num_scanlines > 0) {
  90389. a = uint8array[dataIndex++];
  90390. b = uint8array[dataIndex++];
  90391. c = uint8array[dataIndex++];
  90392. d = uint8array[dataIndex++];
  90393. if (a != 2 || b != 2 || (c & 0x80)) {
  90394. // this file is not run length encoded
  90395. throw "HDR Bad header format, not RLE";
  90396. }
  90397. if (((c << 8) | d) != scanline_width) {
  90398. throw "HDR Bad header format, wrong scan line width";
  90399. }
  90400. index = 0;
  90401. // read each of the four channels for the scanline into the buffer
  90402. for (i = 0; i < 4; i++) {
  90403. endIndex = (i + 1) * scanline_width;
  90404. while (index < endIndex) {
  90405. a = uint8array[dataIndex++];
  90406. b = uint8array[dataIndex++];
  90407. if (a > 128) {
  90408. // a run of the same value
  90409. count = a - 128;
  90410. if ((count == 0) || (count > endIndex - index)) {
  90411. throw "HDR Bad Format, bad scanline data (run)";
  90412. }
  90413. while (count-- > 0) {
  90414. scanLineArray[index++] = b;
  90415. }
  90416. }
  90417. else {
  90418. // a non-run
  90419. count = a;
  90420. if ((count == 0) || (count > endIndex - index)) {
  90421. throw "HDR Bad Format, bad scanline data (non-run)";
  90422. }
  90423. scanLineArray[index++] = b;
  90424. if (--count > 0) {
  90425. for (var j = 0; j < count; j++) {
  90426. scanLineArray[index++] = uint8array[dataIndex++];
  90427. }
  90428. }
  90429. }
  90430. }
  90431. }
  90432. // now convert data from buffer into floats
  90433. for (i = 0; i < scanline_width; i++) {
  90434. a = scanLineArray[i];
  90435. b = scanLineArray[i + scanline_width];
  90436. c = scanLineArray[i + 2 * scanline_width];
  90437. d = scanLineArray[i + 3 * scanline_width];
  90438. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  90439. }
  90440. num_scanlines--;
  90441. }
  90442. return resultArray;
  90443. };
  90444. return HDRTools;
  90445. }());
  90446. BABYLON.HDRTools = HDRTools;
  90447. })(BABYLON || (BABYLON = {}));
  90448. //# sourceMappingURL=babylon.hdr.js.map
  90449. var BABYLON;
  90450. (function (BABYLON) {
  90451. /**
  90452. * This represents a texture coming from an HDR input.
  90453. *
  90454. * The only supported format is currently panorama picture stored in RGBE format.
  90455. * Example of such files can be found on HDRLib: http://hdrlib.com/
  90456. */
  90457. var HDRCubeTexture = /** @class */ (function (_super) {
  90458. __extends(HDRCubeTexture, _super);
  90459. /**
  90460. * Instantiates an HDRTexture from the following parameters.
  90461. *
  90462. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  90463. * @param scene The scene the texture will be used in
  90464. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  90465. * @param noMipmap Forces to not generate the mipmap if true
  90466. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  90467. * @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)
  90468. * @param reserved Reserved flag for internal use.
  90469. */
  90470. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  90471. if (noMipmap === void 0) { noMipmap = false; }
  90472. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90473. if (gammaSpace === void 0) { gammaSpace = false; }
  90474. if (reserved === void 0) { reserved = false; }
  90475. if (onLoad === void 0) { onLoad = null; }
  90476. if (onError === void 0) { onError = null; }
  90477. var _this = _super.call(this, scene) || this;
  90478. _this._generateHarmonics = true;
  90479. _this._onLoad = null;
  90480. _this._onError = null;
  90481. /**
  90482. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  90483. */
  90484. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  90485. _this._isBlocking = true;
  90486. _this._rotationY = 0;
  90487. /**
  90488. * Gets or sets the center of the bounding box associated with the cube texture
  90489. * It must define where the camera used to render the texture was set
  90490. */
  90491. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  90492. if (!url) {
  90493. return _this;
  90494. }
  90495. _this.name = url;
  90496. _this.url = url;
  90497. _this.hasAlpha = false;
  90498. _this.isCube = true;
  90499. _this._textureMatrix = BABYLON.Matrix.Identity();
  90500. _this._onLoad = onLoad;
  90501. _this._onError = onError;
  90502. _this.gammaSpace = gammaSpace;
  90503. _this._noMipmap = noMipmap;
  90504. _this._size = size;
  90505. _this._texture = _this._getFromCache(url, _this._noMipmap);
  90506. if (!_this._texture) {
  90507. if (!scene.useDelayedTextureLoading) {
  90508. _this.loadTexture();
  90509. }
  90510. else {
  90511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  90512. }
  90513. }
  90514. return _this;
  90515. }
  90516. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  90517. /**
  90518. * Gets wether or not the texture is blocking during loading.
  90519. */
  90520. get: function () {
  90521. return this._isBlocking;
  90522. },
  90523. /**
  90524. * Sets wether or not the texture is blocking during loading.
  90525. */
  90526. set: function (value) {
  90527. this._isBlocking = value;
  90528. },
  90529. enumerable: true,
  90530. configurable: true
  90531. });
  90532. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  90533. /**
  90534. * Gets texture matrix rotation angle around Y axis radians.
  90535. */
  90536. get: function () {
  90537. return this._rotationY;
  90538. },
  90539. /**
  90540. * Sets texture matrix rotation angle around Y axis in radians.
  90541. */
  90542. set: function (value) {
  90543. this._rotationY = value;
  90544. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  90545. },
  90546. enumerable: true,
  90547. configurable: true
  90548. });
  90549. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  90550. get: function () {
  90551. return this._boundingBoxSize;
  90552. },
  90553. /**
  90554. * Gets or sets the size of the bounding box associated with the cube texture
  90555. * When defined, the cubemap will switch to local mode
  90556. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  90557. * @example https://www.babylonjs-playground.com/#RNASML
  90558. */
  90559. set: function (value) {
  90560. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  90561. return;
  90562. }
  90563. this._boundingBoxSize = value;
  90564. var scene = this.getScene();
  90565. if (scene) {
  90566. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  90567. }
  90568. },
  90569. enumerable: true,
  90570. configurable: true
  90571. });
  90572. /**
  90573. * Occurs when the file is raw .hdr file.
  90574. */
  90575. HDRCubeTexture.prototype.loadTexture = function () {
  90576. var _this = this;
  90577. var callback = function (buffer) {
  90578. _this.lodGenerationOffset = 0.0;
  90579. _this.lodGenerationScale = 0.8;
  90580. var scene = _this.getScene();
  90581. if (!scene) {
  90582. return null;
  90583. }
  90584. // Extract the raw linear data.
  90585. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  90586. // Generate harmonics if needed.
  90587. if (_this._generateHarmonics) {
  90588. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  90589. _this.sphericalPolynomial = sphericalPolynomial;
  90590. }
  90591. var results = [];
  90592. var byteArray = null;
  90593. // Push each faces.
  90594. for (var j = 0; j < 6; j++) {
  90595. // Create uintarray fallback.
  90596. if (!scene.getEngine().getCaps().textureFloat) {
  90597. // 3 channels of 1 bytes per pixel in bytes.
  90598. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  90599. byteArray = new Uint8Array(byteBuffer);
  90600. }
  90601. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  90602. // If special cases.
  90603. if (_this.gammaSpace || byteArray) {
  90604. for (var i = 0; i < _this._size * _this._size; i++) {
  90605. // Put in gamma space if requested.
  90606. if (_this.gammaSpace) {
  90607. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  90608. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  90609. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  90610. }
  90611. // Convert to int texture for fallback.
  90612. if (byteArray) {
  90613. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  90614. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  90615. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  90616. // May use luminance instead if the result is not accurate.
  90617. var max = Math.max(Math.max(r, g), b);
  90618. if (max > 255) {
  90619. var scale = 255 / max;
  90620. r *= scale;
  90621. g *= scale;
  90622. b *= scale;
  90623. }
  90624. byteArray[(i * 3) + 0] = r;
  90625. byteArray[(i * 3) + 1] = g;
  90626. byteArray[(i * 3) + 2] = b;
  90627. }
  90628. }
  90629. }
  90630. if (byteArray) {
  90631. results.push(byteArray);
  90632. }
  90633. else {
  90634. results.push(dataFace);
  90635. }
  90636. }
  90637. return results;
  90638. };
  90639. var scene = this.getScene();
  90640. if (scene) {
  90641. 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);
  90642. }
  90643. };
  90644. HDRCubeTexture.prototype.clone = function () {
  90645. var scene = this.getScene();
  90646. if (!scene) {
  90647. return this;
  90648. }
  90649. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  90650. // Base texture
  90651. newTexture.level = this.level;
  90652. newTexture.wrapU = this.wrapU;
  90653. newTexture.wrapV = this.wrapV;
  90654. newTexture.coordinatesIndex = this.coordinatesIndex;
  90655. newTexture.coordinatesMode = this.coordinatesMode;
  90656. return newTexture;
  90657. };
  90658. // Methods
  90659. HDRCubeTexture.prototype.delayLoad = function () {
  90660. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  90661. return;
  90662. }
  90663. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  90664. this._texture = this._getFromCache(this.url, this._noMipmap);
  90665. if (!this._texture) {
  90666. this.loadTexture();
  90667. }
  90668. };
  90669. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  90670. return this._textureMatrix;
  90671. };
  90672. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  90673. this._textureMatrix = value;
  90674. };
  90675. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  90676. var texture = null;
  90677. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  90678. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  90679. texture.name = parsedTexture.name;
  90680. texture.hasAlpha = parsedTexture.hasAlpha;
  90681. texture.level = parsedTexture.level;
  90682. texture.coordinatesMode = parsedTexture.coordinatesMode;
  90683. texture.isBlocking = parsedTexture.isBlocking;
  90684. }
  90685. if (texture) {
  90686. if (parsedTexture.boundingBoxPosition) {
  90687. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  90688. }
  90689. if (parsedTexture.boundingBoxSize) {
  90690. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  90691. }
  90692. if (parsedTexture.rotationY) {
  90693. texture.rotationY = parsedTexture.rotationY;
  90694. }
  90695. }
  90696. return texture;
  90697. };
  90698. HDRCubeTexture.prototype.serialize = function () {
  90699. if (!this.name) {
  90700. return null;
  90701. }
  90702. var serializationObject = {};
  90703. serializationObject.name = this.name;
  90704. serializationObject.hasAlpha = this.hasAlpha;
  90705. serializationObject.isCube = true;
  90706. serializationObject.level = this.level;
  90707. serializationObject.size = this._size;
  90708. serializationObject.coordinatesMode = this.coordinatesMode;
  90709. serializationObject.useInGammaSpace = this.gammaSpace;
  90710. serializationObject.generateHarmonics = this._generateHarmonics;
  90711. serializationObject.customType = "BABYLON.HDRCubeTexture";
  90712. serializationObject.noMipmap = this._noMipmap;
  90713. serializationObject.isBlocking = this._isBlocking;
  90714. serializationObject.rotationY = this._rotationY;
  90715. return serializationObject;
  90716. };
  90717. HDRCubeTexture._facesMapping = [
  90718. "right",
  90719. "left",
  90720. "up",
  90721. "down",
  90722. "front",
  90723. "back"
  90724. ];
  90725. return HDRCubeTexture;
  90726. }(BABYLON.BaseTexture));
  90727. BABYLON.HDRCubeTexture = HDRCubeTexture;
  90728. })(BABYLON || (BABYLON = {}));
  90729. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  90730. var BABYLON;
  90731. (function (BABYLON) {
  90732. /**
  90733. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  90734. */
  90735. var PanoramaToCubeMapTools = /** @class */ (function () {
  90736. function PanoramaToCubeMapTools() {
  90737. }
  90738. /**
  90739. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  90740. *
  90741. * @param float32Array The source data.
  90742. * @param inputWidth The width of the input panorama.
  90743. * @param inputhHeight The height of the input panorama.
  90744. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  90745. * @return The cubemap data
  90746. */
  90747. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  90748. if (!float32Array) {
  90749. throw "ConvertPanoramaToCubemap: input cannot be null";
  90750. }
  90751. if (float32Array.length != inputWidth * inputHeight * 3) {
  90752. throw "ConvertPanoramaToCubemap: input size is wrong";
  90753. }
  90754. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  90755. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  90756. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  90757. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  90758. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  90759. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  90760. return {
  90761. front: textureFront,
  90762. back: textureBack,
  90763. left: textureLeft,
  90764. right: textureRight,
  90765. up: textureUp,
  90766. down: textureDown,
  90767. size: size,
  90768. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90769. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  90770. gammaSpace: false,
  90771. };
  90772. };
  90773. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  90774. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  90775. var textureArray = new Float32Array(buffer);
  90776. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  90777. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  90778. var dy = 1 / texSize;
  90779. var fy = 0;
  90780. for (var y = 0; y < texSize; y++) {
  90781. var xv1 = faceData[0];
  90782. var xv2 = faceData[2];
  90783. for (var x = 0; x < texSize; x++) {
  90784. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  90785. v.normalize();
  90786. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  90787. // 3 channels per pixels
  90788. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  90789. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  90790. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  90791. xv1 = xv1.add(rotDX1);
  90792. xv2 = xv2.add(rotDX2);
  90793. }
  90794. fy += dy;
  90795. }
  90796. return textureArray;
  90797. };
  90798. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  90799. var theta = Math.atan2(vDir.z, vDir.x);
  90800. var phi = Math.acos(vDir.y);
  90801. while (theta < -Math.PI)
  90802. theta += 2 * Math.PI;
  90803. while (theta > Math.PI)
  90804. theta -= 2 * Math.PI;
  90805. var dx = theta / Math.PI;
  90806. var dy = phi / Math.PI;
  90807. // recenter.
  90808. dx = dx * 0.5 + 0.5;
  90809. var px = Math.round(dx * inputWidth);
  90810. if (px < 0)
  90811. px = 0;
  90812. else if (px >= inputWidth)
  90813. px = inputWidth - 1;
  90814. var py = Math.round(dy * inputHeight);
  90815. if (py < 0)
  90816. py = 0;
  90817. else if (py >= inputHeight)
  90818. py = inputHeight - 1;
  90819. var inputY = (inputHeight - py - 1);
  90820. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  90821. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  90822. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  90823. return {
  90824. r: r,
  90825. g: g,
  90826. b: b
  90827. };
  90828. };
  90829. PanoramaToCubeMapTools.FACE_FRONT = [
  90830. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90831. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90832. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90833. new BABYLON.Vector3(1.0, 1.0, -1.0)
  90834. ];
  90835. PanoramaToCubeMapTools.FACE_BACK = [
  90836. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90837. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90838. new BABYLON.Vector3(1.0, 1.0, 1.0),
  90839. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  90840. ];
  90841. PanoramaToCubeMapTools.FACE_RIGHT = [
  90842. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90843. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90844. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90845. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90846. ];
  90847. PanoramaToCubeMapTools.FACE_LEFT = [
  90848. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90849. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90850. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90851. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  90852. ];
  90853. PanoramaToCubeMapTools.FACE_DOWN = [
  90854. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90855. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90856. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90857. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90858. ];
  90859. PanoramaToCubeMapTools.FACE_UP = [
  90860. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90861. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90862. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90863. new BABYLON.Vector3(1.0, -1.0, -1.0)
  90864. ];
  90865. return PanoramaToCubeMapTools;
  90866. }());
  90867. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  90868. })(BABYLON || (BABYLON = {}));
  90869. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  90870. var BABYLON;
  90871. (function (BABYLON) {
  90872. var IndexedVector2 = /** @class */ (function (_super) {
  90873. __extends(IndexedVector2, _super);
  90874. function IndexedVector2(original, index) {
  90875. var _this = _super.call(this, original.x, original.y) || this;
  90876. _this.index = index;
  90877. return _this;
  90878. }
  90879. return IndexedVector2;
  90880. }(BABYLON.Vector2));
  90881. var PolygonPoints = /** @class */ (function () {
  90882. function PolygonPoints() {
  90883. this.elements = new Array();
  90884. }
  90885. PolygonPoints.prototype.add = function (originalPoints) {
  90886. var _this = this;
  90887. var result = new Array();
  90888. originalPoints.forEach(function (point) {
  90889. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  90890. var newPoint = new IndexedVector2(point, _this.elements.length);
  90891. result.push(newPoint);
  90892. _this.elements.push(newPoint);
  90893. }
  90894. });
  90895. return result;
  90896. };
  90897. PolygonPoints.prototype.computeBounds = function () {
  90898. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90899. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90900. this.elements.forEach(function (point) {
  90901. // x
  90902. if (point.x < lmin.x) {
  90903. lmin.x = point.x;
  90904. }
  90905. else if (point.x > lmax.x) {
  90906. lmax.x = point.x;
  90907. }
  90908. // y
  90909. if (point.y < lmin.y) {
  90910. lmin.y = point.y;
  90911. }
  90912. else if (point.y > lmax.y) {
  90913. lmax.y = point.y;
  90914. }
  90915. });
  90916. return {
  90917. min: lmin,
  90918. max: lmax,
  90919. width: lmax.x - lmin.x,
  90920. height: lmax.y - lmin.y
  90921. };
  90922. };
  90923. return PolygonPoints;
  90924. }());
  90925. var Polygon = /** @class */ (function () {
  90926. function Polygon() {
  90927. }
  90928. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  90929. return [
  90930. new BABYLON.Vector2(xmin, ymin),
  90931. new BABYLON.Vector2(xmax, ymin),
  90932. new BABYLON.Vector2(xmax, ymax),
  90933. new BABYLON.Vector2(xmin, ymax)
  90934. ];
  90935. };
  90936. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  90937. if (cx === void 0) { cx = 0; }
  90938. if (cy === void 0) { cy = 0; }
  90939. if (numberOfSides === void 0) { numberOfSides = 32; }
  90940. var result = new Array();
  90941. var angle = 0;
  90942. var increment = (Math.PI * 2) / numberOfSides;
  90943. for (var i = 0; i < numberOfSides; i++) {
  90944. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  90945. angle -= increment;
  90946. }
  90947. return result;
  90948. };
  90949. Polygon.Parse = function (input) {
  90950. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  90951. var i, result = [];
  90952. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  90953. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  90954. }
  90955. return result;
  90956. };
  90957. Polygon.StartingAt = function (x, y) {
  90958. return BABYLON.Path2.StartingAt(x, y);
  90959. };
  90960. return Polygon;
  90961. }());
  90962. BABYLON.Polygon = Polygon;
  90963. var PolygonMeshBuilder = /** @class */ (function () {
  90964. function PolygonMeshBuilder(name, contours, scene) {
  90965. this._points = new PolygonPoints();
  90966. this._outlinepoints = new PolygonPoints();
  90967. this._holes = new Array();
  90968. this._epoints = new Array();
  90969. this._eholes = new Array();
  90970. this._name = name;
  90971. this._scene = scene;
  90972. var points;
  90973. if (contours instanceof BABYLON.Path2) {
  90974. points = contours.getPoints();
  90975. }
  90976. else {
  90977. points = contours;
  90978. }
  90979. this._addToepoint(points);
  90980. this._points.add(points);
  90981. this._outlinepoints.add(points);
  90982. if (typeof earcut === 'undefined') {
  90983. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  90984. }
  90985. }
  90986. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  90987. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  90988. var p = points_1[_i];
  90989. this._epoints.push(p.x, p.y);
  90990. }
  90991. };
  90992. PolygonMeshBuilder.prototype.addHole = function (hole) {
  90993. this._points.add(hole);
  90994. var holepoints = new PolygonPoints();
  90995. holepoints.add(hole);
  90996. this._holes.push(holepoints);
  90997. this._eholes.push(this._epoints.length / 2);
  90998. this._addToepoint(hole);
  90999. return this;
  91000. };
  91001. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  91002. var _this = this;
  91003. if (updatable === void 0) { updatable = false; }
  91004. if (depth === void 0) { depth = 0; }
  91005. var result = new BABYLON.Mesh(this._name, this._scene);
  91006. var normals = new Array();
  91007. var positions = new Array();
  91008. var uvs = new Array();
  91009. var bounds = this._points.computeBounds();
  91010. this._points.elements.forEach(function (p) {
  91011. normals.push(0, 1.0, 0);
  91012. positions.push(p.x, 0, p.y);
  91013. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  91014. });
  91015. var indices = new Array();
  91016. var res = earcut(this._epoints, this._eholes, 2);
  91017. for (var i = 0; i < res.length; i++) {
  91018. indices.push(res[i]);
  91019. }
  91020. if (depth > 0) {
  91021. var positionscount = (positions.length / 3); //get the current pointcount
  91022. this._points.elements.forEach(function (p) {
  91023. normals.push(0, -1.0, 0);
  91024. positions.push(p.x, -depth, p.y);
  91025. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  91026. });
  91027. var totalCount = indices.length;
  91028. for (var i = 0; i < totalCount; i += 3) {
  91029. var i0 = indices[i + 0];
  91030. var i1 = indices[i + 1];
  91031. var i2 = indices[i + 2];
  91032. indices.push(i2 + positionscount);
  91033. indices.push(i1 + positionscount);
  91034. indices.push(i0 + positionscount);
  91035. }
  91036. //Add the sides
  91037. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91038. this._holes.forEach(function (hole) {
  91039. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91040. });
  91041. }
  91042. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91043. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91044. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91045. result.setIndices(indices);
  91046. return result;
  91047. };
  91048. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91049. var StartIndex = positions.length / 3;
  91050. var ulength = 0;
  91051. for (var i = 0; i < points.elements.length; i++) {
  91052. var p = points.elements[i];
  91053. var p1;
  91054. if ((i + 1) > points.elements.length - 1) {
  91055. p1 = points.elements[0];
  91056. }
  91057. else {
  91058. p1 = points.elements[i + 1];
  91059. }
  91060. positions.push(p.x, 0, p.y);
  91061. positions.push(p.x, -depth, p.y);
  91062. positions.push(p1.x, 0, p1.y);
  91063. positions.push(p1.x, -depth, p1.y);
  91064. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91065. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91066. var v3 = v2.subtract(v1);
  91067. var v4 = new BABYLON.Vector3(0, 1, 0);
  91068. var vn = BABYLON.Vector3.Cross(v3, v4);
  91069. vn = vn.normalize();
  91070. uvs.push(ulength / bounds.width, 0);
  91071. uvs.push(ulength / bounds.width, 1);
  91072. ulength += v3.length();
  91073. uvs.push((ulength / bounds.width), 0);
  91074. uvs.push((ulength / bounds.width), 1);
  91075. if (!flip) {
  91076. normals.push(-vn.x, -vn.y, -vn.z);
  91077. normals.push(-vn.x, -vn.y, -vn.z);
  91078. normals.push(-vn.x, -vn.y, -vn.z);
  91079. normals.push(-vn.x, -vn.y, -vn.z);
  91080. indices.push(StartIndex);
  91081. indices.push(StartIndex + 1);
  91082. indices.push(StartIndex + 2);
  91083. indices.push(StartIndex + 1);
  91084. indices.push(StartIndex + 3);
  91085. indices.push(StartIndex + 2);
  91086. }
  91087. else {
  91088. normals.push(vn.x, vn.y, vn.z);
  91089. normals.push(vn.x, vn.y, vn.z);
  91090. normals.push(vn.x, vn.y, vn.z);
  91091. normals.push(vn.x, vn.y, vn.z);
  91092. indices.push(StartIndex);
  91093. indices.push(StartIndex + 2);
  91094. indices.push(StartIndex + 1);
  91095. indices.push(StartIndex + 1);
  91096. indices.push(StartIndex + 2);
  91097. indices.push(StartIndex + 3);
  91098. }
  91099. StartIndex += 4;
  91100. }
  91101. ;
  91102. };
  91103. return PolygonMeshBuilder;
  91104. }());
  91105. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91106. })(BABYLON || (BABYLON = {}));
  91107. //# sourceMappingURL=babylon.polygonMesh.js.map
  91108. var BABYLON;
  91109. (function (BABYLON) {
  91110. /**
  91111. * Unique ID when we import meshes from Babylon to CSG
  91112. */
  91113. var currentCSGMeshId = 0;
  91114. /**
  91115. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91116. * one to provide additional features like texture coordinates and vertex
  91117. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91118. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91119. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91120. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91121. * is not used anywhere else.
  91122. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91123. */
  91124. var Vertex = /** @class */ (function () {
  91125. /**
  91126. * Initializes the vertex
  91127. * @param pos The position of the vertex
  91128. * @param normal The normal of the vertex
  91129. * @param uv The texture coordinate of the vertex
  91130. */
  91131. function Vertex(
  91132. /**
  91133. * The position of the vertex
  91134. */
  91135. pos,
  91136. /**
  91137. * The normal of the vertex
  91138. */
  91139. normal,
  91140. /**
  91141. * The texture coordinate of the vertex
  91142. */
  91143. uv) {
  91144. this.pos = pos;
  91145. this.normal = normal;
  91146. this.uv = uv;
  91147. }
  91148. /**
  91149. * Make a clone, or deep copy, of the vertex
  91150. * @returns A new Vertex
  91151. */
  91152. Vertex.prototype.clone = function () {
  91153. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91154. };
  91155. /**
  91156. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91157. * orientation of a polygon is flipped.
  91158. */
  91159. Vertex.prototype.flip = function () {
  91160. this.normal = this.normal.scale(-1);
  91161. };
  91162. /**
  91163. * Create a new vertex between this vertex and `other` by linearly
  91164. * interpolating all properties using a parameter of `t`. Subclasses should
  91165. * override this to interpolate additional properties.
  91166. * @param other the vertex to interpolate against
  91167. * @param t The factor used to linearly interpolate between the vertices
  91168. */
  91169. Vertex.prototype.interpolate = function (other, t) {
  91170. 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));
  91171. };
  91172. return Vertex;
  91173. }());
  91174. /**
  91175. * Represents a plane in 3D space.
  91176. */
  91177. var Plane = /** @class */ (function () {
  91178. /**
  91179. * Initializes the plane
  91180. * @param normal The normal for the plane
  91181. * @param w
  91182. */
  91183. function Plane(normal, w) {
  91184. this.normal = normal;
  91185. this.w = w;
  91186. }
  91187. /**
  91188. * Construct a plane from three points
  91189. * @param a Point a
  91190. * @param b Point b
  91191. * @param c Point c
  91192. */
  91193. Plane.FromPoints = function (a, b, c) {
  91194. var v0 = c.subtract(a);
  91195. var v1 = b.subtract(a);
  91196. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  91197. return null;
  91198. }
  91199. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  91200. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  91201. };
  91202. /**
  91203. * Clone, or make a deep copy of the plane
  91204. * @returns a new Plane
  91205. */
  91206. Plane.prototype.clone = function () {
  91207. return new Plane(this.normal.clone(), this.w);
  91208. };
  91209. /**
  91210. * Flip the face of the plane
  91211. */
  91212. Plane.prototype.flip = function () {
  91213. this.normal.scaleInPlace(-1);
  91214. this.w = -this.w;
  91215. };
  91216. /**
  91217. * Split `polygon` by this plane if needed, then put the polygon or polygon
  91218. * fragments in the appropriate lists. Coplanar polygons go into either
  91219. `* coplanarFront` or `coplanarBack` depending on their orientation with
  91220. * respect to this plane. Polygons in front or in back of this plane go into
  91221. * either `front` or `back`
  91222. * @param polygon The polygon to be split
  91223. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  91224. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  91225. * @param front Will contain the polygons in front of the plane
  91226. * @param back Will contain the polygons begind the plane
  91227. */
  91228. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  91229. var COPLANAR = 0;
  91230. var FRONT = 1;
  91231. var BACK = 2;
  91232. var SPANNING = 3;
  91233. // Classify each point as well as the entire polygon into one of the above
  91234. // four classes.
  91235. var polygonType = 0;
  91236. var types = [];
  91237. var i;
  91238. var t;
  91239. for (i = 0; i < polygon.vertices.length; i++) {
  91240. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  91241. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  91242. polygonType |= type;
  91243. types.push(type);
  91244. }
  91245. // Put the polygon in the correct list, splitting it when necessary
  91246. switch (polygonType) {
  91247. case COPLANAR:
  91248. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  91249. break;
  91250. case FRONT:
  91251. front.push(polygon);
  91252. break;
  91253. case BACK:
  91254. back.push(polygon);
  91255. break;
  91256. case SPANNING:
  91257. var f = [], b = [];
  91258. for (i = 0; i < polygon.vertices.length; i++) {
  91259. var j = (i + 1) % polygon.vertices.length;
  91260. var ti = types[i], tj = types[j];
  91261. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  91262. if (ti !== BACK)
  91263. f.push(vi);
  91264. if (ti !== FRONT)
  91265. b.push(ti !== BACK ? vi.clone() : vi);
  91266. if ((ti | tj) === SPANNING) {
  91267. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  91268. var v = vi.interpolate(vj, t);
  91269. f.push(v);
  91270. b.push(v.clone());
  91271. }
  91272. }
  91273. var poly;
  91274. if (f.length >= 3) {
  91275. poly = new Polygon(f, polygon.shared);
  91276. if (poly.plane)
  91277. front.push(poly);
  91278. }
  91279. if (b.length >= 3) {
  91280. poly = new Polygon(b, polygon.shared);
  91281. if (poly.plane)
  91282. back.push(poly);
  91283. }
  91284. break;
  91285. }
  91286. };
  91287. /**
  91288. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  91289. * point is on the plane
  91290. */
  91291. Plane.EPSILON = 1e-5;
  91292. return Plane;
  91293. }());
  91294. /**
  91295. * Represents a convex polygon. The vertices used to initialize a polygon must
  91296. * be coplanar and form a convex loop.
  91297. *
  91298. * Each convex polygon has a `shared` property, which is shared between all
  91299. * polygons that are clones of each other or were split from the same polygon.
  91300. * This can be used to define per-polygon properties (such as surface color)
  91301. */
  91302. var Polygon = /** @class */ (function () {
  91303. /**
  91304. * Initializes the polygon
  91305. * @param vertices The vertices of the polygon
  91306. * @param shared The properties shared across all polygons
  91307. */
  91308. function Polygon(vertices, shared) {
  91309. this.vertices = vertices;
  91310. this.shared = shared;
  91311. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  91312. }
  91313. /**
  91314. * Clones, or makes a deep copy, or the polygon
  91315. */
  91316. Polygon.prototype.clone = function () {
  91317. var vertices = this.vertices.map(function (v) { return v.clone(); });
  91318. return new Polygon(vertices, this.shared);
  91319. };
  91320. /**
  91321. * Flips the faces of the polygon
  91322. */
  91323. Polygon.prototype.flip = function () {
  91324. this.vertices.reverse().map(function (v) { v.flip(); });
  91325. this.plane.flip();
  91326. };
  91327. return Polygon;
  91328. }());
  91329. /**
  91330. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  91331. * by picking a polygon to split along. That polygon (and all other coplanar
  91332. * polygons) are added directly to that node and the other polygons are added to
  91333. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  91334. * no distinction between internal and leaf nodes
  91335. */
  91336. var Node = /** @class */ (function () {
  91337. /**
  91338. * Initializes the node
  91339. * @param polygons A collection of polygons held in the node
  91340. */
  91341. function Node(polygons) {
  91342. this.plane = null;
  91343. this.front = null;
  91344. this.back = null;
  91345. this.polygons = new Array();
  91346. if (polygons) {
  91347. this.build(polygons);
  91348. }
  91349. }
  91350. /**
  91351. * Clones, or makes a deep copy, of the node
  91352. * @returns The cloned node
  91353. */
  91354. Node.prototype.clone = function () {
  91355. var node = new Node();
  91356. node.plane = this.plane && this.plane.clone();
  91357. node.front = this.front && this.front.clone();
  91358. node.back = this.back && this.back.clone();
  91359. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  91360. return node;
  91361. };
  91362. /**
  91363. * Convert solid space to empty space and empty space to solid space
  91364. */
  91365. Node.prototype.invert = function () {
  91366. for (var i = 0; i < this.polygons.length; i++) {
  91367. this.polygons[i].flip();
  91368. }
  91369. if (this.plane) {
  91370. this.plane.flip();
  91371. }
  91372. if (this.front) {
  91373. this.front.invert();
  91374. }
  91375. if (this.back) {
  91376. this.back.invert();
  91377. }
  91378. var temp = this.front;
  91379. this.front = this.back;
  91380. this.back = temp;
  91381. };
  91382. /**
  91383. * Recursively remove all polygons in `polygons` that are inside this BSP
  91384. * tree.
  91385. * @param polygons Polygons to remove from the BSP
  91386. * @returns Polygons clipped from the BSP
  91387. */
  91388. Node.prototype.clipPolygons = function (polygons) {
  91389. if (!this.plane)
  91390. return polygons.slice();
  91391. var front = new Array(), back = new Array();
  91392. for (var i = 0; i < polygons.length; i++) {
  91393. this.plane.splitPolygon(polygons[i], front, back, front, back);
  91394. }
  91395. if (this.front) {
  91396. front = this.front.clipPolygons(front);
  91397. }
  91398. if (this.back) {
  91399. back = this.back.clipPolygons(back);
  91400. }
  91401. else {
  91402. back = [];
  91403. }
  91404. return front.concat(back);
  91405. };
  91406. /**
  91407. * Remove all polygons in this BSP tree that are inside the other BSP tree
  91408. * `bsp`.
  91409. * @param bsp BSP containing polygons to remove from this BSP
  91410. */
  91411. Node.prototype.clipTo = function (bsp) {
  91412. this.polygons = bsp.clipPolygons(this.polygons);
  91413. if (this.front)
  91414. this.front.clipTo(bsp);
  91415. if (this.back)
  91416. this.back.clipTo(bsp);
  91417. };
  91418. /**
  91419. * Return a list of all polygons in this BSP tree
  91420. * @returns List of all polygons in this BSP tree
  91421. */
  91422. Node.prototype.allPolygons = function () {
  91423. var polygons = this.polygons.slice();
  91424. if (this.front)
  91425. polygons = polygons.concat(this.front.allPolygons());
  91426. if (this.back)
  91427. polygons = polygons.concat(this.back.allPolygons());
  91428. return polygons;
  91429. };
  91430. /**
  91431. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  91432. * new polygons are filtered down to the bottom of the tree and become new
  91433. * nodes there. Each set of polygons is partitioned using the first polygon
  91434. * (no heuristic is used to pick a good split)
  91435. * @param polygons Polygons used to construct the BSP tree
  91436. */
  91437. Node.prototype.build = function (polygons) {
  91438. if (!polygons.length)
  91439. return;
  91440. if (!this.plane)
  91441. this.plane = polygons[0].plane.clone();
  91442. var front = new Array(), back = new Array();
  91443. for (var i = 0; i < polygons.length; i++) {
  91444. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  91445. }
  91446. if (front.length) {
  91447. if (!this.front)
  91448. this.front = new Node();
  91449. this.front.build(front);
  91450. }
  91451. if (back.length) {
  91452. if (!this.back)
  91453. this.back = new Node();
  91454. this.back.build(back);
  91455. }
  91456. };
  91457. return Node;
  91458. }());
  91459. /**
  91460. * Class for building Constructive Solid Geometry
  91461. */
  91462. var CSG = /** @class */ (function () {
  91463. function CSG() {
  91464. this.polygons = new Array();
  91465. }
  91466. /**
  91467. * Convert the BABYLON.Mesh to BABYLON.CSG
  91468. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  91469. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  91470. */
  91471. CSG.FromMesh = function (mesh) {
  91472. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  91473. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  91474. if (mesh instanceof BABYLON.Mesh) {
  91475. mesh.computeWorldMatrix(true);
  91476. matrix = mesh.getWorldMatrix();
  91477. meshPosition = mesh.position.clone();
  91478. meshRotation = mesh.rotation.clone();
  91479. if (mesh.rotationQuaternion) {
  91480. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  91481. }
  91482. meshScaling = mesh.scaling.clone();
  91483. }
  91484. else {
  91485. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  91486. }
  91487. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91488. var subMeshes = mesh.subMeshes;
  91489. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  91490. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  91491. vertices = [];
  91492. for (var j = 0; j < 3; j++) {
  91493. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  91494. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  91495. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  91496. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  91497. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  91498. vertex = new Vertex(position, normal, uv);
  91499. vertices.push(vertex);
  91500. }
  91501. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  91502. // To handle the case of degenerated triangle
  91503. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  91504. if (polygon.plane)
  91505. polygons.push(polygon);
  91506. }
  91507. }
  91508. var csg = CSG.FromPolygons(polygons);
  91509. csg.matrix = matrix;
  91510. csg.position = meshPosition;
  91511. csg.rotation = meshRotation;
  91512. csg.scaling = meshScaling;
  91513. csg.rotationQuaternion = meshRotationQuaternion;
  91514. currentCSGMeshId++;
  91515. return csg;
  91516. };
  91517. /**
  91518. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  91519. * @param polygons Polygons used to construct a BABYLON.CSG solid
  91520. */
  91521. CSG.FromPolygons = function (polygons) {
  91522. var csg = new CSG();
  91523. csg.polygons = polygons;
  91524. return csg;
  91525. };
  91526. /**
  91527. * Clones, or makes a deep copy, of the BABYLON.CSG
  91528. * @returns A new BABYLON.CSG
  91529. */
  91530. CSG.prototype.clone = function () {
  91531. var csg = new CSG();
  91532. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  91533. csg.copyTransformAttributes(this);
  91534. return csg;
  91535. };
  91536. /**
  91537. * Unions this CSG with another CSG
  91538. * @param csg The CSG to union against this CSG
  91539. * @returns The unioned CSG
  91540. */
  91541. CSG.prototype.union = function (csg) {
  91542. var a = new Node(this.clone().polygons);
  91543. var b = new Node(csg.clone().polygons);
  91544. a.clipTo(b);
  91545. b.clipTo(a);
  91546. b.invert();
  91547. b.clipTo(a);
  91548. b.invert();
  91549. a.build(b.allPolygons());
  91550. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91551. };
  91552. /**
  91553. * Unions this CSG with another CSG in place
  91554. * @param csg The CSG to union against this CSG
  91555. */
  91556. CSG.prototype.unionInPlace = function (csg) {
  91557. var a = new Node(this.polygons);
  91558. var b = new Node(csg.polygons);
  91559. a.clipTo(b);
  91560. b.clipTo(a);
  91561. b.invert();
  91562. b.clipTo(a);
  91563. b.invert();
  91564. a.build(b.allPolygons());
  91565. this.polygons = a.allPolygons();
  91566. };
  91567. /**
  91568. * Subtracts this CSG with another CSG
  91569. * @param csg The CSG to subtract against this CSG
  91570. * @returns A new BABYLON.CSG
  91571. */
  91572. CSG.prototype.subtract = function (csg) {
  91573. var a = new Node(this.clone().polygons);
  91574. var b = new Node(csg.clone().polygons);
  91575. a.invert();
  91576. a.clipTo(b);
  91577. b.clipTo(a);
  91578. b.invert();
  91579. b.clipTo(a);
  91580. b.invert();
  91581. a.build(b.allPolygons());
  91582. a.invert();
  91583. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91584. };
  91585. /**
  91586. * Subtracts this CSG with another CSG in place
  91587. * @param csg The CSG to subtact against this CSG
  91588. */
  91589. CSG.prototype.subtractInPlace = function (csg) {
  91590. var a = new Node(this.polygons);
  91591. var b = new Node(csg.polygons);
  91592. a.invert();
  91593. a.clipTo(b);
  91594. b.clipTo(a);
  91595. b.invert();
  91596. b.clipTo(a);
  91597. b.invert();
  91598. a.build(b.allPolygons());
  91599. a.invert();
  91600. this.polygons = a.allPolygons();
  91601. };
  91602. /**
  91603. * Intersect this CSG with another CSG
  91604. * @param csg The CSG to intersect against this CSG
  91605. * @returns A new BABYLON.CSG
  91606. */
  91607. CSG.prototype.intersect = function (csg) {
  91608. var a = new Node(this.clone().polygons);
  91609. var b = new Node(csg.clone().polygons);
  91610. a.invert();
  91611. b.clipTo(a);
  91612. b.invert();
  91613. a.clipTo(b);
  91614. b.clipTo(a);
  91615. a.build(b.allPolygons());
  91616. a.invert();
  91617. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91618. };
  91619. /**
  91620. * Intersects this CSG with another CSG in place
  91621. * @param csg The CSG to intersect against this CSG
  91622. */
  91623. CSG.prototype.intersectInPlace = function (csg) {
  91624. var a = new Node(this.polygons);
  91625. var b = new Node(csg.polygons);
  91626. a.invert();
  91627. b.clipTo(a);
  91628. b.invert();
  91629. a.clipTo(b);
  91630. b.clipTo(a);
  91631. a.build(b.allPolygons());
  91632. a.invert();
  91633. this.polygons = a.allPolygons();
  91634. };
  91635. /**
  91636. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  91637. * not modified.
  91638. * @returns A new BABYLON.CSG solid with solid and empty space switched
  91639. */
  91640. CSG.prototype.inverse = function () {
  91641. var csg = this.clone();
  91642. csg.inverseInPlace();
  91643. return csg;
  91644. };
  91645. /**
  91646. * Inverses the BABYLON.CSG in place
  91647. */
  91648. CSG.prototype.inverseInPlace = function () {
  91649. this.polygons.map(function (p) { p.flip(); });
  91650. };
  91651. /**
  91652. * This is used to keep meshes transformations so they can be restored
  91653. * when we build back a Babylon Mesh
  91654. * NB : All CSG operations are performed in world coordinates
  91655. * @param csg The BABYLON.CSG to copy the transform attributes from
  91656. * @returns This BABYLON.CSG
  91657. */
  91658. CSG.prototype.copyTransformAttributes = function (csg) {
  91659. this.matrix = csg.matrix;
  91660. this.position = csg.position;
  91661. this.rotation = csg.rotation;
  91662. this.scaling = csg.scaling;
  91663. this.rotationQuaternion = csg.rotationQuaternion;
  91664. return this;
  91665. };
  91666. /**
  91667. * Build Raw mesh from CSG
  91668. * Coordinates here are in world space
  91669. * @param name The name of the mesh geometry
  91670. * @param scene The BABYLON.Scene
  91671. * @param keepSubMeshes Specifies if the submeshes should be kept
  91672. * @returns A new BABYLON.Mesh
  91673. */
  91674. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  91675. var matrix = this.matrix.clone();
  91676. matrix.invert();
  91677. 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;
  91678. if (keepSubMeshes) {
  91679. // Sort Polygons, since subMeshes are indices range
  91680. polygons.sort(function (a, b) {
  91681. if (a.shared.meshId === b.shared.meshId) {
  91682. return a.shared.subMeshId - b.shared.subMeshId;
  91683. }
  91684. else {
  91685. return a.shared.meshId - b.shared.meshId;
  91686. }
  91687. });
  91688. }
  91689. for (var i = 0, il = polygons.length; i < il; i++) {
  91690. polygon = polygons[i];
  91691. // Building SubMeshes
  91692. if (!subMesh_dict[polygon.shared.meshId]) {
  91693. subMesh_dict[polygon.shared.meshId] = {};
  91694. }
  91695. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  91696. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  91697. indexStart: +Infinity,
  91698. indexEnd: -Infinity,
  91699. materialIndex: polygon.shared.materialIndex
  91700. };
  91701. }
  91702. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  91703. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  91704. polygonIndices[0] = 0;
  91705. polygonIndices[1] = j - 1;
  91706. polygonIndices[2] = j;
  91707. for (var k = 0; k < 3; k++) {
  91708. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  91709. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  91710. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  91711. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  91712. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  91713. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  91714. // Check if 2 points can be merged
  91715. if (!(typeof vertex_idx !== 'undefined' &&
  91716. normals[vertex_idx * 3] === localNormal.x &&
  91717. normals[vertex_idx * 3 + 1] === localNormal.y &&
  91718. normals[vertex_idx * 3 + 2] === localNormal.z &&
  91719. uvs[vertex_idx * 2] === uv.x &&
  91720. uvs[vertex_idx * 2 + 1] === uv.y)) {
  91721. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  91722. uvs.push(uv.x, uv.y);
  91723. normals.push(normal.x, normal.y, normal.z);
  91724. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  91725. }
  91726. indices.push(vertex_idx);
  91727. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  91728. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  91729. currentIndex++;
  91730. }
  91731. }
  91732. }
  91733. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  91734. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  91735. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  91736. mesh.setIndices(indices, null);
  91737. if (keepSubMeshes) {
  91738. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  91739. var materialIndexOffset = 0, materialMaxIndex;
  91740. mesh.subMeshes = new Array();
  91741. for (var m in subMesh_dict) {
  91742. materialMaxIndex = -1;
  91743. for (var sm in subMesh_dict[m]) {
  91744. subMesh_obj = subMesh_dict[m][sm];
  91745. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  91746. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  91747. }
  91748. materialIndexOffset += ++materialMaxIndex;
  91749. }
  91750. }
  91751. return mesh;
  91752. };
  91753. /**
  91754. * Build Mesh from CSG taking material and transforms into account
  91755. * @param name The name of the BABYLON.Mesh
  91756. * @param material The material of the BABYLON.Mesh
  91757. * @param scene The BABYLON.Scene
  91758. * @param keepSubMeshes Specifies if submeshes should be kept
  91759. * @returns The new BABYLON.Mesh
  91760. */
  91761. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  91762. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  91763. mesh.material = material;
  91764. mesh.position.copyFrom(this.position);
  91765. mesh.rotation.copyFrom(this.rotation);
  91766. if (this.rotationQuaternion) {
  91767. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  91768. }
  91769. mesh.scaling.copyFrom(this.scaling);
  91770. mesh.computeWorldMatrix(true);
  91771. return mesh;
  91772. };
  91773. return CSG;
  91774. }());
  91775. BABYLON.CSG = CSG;
  91776. })(BABYLON || (BABYLON = {}));
  91777. //# sourceMappingURL=babylon.csg.js.map
  91778. var BABYLON;
  91779. (function (BABYLON) {
  91780. /**
  91781. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91782. * It controls one of the indiviual texture used in the effect.
  91783. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91784. */
  91785. var LensFlare = /** @class */ (function () {
  91786. /**
  91787. * Instantiates a new Lens Flare.
  91788. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91789. * It controls one of the indiviual texture used in the effect.
  91790. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91791. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  91792. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  91793. * @param color Define the lens color
  91794. * @param imgUrl Define the lens texture url
  91795. * @param system Define the `lensFlareSystem` this flare is part of
  91796. */
  91797. function LensFlare(
  91798. /**
  91799. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  91800. */
  91801. size,
  91802. /**
  91803. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  91804. */
  91805. position, color, imgUrl, system) {
  91806. this.size = size;
  91807. this.position = position;
  91808. /**
  91809. * Define the alpha mode to render this particular lens.
  91810. */
  91811. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91812. this.color = color || new BABYLON.Color3(1, 1, 1);
  91813. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  91814. this._system = system;
  91815. system.lensFlares.push(this);
  91816. }
  91817. /**
  91818. * Creates a new Lens Flare.
  91819. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  91820. * It controls one of the indiviual texture used in the effect.
  91821. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91822. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  91823. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  91824. * @param color Define the lens color
  91825. * @param imgUrl Define the lens texture url
  91826. * @param system Define the `lensFlareSystem` this flare is part of
  91827. * @returns The newly created Lens Flare
  91828. */
  91829. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  91830. return new LensFlare(size, position, color, imgUrl, system);
  91831. };
  91832. /**
  91833. * Dispose and release the lens flare with its associated resources.
  91834. */
  91835. LensFlare.prototype.dispose = function () {
  91836. if (this.texture) {
  91837. this.texture.dispose();
  91838. }
  91839. // Remove from scene
  91840. var index = this._system.lensFlares.indexOf(this);
  91841. this._system.lensFlares.splice(index, 1);
  91842. };
  91843. ;
  91844. return LensFlare;
  91845. }());
  91846. BABYLON.LensFlare = LensFlare;
  91847. })(BABYLON || (BABYLON = {}));
  91848. //# sourceMappingURL=babylon.lensFlare.js.map
  91849. var BABYLON;
  91850. (function (BABYLON) {
  91851. // Adds the parser to the scene parsers.
  91852. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  91853. // Lens flares
  91854. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  91855. if (!container.lensFlareSystems) {
  91856. container.lensFlareSystems = new Array();
  91857. }
  91858. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  91859. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  91860. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  91861. container.lensFlareSystems.push(lf);
  91862. }
  91863. }
  91864. });
  91865. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  91866. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91867. if (this.lensFlareSystems[index].name === name) {
  91868. return this.lensFlareSystems[index];
  91869. }
  91870. }
  91871. return null;
  91872. };
  91873. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  91874. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91875. if (this.lensFlareSystems[index].id === id) {
  91876. return this.lensFlareSystems[index];
  91877. }
  91878. }
  91879. return null;
  91880. };
  91881. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  91882. var index = this.lensFlareSystems.indexOf(toRemove);
  91883. if (index !== -1) {
  91884. this.lensFlareSystems.splice(index, 1);
  91885. }
  91886. return index;
  91887. };
  91888. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  91889. this.lensFlareSystems.push(newLensFlareSystem);
  91890. };
  91891. /**
  91892. * Defines the lens flare scene component responsible to manage any lens flares
  91893. * in a given scene.
  91894. */
  91895. var LensFlareSystemSceneComponent = /** @class */ (function () {
  91896. /**
  91897. * Creates a new instance of the component for the given scene
  91898. * @param scene Defines the scene to register the component in
  91899. */
  91900. function LensFlareSystemSceneComponent(scene) {
  91901. /**
  91902. * The component name helpfull to identify the component in the list of scene components.
  91903. */
  91904. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  91905. this.scene = scene;
  91906. scene.lensFlareSystems = new Array();
  91907. }
  91908. /**
  91909. * Registers the component in a given scene
  91910. */
  91911. LensFlareSystemSceneComponent.prototype.register = function () {
  91912. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  91913. };
  91914. /**
  91915. * Rebuilds the elements related to this component in case of
  91916. * context lost for instance.
  91917. */
  91918. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  91919. // Nothing to do for lens flare
  91920. };
  91921. /**
  91922. * Adds all the element from the container to the scene
  91923. * @param container the container holding the elements
  91924. */
  91925. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  91926. var _this = this;
  91927. if (!container.lensFlareSystems) {
  91928. return;
  91929. }
  91930. container.lensFlareSystems.forEach(function (o) {
  91931. _this.scene.addLensFlareSystem(o);
  91932. });
  91933. };
  91934. /**
  91935. * Removes all the elements in the container from the scene
  91936. * @param container contains the elements to remove
  91937. */
  91938. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  91939. var _this = this;
  91940. if (!container.lensFlareSystems) {
  91941. return;
  91942. }
  91943. container.lensFlareSystems.forEach(function (o) {
  91944. _this.scene.removeLensFlareSystem(o);
  91945. });
  91946. };
  91947. /**
  91948. * Serializes the component data to the specified json object
  91949. * @param serializationObject The object to serialize to
  91950. */
  91951. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  91952. // Lens flares
  91953. serializationObject.lensFlareSystems = [];
  91954. var lensFlareSystems = this.scene.lensFlareSystems;
  91955. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  91956. var lensFlareSystem = lensFlareSystems_1[_i];
  91957. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  91958. }
  91959. };
  91960. /**
  91961. * Disposes the component and the associated ressources.
  91962. */
  91963. LensFlareSystemSceneComponent.prototype.dispose = function () {
  91964. var lensFlareSystems = this.scene.lensFlareSystems;
  91965. while (lensFlareSystems.length) {
  91966. lensFlareSystems[0].dispose();
  91967. }
  91968. };
  91969. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  91970. // Lens flares
  91971. if (this.scene.lensFlaresEnabled) {
  91972. var lensFlareSystems = this.scene.lensFlareSystems;
  91973. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91974. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  91975. var lensFlareSystem = lensFlareSystems_2[_i];
  91976. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  91977. lensFlareSystem.render();
  91978. }
  91979. }
  91980. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91981. }
  91982. };
  91983. return LensFlareSystemSceneComponent;
  91984. }());
  91985. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  91986. })(BABYLON || (BABYLON = {}));
  91987. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  91988. var BABYLON;
  91989. (function (BABYLON) {
  91990. /**
  91991. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91992. * It is usually composed of several `BABYLON.lensFlare`.
  91993. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91994. */
  91995. var LensFlareSystem = /** @class */ (function () {
  91996. /**
  91997. * Instantiates a lens flare system.
  91998. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91999. * It is usually composed of several `BABYLON.lensFlare`.
  92000. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92001. * @param name Define the name of the lens flare system in the scene
  92002. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  92003. * @param scene Define the scene the lens flare system belongs to
  92004. */
  92005. function LensFlareSystem(
  92006. /**
  92007. * Define the name of the lens flare system
  92008. */
  92009. name, emitter, scene) {
  92010. this.name = name;
  92011. /**
  92012. * List of lens flares used in this system.
  92013. */
  92014. this.lensFlares = new Array();
  92015. /**
  92016. * Define a limit from the border the lens flare can be visible.
  92017. */
  92018. this.borderLimit = 300;
  92019. /**
  92020. * Define a viewport border we do not want to see the lens flare in.
  92021. */
  92022. this.viewportBorder = 0;
  92023. /**
  92024. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  92025. */
  92026. this.layerMask = 0x0FFFFFFF;
  92027. this._vertexBuffers = {};
  92028. this._isEnabled = true;
  92029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92030. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92031. if (!component) {
  92032. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92033. scene._addComponent(component);
  92034. }
  92035. this._emitter = emitter;
  92036. this.id = name;
  92037. scene.lensFlareSystems.push(this);
  92038. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92039. var engine = scene.getEngine();
  92040. // VBO
  92041. var vertices = [];
  92042. vertices.push(1, 1);
  92043. vertices.push(-1, 1);
  92044. vertices.push(-1, -1);
  92045. vertices.push(1, -1);
  92046. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92047. // Indices
  92048. var indices = [];
  92049. indices.push(0);
  92050. indices.push(1);
  92051. indices.push(2);
  92052. indices.push(0);
  92053. indices.push(2);
  92054. indices.push(3);
  92055. this._indexBuffer = engine.createIndexBuffer(indices);
  92056. // Effects
  92057. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92058. }
  92059. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92060. /**
  92061. * Define if the lens flare system is enabled.
  92062. */
  92063. get: function () {
  92064. return this._isEnabled;
  92065. },
  92066. set: function (value) {
  92067. this._isEnabled = value;
  92068. },
  92069. enumerable: true,
  92070. configurable: true
  92071. });
  92072. /**
  92073. * Get the scene the effects belongs to.
  92074. * @returns the scene holding the lens flare system
  92075. */
  92076. LensFlareSystem.prototype.getScene = function () {
  92077. return this._scene;
  92078. };
  92079. /**
  92080. * Get the emitter of the lens flare system.
  92081. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92082. * @returns the emitter of the lens flare system
  92083. */
  92084. LensFlareSystem.prototype.getEmitter = function () {
  92085. return this._emitter;
  92086. };
  92087. /**
  92088. * Set the emitter of the lens flare system.
  92089. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92090. * @param newEmitter Define the new emitter of the system
  92091. */
  92092. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92093. this._emitter = newEmitter;
  92094. };
  92095. /**
  92096. * Get the lens flare system emitter position.
  92097. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92098. * @returns the position
  92099. */
  92100. LensFlareSystem.prototype.getEmitterPosition = function () {
  92101. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92102. };
  92103. /**
  92104. * @hidden
  92105. */
  92106. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92107. var position = this.getEmitterPosition();
  92108. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92109. this._positionX = position.x;
  92110. this._positionY = position.y;
  92111. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92112. if (this.viewportBorder > 0) {
  92113. globalViewport.x -= this.viewportBorder;
  92114. globalViewport.y -= this.viewportBorder;
  92115. globalViewport.width += this.viewportBorder * 2;
  92116. globalViewport.height += this.viewportBorder * 2;
  92117. position.x += this.viewportBorder;
  92118. position.y += this.viewportBorder;
  92119. this._positionX += this.viewportBorder;
  92120. this._positionY += this.viewportBorder;
  92121. }
  92122. if (position.z > 0) {
  92123. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92124. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92125. return true;
  92126. }
  92127. return true;
  92128. }
  92129. return false;
  92130. };
  92131. /** @hidden */
  92132. LensFlareSystem.prototype._isVisible = function () {
  92133. if (!this._isEnabled || !this._scene.activeCamera) {
  92134. return false;
  92135. }
  92136. var emitterPosition = this.getEmitterPosition();
  92137. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92138. var distance = direction.length();
  92139. direction.normalize();
  92140. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92141. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92142. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92143. };
  92144. /**
  92145. * @hidden
  92146. */
  92147. LensFlareSystem.prototype.render = function () {
  92148. if (!this._effect.isReady() || !this._scene.activeCamera)
  92149. return false;
  92150. var engine = this._scene.getEngine();
  92151. var viewport = this._scene.activeCamera.viewport;
  92152. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92153. // Position
  92154. if (!this.computeEffectivePosition(globalViewport)) {
  92155. return false;
  92156. }
  92157. // Visibility
  92158. if (!this._isVisible()) {
  92159. return false;
  92160. }
  92161. // Intensity
  92162. var awayX;
  92163. var awayY;
  92164. if (this._positionX < this.borderLimit + globalViewport.x) {
  92165. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92166. }
  92167. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92168. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  92169. }
  92170. else {
  92171. awayX = 0;
  92172. }
  92173. if (this._positionY < this.borderLimit + globalViewport.y) {
  92174. awayY = this.borderLimit + globalViewport.y - this._positionY;
  92175. }
  92176. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  92177. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  92178. }
  92179. else {
  92180. awayY = 0;
  92181. }
  92182. var away = (awayX > awayY) ? awayX : awayY;
  92183. away -= this.viewportBorder;
  92184. if (away > this.borderLimit) {
  92185. away = this.borderLimit;
  92186. }
  92187. var intensity = 1.0 - (away / this.borderLimit);
  92188. if (intensity < 0) {
  92189. return false;
  92190. }
  92191. if (intensity > 1.0) {
  92192. intensity = 1.0;
  92193. }
  92194. if (this.viewportBorder > 0) {
  92195. globalViewport.x += this.viewportBorder;
  92196. globalViewport.y += this.viewportBorder;
  92197. globalViewport.width -= this.viewportBorder * 2;
  92198. globalViewport.height -= this.viewportBorder * 2;
  92199. this._positionX -= this.viewportBorder;
  92200. this._positionY -= this.viewportBorder;
  92201. }
  92202. // Position
  92203. var centerX = globalViewport.x + globalViewport.width / 2;
  92204. var centerY = globalViewport.y + globalViewport.height / 2;
  92205. var distX = centerX - this._positionX;
  92206. var distY = centerY - this._positionY;
  92207. // Effects
  92208. engine.enableEffect(this._effect);
  92209. engine.setState(false);
  92210. engine.setDepthBuffer(false);
  92211. // VBOs
  92212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  92213. // Flares
  92214. for (var index = 0; index < this.lensFlares.length; index++) {
  92215. var flare = this.lensFlares[index];
  92216. engine.setAlphaMode(flare.alphaMode);
  92217. var x = centerX - (distX * flare.position);
  92218. var y = centerY - (distY * flare.position);
  92219. var cw = flare.size;
  92220. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  92221. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  92222. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  92223. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  92224. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  92225. // Texture
  92226. this._effect.setTexture("textureSampler", flare.texture);
  92227. // Color
  92228. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  92229. // Draw order
  92230. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92231. }
  92232. engine.setDepthBuffer(true);
  92233. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92234. return true;
  92235. };
  92236. /**
  92237. * Dispose and release the lens flare with its associated resources.
  92238. */
  92239. LensFlareSystem.prototype.dispose = function () {
  92240. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92241. if (vertexBuffer) {
  92242. vertexBuffer.dispose();
  92243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92244. }
  92245. if (this._indexBuffer) {
  92246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92247. this._indexBuffer = null;
  92248. }
  92249. while (this.lensFlares.length) {
  92250. this.lensFlares[0].dispose();
  92251. }
  92252. // Remove from scene
  92253. var index = this._scene.lensFlareSystems.indexOf(this);
  92254. this._scene.lensFlareSystems.splice(index, 1);
  92255. };
  92256. /**
  92257. * Parse a lens flare system from a JSON repressentation
  92258. * @param parsedLensFlareSystem Define the JSON to parse
  92259. * @param scene Define the scene the parsed system should be instantiated in
  92260. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  92261. * @returns the parsed system
  92262. */
  92263. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  92264. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  92265. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  92266. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  92267. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  92268. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  92269. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  92270. var parsedFlare = parsedLensFlareSystem.flares[index];
  92271. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  92272. }
  92273. return lensFlareSystem;
  92274. };
  92275. /**
  92276. * Serialize the current Lens Flare System into a JSON representation.
  92277. * @returns the serialized JSON
  92278. */
  92279. LensFlareSystem.prototype.serialize = function () {
  92280. var serializationObject = {};
  92281. serializationObject.id = this.id;
  92282. serializationObject.name = this.name;
  92283. serializationObject.emitterId = this.getEmitter().id;
  92284. serializationObject.borderLimit = this.borderLimit;
  92285. serializationObject.flares = [];
  92286. for (var index = 0; index < this.lensFlares.length; index++) {
  92287. var flare = this.lensFlares[index];
  92288. serializationObject.flares.push({
  92289. size: flare.size,
  92290. position: flare.position,
  92291. color: flare.color.asArray(),
  92292. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  92293. });
  92294. }
  92295. return serializationObject;
  92296. };
  92297. return LensFlareSystem;
  92298. }());
  92299. BABYLON.LensFlareSystem = LensFlareSystem;
  92300. })(BABYLON || (BABYLON = {}));
  92301. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  92302. var BABYLON;
  92303. (function (BABYLON) {
  92304. /**
  92305. * This is a holder class for the physics joint created by the physics plugin.
  92306. * It holds a set of functions to control the underlying joint.
  92307. */
  92308. var PhysicsJoint = /** @class */ (function () {
  92309. function PhysicsJoint(type, jointData) {
  92310. this.type = type;
  92311. this.jointData = jointData;
  92312. jointData.nativeParams = jointData.nativeParams || {};
  92313. }
  92314. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  92315. get: function () {
  92316. return this._physicsJoint;
  92317. },
  92318. set: function (newJoint) {
  92319. if (this._physicsJoint) {
  92320. //remove from the wolrd
  92321. }
  92322. this._physicsJoint = newJoint;
  92323. },
  92324. enumerable: true,
  92325. configurable: true
  92326. });
  92327. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  92328. set: function (physicsPlugin) {
  92329. this._physicsPlugin = physicsPlugin;
  92330. },
  92331. enumerable: true,
  92332. configurable: true
  92333. });
  92334. /**
  92335. * Execute a function that is physics-plugin specific.
  92336. * @param {Function} func the function that will be executed.
  92337. * It accepts two parameters: the physics world and the physics joint.
  92338. */
  92339. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  92340. func(this._physicsPlugin.world, this._physicsJoint);
  92341. };
  92342. //TODO check if the native joints are the same
  92343. //Joint Types
  92344. PhysicsJoint.DistanceJoint = 0;
  92345. PhysicsJoint.HingeJoint = 1;
  92346. PhysicsJoint.BallAndSocketJoint = 2;
  92347. PhysicsJoint.WheelJoint = 3;
  92348. PhysicsJoint.SliderJoint = 4;
  92349. //OIMO
  92350. PhysicsJoint.PrismaticJoint = 5;
  92351. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  92352. PhysicsJoint.UniversalJoint = 6;
  92353. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  92354. //Cannon
  92355. //Similar to a Ball-Joint. Different in params
  92356. PhysicsJoint.PointToPointJoint = 8;
  92357. //Cannon only at the moment
  92358. PhysicsJoint.SpringJoint = 9;
  92359. PhysicsJoint.LockJoint = 10;
  92360. return PhysicsJoint;
  92361. }());
  92362. BABYLON.PhysicsJoint = PhysicsJoint;
  92363. /**
  92364. * A class representing a physics distance joint.
  92365. */
  92366. var DistanceJoint = /** @class */ (function (_super) {
  92367. __extends(DistanceJoint, _super);
  92368. function DistanceJoint(jointData) {
  92369. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  92370. }
  92371. /**
  92372. * Update the predefined distance.
  92373. */
  92374. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  92375. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  92376. };
  92377. return DistanceJoint;
  92378. }(PhysicsJoint));
  92379. BABYLON.DistanceJoint = DistanceJoint;
  92380. var MotorEnabledJoint = /** @class */ (function (_super) {
  92381. __extends(MotorEnabledJoint, _super);
  92382. function MotorEnabledJoint(type, jointData) {
  92383. return _super.call(this, type, jointData) || this;
  92384. }
  92385. /**
  92386. * Set the motor values.
  92387. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92388. * @param {number} force the force to apply
  92389. * @param {number} maxForce max force for this motor.
  92390. */
  92391. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  92392. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  92393. };
  92394. /**
  92395. * Set the motor's limits.
  92396. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92397. */
  92398. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  92399. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  92400. };
  92401. return MotorEnabledJoint;
  92402. }(PhysicsJoint));
  92403. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  92404. /**
  92405. * This class represents a single hinge physics joint
  92406. */
  92407. var HingeJoint = /** @class */ (function (_super) {
  92408. __extends(HingeJoint, _super);
  92409. function HingeJoint(jointData) {
  92410. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  92411. }
  92412. /**
  92413. * Set the motor values.
  92414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92415. * @param {number} force the force to apply
  92416. * @param {number} maxForce max force for this motor.
  92417. */
  92418. HingeJoint.prototype.setMotor = function (force, maxForce) {
  92419. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  92420. };
  92421. /**
  92422. * Set the motor's limits.
  92423. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92424. */
  92425. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  92426. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  92427. };
  92428. return HingeJoint;
  92429. }(MotorEnabledJoint));
  92430. BABYLON.HingeJoint = HingeJoint;
  92431. /**
  92432. * This class represents a dual hinge physics joint (same as wheel joint)
  92433. */
  92434. var Hinge2Joint = /** @class */ (function (_super) {
  92435. __extends(Hinge2Joint, _super);
  92436. function Hinge2Joint(jointData) {
  92437. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  92438. }
  92439. /**
  92440. * Set the motor values.
  92441. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92442. * @param {number} force the force to apply
  92443. * @param {number} maxForce max force for this motor.
  92444. * @param {motorIndex} the motor's index, 0 or 1.
  92445. */
  92446. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  92447. if (motorIndex === void 0) { motorIndex = 0; }
  92448. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  92449. };
  92450. /**
  92451. * Set the motor limits.
  92452. * Attention, this function is plugin specific. Engines won't react 100% the same.
  92453. * @param {number} upperLimit the upper limit
  92454. * @param {number} lowerLimit lower limit
  92455. * @param {motorIndex} the motor's index, 0 or 1.
  92456. */
  92457. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  92458. if (motorIndex === void 0) { motorIndex = 0; }
  92459. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  92460. };
  92461. return Hinge2Joint;
  92462. }(MotorEnabledJoint));
  92463. BABYLON.Hinge2Joint = Hinge2Joint;
  92464. })(BABYLON || (BABYLON = {}));
  92465. //# sourceMappingURL=babylon.physicsJoint.js.map
  92466. var BABYLON;
  92467. (function (BABYLON) {
  92468. var PhysicsImpostor = /** @class */ (function () {
  92469. function PhysicsImpostor(object, type, _options, _scene) {
  92470. if (_options === void 0) { _options = { mass: 0 }; }
  92471. var _this = this;
  92472. this.object = object;
  92473. this.type = type;
  92474. this._options = _options;
  92475. this._scene = _scene;
  92476. this._bodyUpdateRequired = false;
  92477. this._onBeforePhysicsStepCallbacks = new Array();
  92478. this._onAfterPhysicsStepCallbacks = new Array();
  92479. this._onPhysicsCollideCallbacks = [];
  92480. this._deltaPosition = BABYLON.Vector3.Zero();
  92481. this._isDisposed = false;
  92482. //temp variables for parent rotation calculations
  92483. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  92484. this._tmpQuat = new BABYLON.Quaternion();
  92485. this._tmpQuat2 = new BABYLON.Quaternion();
  92486. /**
  92487. * this function is executed by the physics engine.
  92488. */
  92489. this.beforeStep = function () {
  92490. if (!_this._physicsEngine) {
  92491. return;
  92492. }
  92493. _this.object.translate(_this._deltaPosition, -1);
  92494. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  92495. _this.object.computeWorldMatrix(false);
  92496. if (_this.object.parent && _this.object.rotationQuaternion) {
  92497. _this.getParentsRotation();
  92498. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  92499. }
  92500. else {
  92501. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  92502. }
  92503. if (!_this._options.disableBidirectionalTransformation) {
  92504. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  92505. }
  92506. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  92507. func(_this);
  92508. });
  92509. };
  92510. /**
  92511. * this function is executed by the physics engine.
  92512. */
  92513. this.afterStep = function () {
  92514. if (!_this._physicsEngine) {
  92515. return;
  92516. }
  92517. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  92518. func(_this);
  92519. });
  92520. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  92521. // object has now its world rotation. needs to be converted to local.
  92522. if (_this.object.parent && _this.object.rotationQuaternion) {
  92523. _this.getParentsRotation();
  92524. _this._tmpQuat.conjugateInPlace();
  92525. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  92526. }
  92527. // take the position set and make it the absolute position of this object.
  92528. _this.object.setAbsolutePosition(_this.object.position);
  92529. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  92530. _this.object.translate(_this._deltaPosition, 1);
  92531. };
  92532. /**
  92533. * Legacy collision detection event support
  92534. */
  92535. this.onCollideEvent = null;
  92536. //event and body object due to cannon's event-based architecture.
  92537. this.onCollide = function (e) {
  92538. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  92539. return;
  92540. }
  92541. if (!_this._physicsEngine) {
  92542. return;
  92543. }
  92544. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  92545. if (otherImpostor) {
  92546. // Legacy collision detection event support
  92547. if (_this.onCollideEvent) {
  92548. _this.onCollideEvent(_this, otherImpostor);
  92549. }
  92550. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  92551. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  92552. }).forEach(function (obj) {
  92553. obj.callback(_this, otherImpostor);
  92554. });
  92555. }
  92556. };
  92557. //sanity check!
  92558. if (!this.object) {
  92559. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  92560. return;
  92561. }
  92562. //legacy support for old syntax.
  92563. if (!this._scene && object.getScene) {
  92564. this._scene = object.getScene();
  92565. }
  92566. if (!this._scene) {
  92567. return;
  92568. }
  92569. this._physicsEngine = this._scene.getPhysicsEngine();
  92570. if (!this._physicsEngine) {
  92571. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  92572. }
  92573. else {
  92574. //set the object's quaternion, if not set
  92575. if (!this.object.rotationQuaternion) {
  92576. if (this.object.rotation) {
  92577. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  92578. }
  92579. else {
  92580. this.object.rotationQuaternion = new BABYLON.Quaternion();
  92581. }
  92582. }
  92583. //default options params
  92584. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  92585. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  92586. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  92587. this._joints = [];
  92588. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  92589. if (!this.object.parent || this._options.ignoreParent) {
  92590. this._init();
  92591. }
  92592. else if (this.object.parent.physicsImpostor) {
  92593. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  92594. }
  92595. }
  92596. }
  92597. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  92598. get: function () {
  92599. return this._isDisposed;
  92600. },
  92601. enumerable: true,
  92602. configurable: true
  92603. });
  92604. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  92605. get: function () {
  92606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  92607. },
  92608. set: function (value) {
  92609. this.setMass(value);
  92610. },
  92611. enumerable: true,
  92612. configurable: true
  92613. });
  92614. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  92615. get: function () {
  92616. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  92617. },
  92618. set: function (value) {
  92619. if (!this._physicsEngine) {
  92620. return;
  92621. }
  92622. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  92623. },
  92624. enumerable: true,
  92625. configurable: true
  92626. });
  92627. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  92628. get: function () {
  92629. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  92630. },
  92631. set: function (value) {
  92632. if (!this._physicsEngine) {
  92633. return;
  92634. }
  92635. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  92636. },
  92637. enumerable: true,
  92638. configurable: true
  92639. });
  92640. /**
  92641. * This function will completly initialize this impostor.
  92642. * It will create a new body - but only if this mesh has no parent.
  92643. * If it has, this impostor will not be used other than to define the impostor
  92644. * of the child mesh.
  92645. * @hidden
  92646. */
  92647. PhysicsImpostor.prototype._init = function () {
  92648. if (!this._physicsEngine) {
  92649. return;
  92650. }
  92651. this._physicsEngine.removeImpostor(this);
  92652. this.physicsBody = null;
  92653. this._parent = this._parent || this._getPhysicsParent();
  92654. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  92655. this._physicsEngine.addImpostor(this);
  92656. }
  92657. };
  92658. PhysicsImpostor.prototype._getPhysicsParent = function () {
  92659. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  92660. var parentMesh = this.object.parent;
  92661. return parentMesh.physicsImpostor;
  92662. }
  92663. return null;
  92664. };
  92665. /**
  92666. * Should a new body be generated.
  92667. */
  92668. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  92669. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  92670. };
  92671. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  92672. this.forceUpdate();
  92673. };
  92674. /**
  92675. * Force a regeneration of this or the parent's impostor's body.
  92676. * Use under cautious - This will remove all joints already implemented.
  92677. */
  92678. PhysicsImpostor.prototype.forceUpdate = function () {
  92679. this._init();
  92680. if (this.parent && !this._options.ignoreParent) {
  92681. this.parent.forceUpdate();
  92682. }
  92683. };
  92684. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  92685. /*public get mesh(): AbstractMesh {
  92686. return this._mesh;
  92687. }*/
  92688. /**
  92689. * Gets the body that holds this impostor. Either its own, or its parent.
  92690. */
  92691. get: function () {
  92692. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  92693. },
  92694. /**
  92695. * Set the physics body. Used mainly by the physics engine/plugin
  92696. */
  92697. set: function (physicsBody) {
  92698. if (this._physicsBody && this._physicsEngine) {
  92699. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  92700. }
  92701. this._physicsBody = physicsBody;
  92702. this.resetUpdateFlags();
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  92708. get: function () {
  92709. return !this._options.ignoreParent && this._parent ? this._parent : null;
  92710. },
  92711. set: function (value) {
  92712. this._parent = value;
  92713. },
  92714. enumerable: true,
  92715. configurable: true
  92716. });
  92717. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  92718. this._bodyUpdateRequired = false;
  92719. };
  92720. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  92721. if (this.object.getBoundingInfo) {
  92722. var q = this.object.rotationQuaternion;
  92723. //reset rotation
  92724. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  92725. //calculate the world matrix with no rotation
  92726. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  92727. var boundingInfo = this.object.getBoundingInfo();
  92728. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  92729. //bring back the rotation
  92730. this.object.rotationQuaternion = q;
  92731. //calculate the world matrix with the new rotation
  92732. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  92733. return size;
  92734. }
  92735. else {
  92736. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  92737. }
  92738. };
  92739. PhysicsImpostor.prototype.getObjectCenter = function () {
  92740. if (this.object.getBoundingInfo) {
  92741. var boundingInfo = this.object.getBoundingInfo();
  92742. return boundingInfo.boundingBox.centerWorld;
  92743. }
  92744. else {
  92745. return this.object.position;
  92746. }
  92747. };
  92748. /**
  92749. * Get a specific parametes from the options parameter.
  92750. */
  92751. PhysicsImpostor.prototype.getParam = function (paramName) {
  92752. return this._options[paramName];
  92753. };
  92754. /**
  92755. * Sets a specific parameter in the options given to the physics plugin
  92756. */
  92757. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  92758. this._options[paramName] = value;
  92759. this._bodyUpdateRequired = true;
  92760. };
  92761. /**
  92762. * Specifically change the body's mass option. Won't recreate the physics body object
  92763. */
  92764. PhysicsImpostor.prototype.setMass = function (mass) {
  92765. if (this.getParam("mass") !== mass) {
  92766. this.setParam("mass", mass);
  92767. }
  92768. if (this._physicsEngine) {
  92769. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  92770. }
  92771. };
  92772. PhysicsImpostor.prototype.getLinearVelocity = function () {
  92773. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  92774. };
  92775. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  92776. if (this._physicsEngine) {
  92777. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  92778. }
  92779. };
  92780. PhysicsImpostor.prototype.getAngularVelocity = function () {
  92781. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  92782. };
  92783. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  92784. if (this._physicsEngine) {
  92785. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  92786. }
  92787. };
  92788. /**
  92789. * Execute a function with the physics plugin native code.
  92790. * Provide a function the will have two variables - the world object and the physics body object.
  92791. */
  92792. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  92793. if (this._physicsEngine) {
  92794. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  92795. }
  92796. };
  92797. /**
  92798. * Register a function that will be executed before the physics world is stepping forward.
  92799. */
  92800. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  92801. this._onBeforePhysicsStepCallbacks.push(func);
  92802. };
  92803. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  92804. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  92805. if (index > -1) {
  92806. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  92807. }
  92808. else {
  92809. BABYLON.Tools.Warn("Function to remove was not found");
  92810. }
  92811. };
  92812. /**
  92813. * Register a function that will be executed after the physics step
  92814. */
  92815. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  92816. this._onAfterPhysicsStepCallbacks.push(func);
  92817. };
  92818. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  92819. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  92820. if (index > -1) {
  92821. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  92822. }
  92823. else {
  92824. BABYLON.Tools.Warn("Function to remove was not found");
  92825. }
  92826. };
  92827. /**
  92828. * register a function that will be executed when this impostor collides against a different body.
  92829. */
  92830. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  92831. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92832. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  92833. };
  92834. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  92835. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92836. var index = -1;
  92837. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  92838. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  92839. // chcek the arrays match
  92840. var sameList = cbDef.otherImpostors.every(function (impostor) {
  92841. return collidedAgainstList.indexOf(impostor) > -1;
  92842. });
  92843. if (sameList) {
  92844. index = idx;
  92845. }
  92846. return sameList;
  92847. }
  92848. return false;
  92849. });
  92850. if (found) {
  92851. this._onPhysicsCollideCallbacks.splice(index, 1);
  92852. }
  92853. else {
  92854. BABYLON.Tools.Warn("Function to remove was not found");
  92855. }
  92856. };
  92857. PhysicsImpostor.prototype.getParentsRotation = function () {
  92858. var parent = this.object.parent;
  92859. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  92860. while (parent) {
  92861. if (parent.rotationQuaternion) {
  92862. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  92863. }
  92864. else {
  92865. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  92866. }
  92867. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  92868. parent = parent.parent;
  92869. }
  92870. return this._tmpQuat;
  92871. };
  92872. /**
  92873. * Apply a force
  92874. */
  92875. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  92876. if (this._physicsEngine) {
  92877. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  92878. }
  92879. return this;
  92880. };
  92881. /**
  92882. * Apply an impulse
  92883. */
  92884. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  92885. if (this._physicsEngine) {
  92886. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  92887. }
  92888. return this;
  92889. };
  92890. /**
  92891. * A help function to create a joint.
  92892. */
  92893. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  92894. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  92895. this.addJoint(otherImpostor, joint);
  92896. return this;
  92897. };
  92898. /**
  92899. * Add a joint to this impostor with a different impostor.
  92900. */
  92901. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  92902. this._joints.push({
  92903. otherImpostor: otherImpostor,
  92904. joint: joint
  92905. });
  92906. if (this._physicsEngine) {
  92907. this._physicsEngine.addJoint(this, otherImpostor, joint);
  92908. }
  92909. return this;
  92910. };
  92911. /**
  92912. * Will keep this body still, in a sleep mode.
  92913. */
  92914. PhysicsImpostor.prototype.sleep = function () {
  92915. if (this._physicsEngine) {
  92916. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  92917. }
  92918. return this;
  92919. };
  92920. /**
  92921. * Wake the body up.
  92922. */
  92923. PhysicsImpostor.prototype.wakeUp = function () {
  92924. if (this._physicsEngine) {
  92925. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  92926. }
  92927. return this;
  92928. };
  92929. PhysicsImpostor.prototype.clone = function (newObject) {
  92930. if (!newObject)
  92931. return null;
  92932. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  92933. };
  92934. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  92935. var _this = this;
  92936. //no dispose if no physics engine is available.
  92937. if (!this._physicsEngine) {
  92938. return;
  92939. }
  92940. this._joints.forEach(function (j) {
  92941. if (_this._physicsEngine) {
  92942. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  92943. }
  92944. });
  92945. //dispose the physics body
  92946. this._physicsEngine.removeImpostor(this);
  92947. if (this.parent) {
  92948. this.parent.forceUpdate();
  92949. }
  92950. else {
  92951. /*this._object.getChildMeshes().forEach(function(mesh) {
  92952. if (mesh.physicsImpostor) {
  92953. if (disposeChildren) {
  92954. mesh.physicsImpostor.dispose();
  92955. mesh.physicsImpostor = null;
  92956. }
  92957. }
  92958. })*/
  92959. }
  92960. this._isDisposed = true;
  92961. };
  92962. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  92963. this._deltaPosition.copyFrom(position);
  92964. };
  92965. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  92966. if (!this._deltaRotation) {
  92967. this._deltaRotation = new BABYLON.Quaternion();
  92968. }
  92969. this._deltaRotation.copyFrom(rotation);
  92970. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  92971. };
  92972. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  92973. if (this._physicsEngine) {
  92974. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  92975. }
  92976. return this;
  92977. };
  92978. PhysicsImpostor.prototype.getRadius = function () {
  92979. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  92980. };
  92981. /**
  92982. * Sync a bone with this impostor
  92983. * @param bone The bone to sync to the impostor.
  92984. * @param boneMesh The mesh that the bone is influencing.
  92985. * @param jointPivot The pivot of the joint / bone in local space.
  92986. * @param distToJoint Optional distance from the impostor to the joint.
  92987. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92988. */
  92989. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  92990. var tempVec = PhysicsImpostor._tmpVecs[0];
  92991. var mesh = this.object;
  92992. if (mesh.rotationQuaternion) {
  92993. if (adjustRotation) {
  92994. var tempQuat = PhysicsImpostor._tmpQuat;
  92995. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  92996. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  92997. }
  92998. else {
  92999. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  93000. }
  93001. }
  93002. tempVec.x = 0;
  93003. tempVec.y = 0;
  93004. tempVec.z = 0;
  93005. if (jointPivot) {
  93006. tempVec.x = jointPivot.x;
  93007. tempVec.y = jointPivot.y;
  93008. tempVec.z = jointPivot.z;
  93009. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  93010. if (distToJoint === undefined || distToJoint === null) {
  93011. distToJoint = jointPivot.length();
  93012. }
  93013. tempVec.x *= distToJoint;
  93014. tempVec.y *= distToJoint;
  93015. tempVec.z *= distToJoint;
  93016. }
  93017. if (bone.getParent()) {
  93018. tempVec.addInPlace(mesh.getAbsolutePosition());
  93019. bone.setAbsolutePosition(tempVec, boneMesh);
  93020. }
  93021. else {
  93022. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  93023. boneMesh.position.x -= tempVec.x;
  93024. boneMesh.position.y -= tempVec.y;
  93025. boneMesh.position.z -= tempVec.z;
  93026. }
  93027. };
  93028. /**
  93029. * Sync impostor to a bone
  93030. * @param bone The bone that the impostor will be synced to.
  93031. * @param boneMesh The mesh that the bone is influencing.
  93032. * @param jointPivot The pivot of the joint / bone in local space.
  93033. * @param distToJoint Optional distance from the impostor to the joint.
  93034. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93035. * @param boneAxis Optional vector3 axis the bone is aligned with
  93036. */
  93037. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93038. var mesh = this.object;
  93039. if (mesh.rotationQuaternion) {
  93040. if (adjustRotation) {
  93041. var tempQuat = PhysicsImpostor._tmpQuat;
  93042. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93043. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93044. }
  93045. else {
  93046. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93047. }
  93048. }
  93049. var pos = PhysicsImpostor._tmpVecs[0];
  93050. var boneDir = PhysicsImpostor._tmpVecs[1];
  93051. if (!boneAxis) {
  93052. boneAxis = PhysicsImpostor._tmpVecs[2];
  93053. boneAxis.x = 0;
  93054. boneAxis.y = 1;
  93055. boneAxis.z = 0;
  93056. }
  93057. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93058. bone.getAbsolutePositionToRef(boneMesh, pos);
  93059. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93060. distToJoint = jointPivot.length();
  93061. }
  93062. if (distToJoint !== undefined && distToJoint !== null) {
  93063. pos.x += boneDir.x * distToJoint;
  93064. pos.y += boneDir.y * distToJoint;
  93065. pos.z += boneDir.z * distToJoint;
  93066. }
  93067. mesh.setAbsolutePosition(pos);
  93068. };
  93069. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93070. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93071. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93072. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93073. //Impostor types
  93074. PhysicsImpostor.NoImpostor = 0;
  93075. PhysicsImpostor.SphereImpostor = 1;
  93076. PhysicsImpostor.BoxImpostor = 2;
  93077. PhysicsImpostor.PlaneImpostor = 3;
  93078. PhysicsImpostor.MeshImpostor = 4;
  93079. PhysicsImpostor.CylinderImpostor = 7;
  93080. PhysicsImpostor.ParticleImpostor = 8;
  93081. PhysicsImpostor.HeightmapImpostor = 9;
  93082. return PhysicsImpostor;
  93083. }());
  93084. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93085. })(BABYLON || (BABYLON = {}));
  93086. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93087. var BABYLON;
  93088. (function (BABYLON) {
  93089. /**
  93090. * Class used to control physics engine
  93091. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93092. */
  93093. var PhysicsEngine = /** @class */ (function () {
  93094. /**
  93095. * Creates a new Physics Engine
  93096. * @param gravity defines the gravity vector used by the simulation
  93097. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93098. */
  93099. function PhysicsEngine(gravity, _physicsPlugin) {
  93100. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93101. this._physicsPlugin = _physicsPlugin;
  93102. this._impostors = [];
  93103. this._joints = [];
  93104. if (!this._physicsPlugin.isSupported()) {
  93105. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93106. + "Please make sure it is included.");
  93107. }
  93108. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93109. this.setGravity(gravity);
  93110. this.setTimeStep();
  93111. }
  93112. /**
  93113. * Sets the gravity vector used by the simulation
  93114. * @param gravity defines the gravity vector to use
  93115. */
  93116. PhysicsEngine.prototype.setGravity = function (gravity) {
  93117. this.gravity = gravity;
  93118. this._physicsPlugin.setGravity(this.gravity);
  93119. };
  93120. /**
  93121. * Set the time step of the physics engine.
  93122. * Default is 1/60.
  93123. * To slow it down, enter 1/600 for example.
  93124. * To speed it up, 1/30
  93125. * @param newTimeStep defines the new timestep to apply to this world.
  93126. */
  93127. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93128. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93129. this._physicsPlugin.setTimeStep(newTimeStep);
  93130. };
  93131. /**
  93132. * Get the time step of the physics engine.
  93133. * @returns the current time step
  93134. */
  93135. PhysicsEngine.prototype.getTimeStep = function () {
  93136. return this._physicsPlugin.getTimeStep();
  93137. };
  93138. /**
  93139. * Release all resources
  93140. */
  93141. PhysicsEngine.prototype.dispose = function () {
  93142. this._impostors.forEach(function (impostor) {
  93143. impostor.dispose();
  93144. });
  93145. this._physicsPlugin.dispose();
  93146. };
  93147. /**
  93148. * Gets the name of the current physics plugin
  93149. * @returns the name of the plugin
  93150. */
  93151. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93152. return this._physicsPlugin.name;
  93153. };
  93154. /**
  93155. * Adding a new impostor for the impostor tracking.
  93156. * This will be done by the impostor itself.
  93157. * @param impostor the impostor to add
  93158. */
  93159. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93160. impostor.uniqueId = this._impostors.push(impostor);
  93161. //if no parent, generate the body
  93162. if (!impostor.parent) {
  93163. this._physicsPlugin.generatePhysicsBody(impostor);
  93164. }
  93165. };
  93166. /**
  93167. * Remove an impostor from the engine.
  93168. * This impostor and its mesh will not longer be updated by the physics engine.
  93169. * @param impostor the impostor to remove
  93170. */
  93171. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  93172. var index = this._impostors.indexOf(impostor);
  93173. if (index > -1) {
  93174. var removed = this._impostors.splice(index, 1);
  93175. //Is it needed?
  93176. if (removed.length) {
  93177. //this will also remove it from the world.
  93178. removed[0].physicsBody = null;
  93179. }
  93180. }
  93181. };
  93182. /**
  93183. * Add a joint to the physics engine
  93184. * @param mainImpostor defines the main impostor to which the joint is added.
  93185. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  93186. * @param joint defines the joint that will connect both impostors.
  93187. */
  93188. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  93189. var impostorJoint = {
  93190. mainImpostor: mainImpostor,
  93191. connectedImpostor: connectedImpostor,
  93192. joint: joint
  93193. };
  93194. joint.physicsPlugin = this._physicsPlugin;
  93195. this._joints.push(impostorJoint);
  93196. this._physicsPlugin.generateJoint(impostorJoint);
  93197. };
  93198. /**
  93199. * Removes a joint from the simulation
  93200. * @param mainImpostor defines the impostor used with the joint
  93201. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  93202. * @param joint defines the joint to remove
  93203. */
  93204. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  93205. var matchingJoints = this._joints.filter(function (impostorJoint) {
  93206. return (impostorJoint.connectedImpostor === connectedImpostor
  93207. && impostorJoint.joint === joint
  93208. && impostorJoint.mainImpostor === mainImpostor);
  93209. });
  93210. if (matchingJoints.length) {
  93211. this._physicsPlugin.removeJoint(matchingJoints[0]);
  93212. //TODO remove it from the list as well
  93213. }
  93214. };
  93215. /**
  93216. * Called by the scene. No need to call it.
  93217. * @param delta defines the timespam between frames
  93218. */
  93219. PhysicsEngine.prototype._step = function (delta) {
  93220. var _this = this;
  93221. //check if any mesh has no body / requires an update
  93222. this._impostors.forEach(function (impostor) {
  93223. if (impostor.isBodyInitRequired()) {
  93224. _this._physicsPlugin.generatePhysicsBody(impostor);
  93225. }
  93226. });
  93227. if (delta > 0.1) {
  93228. delta = 0.1;
  93229. }
  93230. else if (delta <= 0) {
  93231. delta = 1.0 / 60.0;
  93232. }
  93233. this._physicsPlugin.executeStep(delta, this._impostors);
  93234. };
  93235. /**
  93236. * Gets the current plugin used to run the simulation
  93237. * @returns current plugin
  93238. */
  93239. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  93240. return this._physicsPlugin;
  93241. };
  93242. /**
  93243. * Gets the list of physic impostors
  93244. * @returns an array of PhysicsImpostor
  93245. */
  93246. PhysicsEngine.prototype.getImpostors = function () {
  93247. return this._impostors;
  93248. };
  93249. /**
  93250. * Gets the impostor for a physics enabled object
  93251. * @param object defines the object impersonated by the impostor
  93252. * @returns the PhysicsImpostor or null if not found
  93253. */
  93254. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  93255. for (var i = 0; i < this._impostors.length; ++i) {
  93256. if (this._impostors[i].object === object) {
  93257. return this._impostors[i];
  93258. }
  93259. }
  93260. return null;
  93261. };
  93262. /**
  93263. * Gets the impostor for a physics body object
  93264. * @param body defines physics body used by the impostor
  93265. * @returns the PhysicsImpostor or null if not found
  93266. */
  93267. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  93268. for (var i = 0; i < this._impostors.length; ++i) {
  93269. if (this._impostors[i].physicsBody === body) {
  93270. return this._impostors[i];
  93271. }
  93272. }
  93273. return null;
  93274. };
  93275. /**
  93276. * Global value used to control the smallest number supported by the simulation
  93277. */
  93278. PhysicsEngine.Epsilon = 0.001;
  93279. return PhysicsEngine;
  93280. }());
  93281. BABYLON.PhysicsEngine = PhysicsEngine;
  93282. })(BABYLON || (BABYLON = {}));
  93283. //# sourceMappingURL=babylon.physicsEngine.js.map
  93284. var BABYLON;
  93285. (function (BABYLON) {
  93286. var PhysicsHelper = /** @class */ (function () {
  93287. function PhysicsHelper(scene) {
  93288. this._scene = scene;
  93289. this._physicsEngine = this._scene.getPhysicsEngine();
  93290. if (!this._physicsEngine) {
  93291. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  93292. }
  93293. }
  93294. /**
  93295. * @param {Vector3} origin the origin of the explosion
  93296. * @param {number} radius the explosion radius
  93297. * @param {number} strength the explosion strength
  93298. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93299. */
  93300. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  93301. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93302. if (!this._physicsEngine) {
  93303. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  93304. return null;
  93305. }
  93306. var impostors = this._physicsEngine.getImpostors();
  93307. if (impostors.length === 0) {
  93308. return null;
  93309. }
  93310. var event = new PhysicsRadialExplosionEvent(this._scene);
  93311. impostors.forEach(function (impostor) {
  93312. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  93313. if (!impostorForceAndContactPoint) {
  93314. return;
  93315. }
  93316. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93317. });
  93318. event.dispose(false);
  93319. return event;
  93320. };
  93321. /**
  93322. * @param {Vector3} origin the origin of the explosion
  93323. * @param {number} radius the explosion radius
  93324. * @param {number} strength the explosion strength
  93325. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93326. */
  93327. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  93328. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93329. if (!this._physicsEngine) {
  93330. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93331. return null;
  93332. }
  93333. var impostors = this._physicsEngine.getImpostors();
  93334. if (impostors.length === 0) {
  93335. return null;
  93336. }
  93337. var event = new PhysicsRadialExplosionEvent(this._scene);
  93338. impostors.forEach(function (impostor) {
  93339. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  93340. if (!impostorForceAndContactPoint) {
  93341. return;
  93342. }
  93343. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93344. });
  93345. event.dispose(false);
  93346. return event;
  93347. };
  93348. /**
  93349. * @param {Vector3} origin the origin of the explosion
  93350. * @param {number} radius the explosion radius
  93351. * @param {number} strength the explosion strength
  93352. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  93353. */
  93354. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  93355. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93356. if (!this._physicsEngine) {
  93357. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93358. return null;
  93359. }
  93360. var impostors = this._physicsEngine.getImpostors();
  93361. if (impostors.length === 0) {
  93362. return null;
  93363. }
  93364. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  93365. event.dispose(false);
  93366. return event;
  93367. };
  93368. /**
  93369. * @param {Vector3} origin the origin of the updraft
  93370. * @param {number} radius the radius of the updraft
  93371. * @param {number} strength the strength of the updraft
  93372. * @param {number} height the height of the updraft
  93373. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  93374. */
  93375. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  93376. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  93377. if (!this._physicsEngine) {
  93378. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93379. return null;
  93380. }
  93381. if (this._physicsEngine.getImpostors().length === 0) {
  93382. return null;
  93383. }
  93384. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  93385. event.dispose(false);
  93386. return event;
  93387. };
  93388. /**
  93389. * @param {Vector3} origin the of the vortex
  93390. * @param {number} radius the radius of the vortex
  93391. * @param {number} strength the strength of the vortex
  93392. * @param {number} height the height of the vortex
  93393. */
  93394. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  93395. if (!this._physicsEngine) {
  93396. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  93397. return null;
  93398. }
  93399. if (this._physicsEngine.getImpostors().length === 0) {
  93400. return null;
  93401. }
  93402. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  93403. event.dispose(false);
  93404. return event;
  93405. };
  93406. return PhysicsHelper;
  93407. }());
  93408. BABYLON.PhysicsHelper = PhysicsHelper;
  93409. /***** Radial explosion *****/
  93410. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  93411. function PhysicsRadialExplosionEvent(scene) {
  93412. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  93413. this._rays = [];
  93414. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  93415. this._scene = scene;
  93416. }
  93417. /**
  93418. * Returns the data related to the radial explosion event (sphere & rays).
  93419. * @returns {PhysicsRadialExplosionEventData}
  93420. */
  93421. PhysicsRadialExplosionEvent.prototype.getData = function () {
  93422. this._dataFetched = true;
  93423. return {
  93424. sphere: this._sphere,
  93425. rays: this._rays,
  93426. };
  93427. };
  93428. /**
  93429. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  93430. * @param impostor
  93431. * @param {Vector3} origin the origin of the explosion
  93432. * @param {number} radius the explosion radius
  93433. * @param {number} strength the explosion strength
  93434. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  93435. * @returns {Nullable<PhysicsForceAndContactPoint>}
  93436. */
  93437. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  93438. if (impostor.mass === 0) {
  93439. return null;
  93440. }
  93441. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  93442. return null;
  93443. }
  93444. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  93445. return null;
  93446. }
  93447. var impostorObjectCenter = impostor.getObjectCenter();
  93448. var direction = impostorObjectCenter.subtract(origin);
  93449. var ray = new BABYLON.Ray(origin, direction, radius);
  93450. this._rays.push(ray);
  93451. var hit = ray.intersectsMesh(impostor.object);
  93452. var contactPoint = hit.pickedPoint;
  93453. if (!contactPoint) {
  93454. return null;
  93455. }
  93456. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  93457. if (distanceFromOrigin > radius) {
  93458. return null;
  93459. }
  93460. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  93461. ? strength
  93462. : strength * (1 - (distanceFromOrigin / radius));
  93463. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  93464. return { force: force, contactPoint: contactPoint };
  93465. };
  93466. /**
  93467. * Disposes the sphere.
  93468. * @param {bolean} force
  93469. */
  93470. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  93471. var _this = this;
  93472. if (force === void 0) { force = true; }
  93473. if (force) {
  93474. this._sphere.dispose();
  93475. }
  93476. else {
  93477. setTimeout(function () {
  93478. if (!_this._dataFetched) {
  93479. _this._sphere.dispose();
  93480. }
  93481. }, 0);
  93482. }
  93483. };
  93484. /*** Helpers ***/
  93485. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  93486. if (!this._sphere) {
  93487. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  93488. this._sphere.isVisible = false;
  93489. }
  93490. };
  93491. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  93492. var impostorObject = impostor.object;
  93493. this._prepareSphere();
  93494. this._sphere.position = origin;
  93495. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  93496. this._sphere._updateBoundingInfo();
  93497. this._sphere.computeWorldMatrix(true);
  93498. return this._sphere.intersectsMesh(impostorObject, true);
  93499. };
  93500. return PhysicsRadialExplosionEvent;
  93501. }());
  93502. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  93503. /***** Gravitational Field *****/
  93504. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  93505. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  93506. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  93507. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93508. this._physicsHelper = physicsHelper;
  93509. this._scene = scene;
  93510. this._origin = origin;
  93511. this._radius = radius;
  93512. this._strength = strength;
  93513. this._falloff = falloff;
  93514. this._tickCallback = this._tick.bind(this);
  93515. }
  93516. /**
  93517. * Returns the data related to the gravitational field event (sphere).
  93518. * @returns {PhysicsGravitationalFieldEventData}
  93519. */
  93520. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  93521. this._dataFetched = true;
  93522. return {
  93523. sphere: this._sphere,
  93524. };
  93525. };
  93526. /**
  93527. * Enables the gravitational field.
  93528. */
  93529. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  93530. this._tickCallback.call(this);
  93531. this._scene.registerBeforeRender(this._tickCallback);
  93532. };
  93533. /**
  93534. * Disables the gravitational field.
  93535. */
  93536. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  93537. this._scene.unregisterBeforeRender(this._tickCallback);
  93538. };
  93539. /**
  93540. * Disposes the sphere.
  93541. * @param {bolean} force
  93542. */
  93543. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  93544. var _this = this;
  93545. if (force === void 0) { force = true; }
  93546. if (force) {
  93547. this._sphere.dispose();
  93548. }
  93549. else {
  93550. setTimeout(function () {
  93551. if (!_this._dataFetched) {
  93552. _this._sphere.dispose();
  93553. }
  93554. }, 0);
  93555. }
  93556. };
  93557. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  93558. // Since the params won't change, we fetch the event only once
  93559. if (this._sphere) {
  93560. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  93561. }
  93562. else {
  93563. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  93564. if (radialExplosionEvent) {
  93565. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  93566. }
  93567. }
  93568. };
  93569. return PhysicsGravitationalFieldEvent;
  93570. }());
  93571. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  93572. /***** Updraft *****/
  93573. var PhysicsUpdraftEvent = /** @class */ (function () {
  93574. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  93575. this._scene = _scene;
  93576. this._origin = _origin;
  93577. this._radius = _radius;
  93578. this._strength = _strength;
  93579. this._height = _height;
  93580. this._updraftMode = _updraftMode;
  93581. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  93582. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  93583. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  93584. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93585. this._physicsEngine = this._scene.getPhysicsEngine();
  93586. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  93587. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  93588. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  93589. this._originDirection = this._origin.subtract(this._originTop).normalize();
  93590. }
  93591. this._tickCallback = this._tick.bind(this);
  93592. }
  93593. /**
  93594. * Returns the data related to the updraft event (cylinder).
  93595. * @returns {PhysicsUpdraftEventData}
  93596. */
  93597. PhysicsUpdraftEvent.prototype.getData = function () {
  93598. this._dataFetched = true;
  93599. return {
  93600. cylinder: this._cylinder,
  93601. };
  93602. };
  93603. /**
  93604. * Enables the updraft.
  93605. */
  93606. PhysicsUpdraftEvent.prototype.enable = function () {
  93607. this._tickCallback.call(this);
  93608. this._scene.registerBeforeRender(this._tickCallback);
  93609. };
  93610. /**
  93611. * Disables the cortex.
  93612. */
  93613. PhysicsUpdraftEvent.prototype.disable = function () {
  93614. this._scene.unregisterBeforeRender(this._tickCallback);
  93615. };
  93616. /**
  93617. * Disposes the sphere.
  93618. * @param {bolean} force
  93619. */
  93620. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  93621. var _this = this;
  93622. if (force === void 0) { force = true; }
  93623. if (force) {
  93624. this._cylinder.dispose();
  93625. }
  93626. else {
  93627. setTimeout(function () {
  93628. if (!_this._dataFetched) {
  93629. _this._cylinder.dispose();
  93630. }
  93631. }, 0);
  93632. }
  93633. };
  93634. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  93635. if (impostor.mass === 0) {
  93636. return null;
  93637. }
  93638. if (!this._intersectsWithCylinder(impostor)) {
  93639. return null;
  93640. }
  93641. var impostorObjectCenter = impostor.getObjectCenter();
  93642. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  93643. var direction = this._originDirection;
  93644. }
  93645. else {
  93646. var direction = impostorObjectCenter.subtract(this._originTop);
  93647. }
  93648. var multiplier = this._strength * -1;
  93649. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  93650. return { force: force, contactPoint: impostorObjectCenter };
  93651. };
  93652. PhysicsUpdraftEvent.prototype._tick = function () {
  93653. var _this = this;
  93654. this._physicsEngine.getImpostors().forEach(function (impostor) {
  93655. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  93656. if (!impostorForceAndContactPoint) {
  93657. return;
  93658. }
  93659. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93660. });
  93661. };
  93662. /*** Helpers ***/
  93663. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  93664. if (!this._cylinder) {
  93665. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  93666. height: this._height,
  93667. diameter: this._radius * 2,
  93668. }, this._scene);
  93669. this._cylinder.isVisible = false;
  93670. }
  93671. };
  93672. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  93673. var impostorObject = impostor.object;
  93674. this._prepareCylinder();
  93675. this._cylinder.position = this._cylinderPosition;
  93676. return this._cylinder.intersectsMesh(impostorObject, true);
  93677. };
  93678. return PhysicsUpdraftEvent;
  93679. }());
  93680. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  93681. /***** Vortex *****/
  93682. var PhysicsVortexEvent = /** @class */ (function () {
  93683. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  93684. this._scene = _scene;
  93685. this._origin = _origin;
  93686. this._radius = _radius;
  93687. this._strength = _strength;
  93688. this._height = _height;
  93689. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  93690. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  93691. this._updraftMultiplier = 0.02;
  93692. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  93693. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  93694. this._physicsEngine = this._scene.getPhysicsEngine();
  93695. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  93696. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  93697. this._tickCallback = this._tick.bind(this);
  93698. }
  93699. /**
  93700. * Returns the data related to the vortex event (cylinder).
  93701. * @returns {PhysicsVortexEventData}
  93702. */
  93703. PhysicsVortexEvent.prototype.getData = function () {
  93704. this._dataFetched = true;
  93705. return {
  93706. cylinder: this._cylinder,
  93707. };
  93708. };
  93709. /**
  93710. * Enables the vortex.
  93711. */
  93712. PhysicsVortexEvent.prototype.enable = function () {
  93713. this._tickCallback.call(this);
  93714. this._scene.registerBeforeRender(this._tickCallback);
  93715. };
  93716. /**
  93717. * Disables the cortex.
  93718. */
  93719. PhysicsVortexEvent.prototype.disable = function () {
  93720. this._scene.unregisterBeforeRender(this._tickCallback);
  93721. };
  93722. /**
  93723. * Disposes the sphere.
  93724. * @param {bolean} force
  93725. */
  93726. PhysicsVortexEvent.prototype.dispose = function (force) {
  93727. var _this = this;
  93728. if (force === void 0) { force = true; }
  93729. if (force) {
  93730. this._cylinder.dispose();
  93731. }
  93732. else {
  93733. setTimeout(function () {
  93734. if (!_this._dataFetched) {
  93735. _this._cylinder.dispose();
  93736. }
  93737. }, 0);
  93738. }
  93739. };
  93740. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  93741. if (impostor.mass === 0) {
  93742. return null;
  93743. }
  93744. if (!this._intersectsWithCylinder(impostor)) {
  93745. return null;
  93746. }
  93747. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  93748. return null;
  93749. }
  93750. var impostorObjectCenter = impostor.getObjectCenter();
  93751. 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)
  93752. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  93753. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  93754. var hit = ray.intersectsMesh(impostor.object);
  93755. var contactPoint = hit.pickedPoint;
  93756. if (!contactPoint) {
  93757. return null;
  93758. }
  93759. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  93760. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  93761. var directionToOrigin = contactPoint.normalize();
  93762. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  93763. directionToOrigin = directionToOrigin.negate();
  93764. }
  93765. // TODO: find a more physically based solution
  93766. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  93767. var forceX = directionToOrigin.x * this._strength / 8;
  93768. var forceY = directionToOrigin.y * this._updraftMultiplier;
  93769. var forceZ = directionToOrigin.z * this._strength / 8;
  93770. }
  93771. else {
  93772. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  93773. var forceY = this._originTop.y * this._updraftMultiplier;
  93774. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  93775. }
  93776. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  93777. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  93778. return { force: force, contactPoint: impostorObjectCenter };
  93779. };
  93780. PhysicsVortexEvent.prototype._tick = function () {
  93781. var _this = this;
  93782. this._physicsEngine.getImpostors().forEach(function (impostor) {
  93783. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  93784. if (!impostorForceAndContactPoint) {
  93785. return;
  93786. }
  93787. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  93788. });
  93789. };
  93790. /*** Helpers ***/
  93791. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  93792. if (!this._cylinder) {
  93793. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  93794. height: this._height,
  93795. diameter: this._radius * 2,
  93796. }, this._scene);
  93797. this._cylinder.isVisible = false;
  93798. }
  93799. };
  93800. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  93801. var impostorObject = impostor.object;
  93802. this._prepareCylinder();
  93803. this._cylinder.position = this._cylinderPosition;
  93804. return this._cylinder.intersectsMesh(impostorObject, true);
  93805. };
  93806. return PhysicsVortexEvent;
  93807. }());
  93808. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  93809. /***** Enums *****/
  93810. /**
  93811. * The strenght of the force in correspondence to the distance of the affected object
  93812. */
  93813. var PhysicsRadialImpulseFalloff;
  93814. (function (PhysicsRadialImpulseFalloff) {
  93815. /** Defines that impulse is constant in strength across it's whole radius */
  93816. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  93817. /** DEfines that impulse gets weaker if it's further from the origin */
  93818. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  93819. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  93820. /**
  93821. * The strenght of the force in correspondence to the distance of the affected object
  93822. */
  93823. var PhysicsUpdraftMode;
  93824. (function (PhysicsUpdraftMode) {
  93825. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  93826. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  93827. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  93828. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  93829. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  93830. })(BABYLON || (BABYLON = {}));
  93831. //# sourceMappingURL=babylon.physicsHelper.js.map
  93832. var BABYLON;
  93833. (function (BABYLON) {
  93834. /** @hidden */
  93835. var CannonJSPlugin = /** @class */ (function () {
  93836. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  93837. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  93838. if (iterations === void 0) { iterations = 10; }
  93839. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  93840. this.name = "CannonJSPlugin";
  93841. this._physicsMaterials = new Array();
  93842. this._fixedTimeStep = 1 / 60;
  93843. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  93844. this.BJSCANNON = CANNON;
  93845. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  93846. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  93847. this._tmpPosition = BABYLON.Vector3.Zero();
  93848. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  93849. this._tmpUnityRotation = new BABYLON.Quaternion();
  93850. if (!this.isSupported()) {
  93851. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  93852. return;
  93853. }
  93854. this._extendNamespace();
  93855. this.world = new this.BJSCANNON.World();
  93856. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  93857. this.world.solver.iterations = iterations;
  93858. }
  93859. CannonJSPlugin.prototype.setGravity = function (gravity) {
  93860. this.world.gravity.copy(gravity);
  93861. };
  93862. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  93863. this._fixedTimeStep = timeStep;
  93864. };
  93865. CannonJSPlugin.prototype.getTimeStep = function () {
  93866. return this._fixedTimeStep;
  93867. };
  93868. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  93869. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  93870. };
  93871. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93872. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93873. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93874. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  93875. };
  93876. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93877. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93878. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93879. impostor.physicsBody.applyForce(impulse, worldPoint);
  93880. };
  93881. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93882. //parent-child relationship. Does this impostor has a parent impostor?
  93883. if (impostor.parent) {
  93884. if (impostor.physicsBody) {
  93885. this.removePhysicsBody(impostor);
  93886. //TODO is that needed?
  93887. impostor.forceUpdate();
  93888. }
  93889. return;
  93890. }
  93891. //should a new body be created for this impostor?
  93892. if (impostor.isBodyInitRequired()) {
  93893. var shape = this._createShape(impostor);
  93894. //unregister events, if body is being changed
  93895. var oldBody = impostor.physicsBody;
  93896. if (oldBody) {
  93897. this.removePhysicsBody(impostor);
  93898. }
  93899. //create the body and material
  93900. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  93901. var bodyCreationObject = {
  93902. mass: impostor.getParam("mass"),
  93903. material: material
  93904. };
  93905. // A simple extend, in case native options were used.
  93906. var nativeOptions = impostor.getParam("nativeOptions");
  93907. for (var key in nativeOptions) {
  93908. if (nativeOptions.hasOwnProperty(key)) {
  93909. bodyCreationObject[key] = nativeOptions[key];
  93910. }
  93911. }
  93912. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  93913. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  93914. this.world.addEventListener("preStep", impostor.beforeStep);
  93915. this.world.addEventListener("postStep", impostor.afterStep);
  93916. impostor.physicsBody.addShape(shape);
  93917. this.world.add(impostor.physicsBody);
  93918. //try to keep the body moving in the right direction by taking old properties.
  93919. //Should be tested!
  93920. if (oldBody) {
  93921. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  93922. impostor.physicsBody[param].copy(oldBody[param]);
  93923. });
  93924. }
  93925. this._processChildMeshes(impostor);
  93926. }
  93927. //now update the body's transformation
  93928. this._updatePhysicsBodyTransformation(impostor);
  93929. };
  93930. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  93931. var _this = this;
  93932. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  93933. var currentRotation = mainImpostor.object.rotationQuaternion;
  93934. if (meshChildren.length) {
  93935. var processMesh = function (localPosition, mesh) {
  93936. if (!currentRotation || !mesh.rotationQuaternion) {
  93937. return;
  93938. }
  93939. var childImpostor = mesh.getPhysicsImpostor();
  93940. if (childImpostor) {
  93941. var parent = childImpostor.parent;
  93942. if (parent !== mainImpostor) {
  93943. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  93944. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  93945. if (childImpostor.physicsBody) {
  93946. _this.removePhysicsBody(childImpostor);
  93947. childImpostor.physicsBody = null;
  93948. }
  93949. childImpostor.parent = mainImpostor;
  93950. childImpostor.resetUpdateFlags();
  93951. 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));
  93952. //Add the mass of the children.
  93953. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  93954. }
  93955. }
  93956. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  93957. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  93958. };
  93959. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  93960. }
  93961. };
  93962. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93963. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  93964. this.world.removeEventListener("preStep", impostor.beforeStep);
  93965. this.world.removeEventListener("postStep", impostor.afterStep);
  93966. this.world.remove(impostor.physicsBody);
  93967. };
  93968. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93969. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93970. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93971. if (!mainBody || !connectedBody) {
  93972. return;
  93973. }
  93974. var constraint;
  93975. var jointData = impostorJoint.joint.jointData;
  93976. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  93977. var constraintData = {
  93978. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  93979. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  93980. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  93981. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  93982. maxForce: jointData.nativeParams.maxForce,
  93983. collideConnected: !!jointData.collision
  93984. };
  93985. switch (impostorJoint.joint.type) {
  93986. case BABYLON.PhysicsJoint.HingeJoint:
  93987. case BABYLON.PhysicsJoint.Hinge2Joint:
  93988. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  93989. break;
  93990. case BABYLON.PhysicsJoint.DistanceJoint:
  93991. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  93992. break;
  93993. case BABYLON.PhysicsJoint.SpringJoint:
  93994. var springData = jointData;
  93995. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  93996. restLength: springData.length,
  93997. stiffness: springData.stiffness,
  93998. damping: springData.damping,
  93999. localAnchorA: constraintData.pivotA,
  94000. localAnchorB: constraintData.pivotB
  94001. });
  94002. break;
  94003. case BABYLON.PhysicsJoint.LockJoint:
  94004. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  94005. break;
  94006. case BABYLON.PhysicsJoint.PointToPointJoint:
  94007. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94008. default:
  94009. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  94010. break;
  94011. }
  94012. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  94013. constraint.collideConnected = !!jointData.collision;
  94014. impostorJoint.joint.physicsJoint = constraint;
  94015. //don't add spring as constraint, as it is not one.
  94016. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94017. this.world.addConstraint(constraint);
  94018. }
  94019. else {
  94020. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  94021. constraint.applyForce();
  94022. };
  94023. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94024. }
  94025. };
  94026. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94027. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94028. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94029. }
  94030. else {
  94031. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94032. }
  94033. };
  94034. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94035. var index;
  94036. var mat;
  94037. for (index = 0; index < this._physicsMaterials.length; index++) {
  94038. mat = this._physicsMaterials[index];
  94039. if (mat.friction === friction && mat.restitution === restitution) {
  94040. return mat;
  94041. }
  94042. }
  94043. var currentMat = new this.BJSCANNON.Material(name);
  94044. currentMat.friction = friction;
  94045. currentMat.restitution = restitution;
  94046. this._physicsMaterials.push(currentMat);
  94047. return currentMat;
  94048. };
  94049. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94050. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94051. };
  94052. CannonJSPlugin.prototype._createShape = function (impostor) {
  94053. var object = impostor.object;
  94054. var returnValue;
  94055. var extendSize = impostor.getObjectExtendSize();
  94056. switch (impostor.type) {
  94057. case BABYLON.PhysicsImpostor.SphereImpostor:
  94058. var radiusX = extendSize.x;
  94059. var radiusY = extendSize.y;
  94060. var radiusZ = extendSize.z;
  94061. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94062. break;
  94063. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94064. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94065. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94066. break;
  94067. case BABYLON.PhysicsImpostor.BoxImpostor:
  94068. var box = extendSize.scale(0.5);
  94069. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94070. break;
  94071. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94072. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94073. returnValue = new this.BJSCANNON.Plane();
  94074. break;
  94075. case BABYLON.PhysicsImpostor.MeshImpostor:
  94076. // should transform the vertex data to world coordinates!!
  94077. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94078. var rawFaces = object.getIndices ? object.getIndices() : [];
  94079. if (!rawVerts)
  94080. return;
  94081. // get only scale! so the object could transform correctly.
  94082. var oldPosition = object.position.clone();
  94083. var oldRotation = object.rotation && object.rotation.clone();
  94084. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94085. object.position.copyFromFloats(0, 0, 0);
  94086. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94087. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94088. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94089. var transform = object.computeWorldMatrix(true);
  94090. // convert rawVerts to object space
  94091. var temp = new Array();
  94092. var index;
  94093. for (index = 0; index < rawVerts.length; index += 3) {
  94094. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94095. }
  94096. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94097. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94098. //now set back the transformation!
  94099. object.position.copyFrom(oldPosition);
  94100. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94101. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94102. break;
  94103. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94104. var oldPosition2 = object.position.clone();
  94105. var oldRotation2 = object.rotation && object.rotation.clone();
  94106. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94107. object.position.copyFromFloats(0, 0, 0);
  94108. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94109. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94110. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94111. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94112. returnValue = this._createHeightmap(object);
  94113. object.position.copyFrom(oldPosition2);
  94114. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94115. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94116. object.computeWorldMatrix(true);
  94117. break;
  94118. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94119. returnValue = new this.BJSCANNON.Particle();
  94120. break;
  94121. }
  94122. return returnValue;
  94123. };
  94124. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94125. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94126. var transform = object.computeWorldMatrix(true);
  94127. // convert rawVerts to object space
  94128. var temp = new Array();
  94129. var index;
  94130. for (index = 0; index < pos.length; index += 3) {
  94131. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94132. }
  94133. pos = temp;
  94134. var matrix = new Array();
  94135. //For now pointDepth will not be used and will be automatically calculated.
  94136. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94137. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94138. var boundingInfo = object.getBoundingInfo();
  94139. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94140. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94141. var elementSize = dim * 2 / arraySize;
  94142. for (var i = 0; i < pos.length; i = i + 3) {
  94143. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94144. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94145. var y = -pos[i + 2] + minY;
  94146. if (!matrix[x]) {
  94147. matrix[x] = [];
  94148. }
  94149. if (!matrix[x][z]) {
  94150. matrix[x][z] = y;
  94151. }
  94152. matrix[x][z] = Math.max(y, matrix[x][z]);
  94153. }
  94154. for (var x = 0; x <= arraySize; ++x) {
  94155. if (!matrix[x]) {
  94156. var loc = 1;
  94157. while (!matrix[(x + loc) % arraySize]) {
  94158. loc++;
  94159. }
  94160. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94161. //console.log("missing x", x);
  94162. }
  94163. for (var z = 0; z <= arraySize; ++z) {
  94164. if (!matrix[x][z]) {
  94165. var loc = 1;
  94166. var newValue;
  94167. while (newValue === undefined) {
  94168. newValue = matrix[x][(z + loc++) % arraySize];
  94169. }
  94170. matrix[x][z] = newValue;
  94171. }
  94172. }
  94173. }
  94174. var shape = new this.BJSCANNON.Heightfield(matrix, {
  94175. elementSize: elementSize
  94176. });
  94177. //For future reference, needed for body transformation
  94178. shape.minY = minY;
  94179. return shape;
  94180. };
  94181. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  94182. var object = impostor.object;
  94183. //make sure it is updated...
  94184. object.computeWorldMatrix && object.computeWorldMatrix(true);
  94185. // The delta between the mesh position and the mesh bounding box center
  94186. var bInfo = object.getBoundingInfo();
  94187. if (!bInfo)
  94188. return;
  94189. var center = impostor.getObjectCenter();
  94190. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  94191. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  94192. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  94193. this._tmpPosition.copyFrom(center);
  94194. var quaternion = object.rotationQuaternion;
  94195. if (!quaternion) {
  94196. return;
  94197. }
  94198. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  94199. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  94200. //-90 DEG in X, precalculated
  94201. quaternion = quaternion.multiply(this._minus90X);
  94202. //Invert! (Precalculated, 90 deg in X)
  94203. //No need to clone. this will never change.
  94204. impostor.setDeltaRotation(this._plus90X);
  94205. }
  94206. //If it is a heightfield, if should be centered.
  94207. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  94208. var mesh = object;
  94209. var boundingInfo = mesh.getBoundingInfo();
  94210. //calculate the correct body position:
  94211. var rotationQuaternion = mesh.rotationQuaternion;
  94212. mesh.rotationQuaternion = this._tmpUnityRotation;
  94213. mesh.computeWorldMatrix(true);
  94214. //get original center with no rotation
  94215. var c = center.clone();
  94216. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  94217. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  94218. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  94219. mesh.setPreTransformMatrix(p);
  94220. mesh.computeWorldMatrix(true);
  94221. //calculate the translation
  94222. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  94223. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  94224. //add it inverted to the delta
  94225. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  94226. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  94227. //rotation is back
  94228. mesh.rotationQuaternion = rotationQuaternion;
  94229. mesh.setPreTransformMatrix(oldPivot);
  94230. mesh.computeWorldMatrix(true);
  94231. }
  94232. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  94233. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  94234. //this._tmpPosition.copyFrom(object.position);
  94235. }
  94236. impostor.setDeltaPosition(this._tmpDeltaPosition);
  94237. //Now update the impostor object
  94238. impostor.physicsBody.position.copy(this._tmpPosition);
  94239. impostor.physicsBody.quaternion.copy(quaternion);
  94240. };
  94241. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  94242. impostor.object.position.copyFrom(impostor.physicsBody.position);
  94243. if (impostor.object.rotationQuaternion) {
  94244. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  94245. }
  94246. };
  94247. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  94248. impostor.physicsBody.position.copy(newPosition);
  94249. impostor.physicsBody.quaternion.copy(newRotation);
  94250. };
  94251. CannonJSPlugin.prototype.isSupported = function () {
  94252. return this.BJSCANNON !== undefined;
  94253. };
  94254. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  94255. impostor.physicsBody.velocity.copy(velocity);
  94256. };
  94257. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  94258. impostor.physicsBody.angularVelocity.copy(velocity);
  94259. };
  94260. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  94261. var v = impostor.physicsBody.velocity;
  94262. if (!v) {
  94263. return null;
  94264. }
  94265. return new BABYLON.Vector3(v.x, v.y, v.z);
  94266. };
  94267. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  94268. var v = impostor.physicsBody.angularVelocity;
  94269. if (!v) {
  94270. return null;
  94271. }
  94272. return new BABYLON.Vector3(v.x, v.y, v.z);
  94273. };
  94274. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  94275. impostor.physicsBody.mass = mass;
  94276. impostor.physicsBody.updateMassProperties();
  94277. };
  94278. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  94279. return impostor.physicsBody.mass;
  94280. };
  94281. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  94282. return impostor.physicsBody.material.friction;
  94283. };
  94284. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  94285. impostor.physicsBody.material.friction = friction;
  94286. };
  94287. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  94288. return impostor.physicsBody.material.restitution;
  94289. };
  94290. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  94291. impostor.physicsBody.material.restitution = restitution;
  94292. };
  94293. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  94294. impostor.physicsBody.sleep();
  94295. };
  94296. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  94297. impostor.physicsBody.wakeUp();
  94298. };
  94299. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  94300. joint.physicsJoint.distance = maxDistance;
  94301. };
  94302. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  94303. // if (!motorIndex) {
  94304. // joint.physicsJoint.enableMotor();
  94305. // }
  94306. // }
  94307. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  94308. // if (!motorIndex) {
  94309. // joint.physicsJoint.disableMotor();
  94310. // }
  94311. // }
  94312. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  94313. if (!motorIndex) {
  94314. joint.physicsJoint.enableMotor();
  94315. joint.physicsJoint.setMotorSpeed(speed);
  94316. if (maxForce) {
  94317. this.setLimit(joint, maxForce);
  94318. }
  94319. }
  94320. };
  94321. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  94322. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  94323. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  94324. };
  94325. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  94326. var body = impostor.physicsBody;
  94327. mesh.position.x = body.position.x;
  94328. mesh.position.y = body.position.y;
  94329. mesh.position.z = body.position.z;
  94330. if (mesh.rotationQuaternion) {
  94331. mesh.rotationQuaternion.x = body.quaternion.x;
  94332. mesh.rotationQuaternion.y = body.quaternion.y;
  94333. mesh.rotationQuaternion.z = body.quaternion.z;
  94334. mesh.rotationQuaternion.w = body.quaternion.w;
  94335. }
  94336. };
  94337. CannonJSPlugin.prototype.getRadius = function (impostor) {
  94338. var shape = impostor.physicsBody.shapes[0];
  94339. return shape.boundingSphereRadius;
  94340. };
  94341. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  94342. var shape = impostor.physicsBody.shapes[0];
  94343. result.x = shape.halfExtents.x * 2;
  94344. result.y = shape.halfExtents.y * 2;
  94345. result.z = shape.halfExtents.z * 2;
  94346. };
  94347. CannonJSPlugin.prototype.dispose = function () {
  94348. };
  94349. CannonJSPlugin.prototype._extendNamespace = function () {
  94350. //this will force cannon to execute at least one step when using interpolation
  94351. var step_tmp1 = new this.BJSCANNON.Vec3();
  94352. var Engine = this.BJSCANNON;
  94353. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  94354. maxSubSteps = maxSubSteps || 10;
  94355. timeSinceLastCalled = timeSinceLastCalled || 0;
  94356. if (timeSinceLastCalled === 0) {
  94357. this.internalStep(dt);
  94358. this.time += dt;
  94359. }
  94360. else {
  94361. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  94362. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  94363. var t0 = performance.now();
  94364. for (var i = 0; i !== internalSteps; i++) {
  94365. this.internalStep(dt);
  94366. if (performance.now() - t0 > dt * 1000) {
  94367. break;
  94368. }
  94369. }
  94370. this.time += timeSinceLastCalled;
  94371. var h = this.time % dt;
  94372. var h_div_dt = h / dt;
  94373. var interpvelo = step_tmp1;
  94374. var bodies = this.bodies;
  94375. for (var j = 0; j !== bodies.length; j++) {
  94376. var b = bodies[j];
  94377. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  94378. b.position.vsub(b.previousPosition, interpvelo);
  94379. interpvelo.scale(h_div_dt, interpvelo);
  94380. b.position.vadd(interpvelo, b.interpolatedPosition);
  94381. }
  94382. else {
  94383. b.interpolatedPosition.copy(b.position);
  94384. b.interpolatedQuaternion.copy(b.quaternion);
  94385. }
  94386. }
  94387. }
  94388. };
  94389. };
  94390. return CannonJSPlugin;
  94391. }());
  94392. BABYLON.CannonJSPlugin = CannonJSPlugin;
  94393. })(BABYLON || (BABYLON = {}));
  94394. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  94395. var BABYLON;
  94396. (function (BABYLON) {
  94397. /** @hidden */
  94398. var OimoJSPlugin = /** @class */ (function () {
  94399. function OimoJSPlugin(iterations) {
  94400. this.name = "OimoJSPlugin";
  94401. this._tmpImpostorsArray = [];
  94402. this._tmpPositionVector = BABYLON.Vector3.Zero();
  94403. this.BJSOIMO = OIMO;
  94404. this.world = new this.BJSOIMO.World({
  94405. iterations: iterations
  94406. });
  94407. this.world.clear();
  94408. }
  94409. OimoJSPlugin.prototype.setGravity = function (gravity) {
  94410. this.world.gravity.copy(gravity);
  94411. };
  94412. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  94413. this.world.timeStep = timeStep;
  94414. };
  94415. OimoJSPlugin.prototype.getTimeStep = function () {
  94416. return this.world.timeStep;
  94417. };
  94418. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  94419. var _this = this;
  94420. impostors.forEach(function (impostor) {
  94421. impostor.beforeStep();
  94422. });
  94423. this.world.step();
  94424. impostors.forEach(function (impostor) {
  94425. impostor.afterStep();
  94426. //update the ordered impostors array
  94427. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  94428. });
  94429. //check for collisions
  94430. var contact = this.world.contacts;
  94431. while (contact !== null) {
  94432. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  94433. contact = contact.next;
  94434. continue;
  94435. }
  94436. //is this body colliding with any other? get the impostor
  94437. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  94438. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  94439. if (!mainImpostor || !collidingImpostor) {
  94440. contact = contact.next;
  94441. continue;
  94442. }
  94443. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  94444. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  94445. contact = contact.next;
  94446. }
  94447. };
  94448. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94449. var mass = impostor.physicsBody.mass;
  94450. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  94451. };
  94452. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94453. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  94454. this.applyImpulse(impostor, force, contactPoint);
  94455. };
  94456. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94457. var _this = this;
  94458. //parent-child relationship. Does this impostor has a parent impostor?
  94459. if (impostor.parent) {
  94460. if (impostor.physicsBody) {
  94461. this.removePhysicsBody(impostor);
  94462. //TODO is that needed?
  94463. impostor.forceUpdate();
  94464. }
  94465. return;
  94466. }
  94467. if (impostor.isBodyInitRequired()) {
  94468. var bodyConfig = {
  94469. name: impostor.uniqueId,
  94470. //Oimo must have mass, also for static objects.
  94471. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  94472. size: [],
  94473. type: [],
  94474. pos: [],
  94475. posShape: [],
  94476. rot: [],
  94477. rotShape: [],
  94478. move: impostor.getParam("mass") !== 0,
  94479. density: impostor.getParam("mass"),
  94480. friction: impostor.getParam("friction"),
  94481. restitution: impostor.getParam("restitution"),
  94482. //Supporting older versions of Oimo
  94483. world: this.world
  94484. };
  94485. var impostors = [impostor];
  94486. var addToArray = function (parent) {
  94487. if (!parent.getChildMeshes)
  94488. return;
  94489. parent.getChildMeshes().forEach(function (m) {
  94490. if (m.physicsImpostor) {
  94491. impostors.push(m.physicsImpostor);
  94492. //m.physicsImpostor._init();
  94493. }
  94494. });
  94495. };
  94496. addToArray(impostor.object);
  94497. var checkWithEpsilon_1 = function (value) {
  94498. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  94499. };
  94500. var globalQuaternion_1 = new BABYLON.Quaternion();
  94501. impostors.forEach(function (i) {
  94502. if (!i.object.rotationQuaternion) {
  94503. return;
  94504. }
  94505. //get the correct bounding box
  94506. var oldQuaternion = i.object.rotationQuaternion;
  94507. globalQuaternion_1 = oldQuaternion.clone();
  94508. var rot = oldQuaternion.toEulerAngles();
  94509. var extendSize = i.getObjectExtendSize();
  94510. var radToDeg = 57.295779513082320876;
  94511. if (i === impostor) {
  94512. var center = impostor.getObjectCenter();
  94513. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  94514. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  94515. //Can also use Array.prototype.push.apply
  94516. bodyConfig.pos.push(center.x);
  94517. bodyConfig.pos.push(center.y);
  94518. bodyConfig.pos.push(center.z);
  94519. bodyConfig.posShape.push(0, 0, 0);
  94520. //tmp solution
  94521. bodyConfig.rot.push(0);
  94522. bodyConfig.rot.push(0);
  94523. bodyConfig.rot.push(0);
  94524. bodyConfig.rotShape.push(0, 0, 0);
  94525. }
  94526. else {
  94527. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  94528. bodyConfig.posShape.push(localPosition.x);
  94529. bodyConfig.posShape.push(localPosition.y);
  94530. bodyConfig.posShape.push(localPosition.z);
  94531. bodyConfig.pos.push(0, 0, 0);
  94532. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  94533. bodyConfig.rot.push(0);
  94534. bodyConfig.rot.push(0);
  94535. bodyConfig.rot.push(0);
  94536. bodyConfig.rotShape.push(rot.x * radToDeg);
  94537. bodyConfig.rotShape.push(rot.y * radToDeg);
  94538. bodyConfig.rotShape.push(rot.z * radToDeg);
  94539. }
  94540. // register mesh
  94541. switch (i.type) {
  94542. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94543. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  94544. case BABYLON.PhysicsImpostor.SphereImpostor:
  94545. var radiusX = extendSize.x;
  94546. var radiusY = extendSize.y;
  94547. var radiusZ = extendSize.z;
  94548. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  94549. bodyConfig.type.push('sphere');
  94550. //due to the way oimo works with compounds, add 3 times
  94551. bodyConfig.size.push(size);
  94552. bodyConfig.size.push(size);
  94553. bodyConfig.size.push(size);
  94554. break;
  94555. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94556. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  94557. var sizeY = checkWithEpsilon_1(extendSize.y);
  94558. bodyConfig.type.push('cylinder');
  94559. bodyConfig.size.push(sizeX);
  94560. bodyConfig.size.push(sizeY);
  94561. //due to the way oimo works with compounds, add one more value.
  94562. bodyConfig.size.push(sizeY);
  94563. break;
  94564. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94565. case BABYLON.PhysicsImpostor.BoxImpostor:
  94566. default:
  94567. var sizeX = checkWithEpsilon_1(extendSize.x);
  94568. var sizeY = checkWithEpsilon_1(extendSize.y);
  94569. var sizeZ = checkWithEpsilon_1(extendSize.z);
  94570. bodyConfig.type.push('box');
  94571. //if (i === impostor) {
  94572. bodyConfig.size.push(sizeX);
  94573. bodyConfig.size.push(sizeY);
  94574. bodyConfig.size.push(sizeZ);
  94575. //} else {
  94576. // bodyConfig.size.push(0,0,0);
  94577. //}
  94578. break;
  94579. }
  94580. //actually not needed, but hey...
  94581. i.object.rotationQuaternion = oldQuaternion;
  94582. });
  94583. impostor.physicsBody = this.world.add(bodyConfig);
  94584. // set the quaternion, ignoring the previously defined (euler) rotation
  94585. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  94586. // update with delta 0, so the body will reveive the new rotation.
  94587. impostor.physicsBody.updatePosition(0);
  94588. }
  94589. else {
  94590. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  94591. }
  94592. impostor.setDeltaPosition(this._tmpPositionVector);
  94593. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  94594. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  94595. };
  94596. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94597. //impostor.physicsBody.dispose();
  94598. //Same as : (older oimo versions)
  94599. this.world.removeRigidBody(impostor.physicsBody);
  94600. };
  94601. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94602. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94603. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94604. if (!mainBody || !connectedBody) {
  94605. return;
  94606. }
  94607. var jointData = impostorJoint.joint.jointData;
  94608. var options = jointData.nativeParams || {};
  94609. var type;
  94610. var nativeJointData = {
  94611. body1: mainBody,
  94612. body2: connectedBody,
  94613. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  94614. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  94615. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  94616. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  94617. min: options.min,
  94618. max: options.max,
  94619. collision: options.collision || jointData.collision,
  94620. spring: options.spring,
  94621. //supporting older version of Oimo
  94622. world: this.world
  94623. };
  94624. switch (impostorJoint.joint.type) {
  94625. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94626. type = "jointBall";
  94627. break;
  94628. case BABYLON.PhysicsJoint.SpringJoint:
  94629. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  94630. var springData = jointData;
  94631. nativeJointData.min = springData.length || nativeJointData.min;
  94632. //Max should also be set, just make sure it is at least min
  94633. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  94634. case BABYLON.PhysicsJoint.DistanceJoint:
  94635. type = "jointDistance";
  94636. nativeJointData.max = jointData.maxDistance;
  94637. break;
  94638. case BABYLON.PhysicsJoint.PrismaticJoint:
  94639. type = "jointPrisme";
  94640. break;
  94641. case BABYLON.PhysicsJoint.SliderJoint:
  94642. type = "jointSlide";
  94643. break;
  94644. case BABYLON.PhysicsJoint.WheelJoint:
  94645. type = "jointWheel";
  94646. break;
  94647. case BABYLON.PhysicsJoint.HingeJoint:
  94648. default:
  94649. type = "jointHinge";
  94650. break;
  94651. }
  94652. nativeJointData.type = type;
  94653. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  94654. };
  94655. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94656. //Bug in Oimo prevents us from disposing a joint in the playground
  94657. //joint.joint.physicsJoint.dispose();
  94658. //So we will bruteforce it!
  94659. try {
  94660. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  94661. }
  94662. catch (e) {
  94663. BABYLON.Tools.Warn(e);
  94664. }
  94665. };
  94666. OimoJSPlugin.prototype.isSupported = function () {
  94667. return this.BJSOIMO !== undefined;
  94668. };
  94669. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  94670. if (!impostor.physicsBody.sleeping) {
  94671. //TODO check that
  94672. /*if (impostor.physicsBody.shapes.next) {
  94673. var parentShape = this._getLastShape(impostor.physicsBody);
  94674. impostor.object.position.copyFrom(parentShape.position);
  94675. console.log(parentShape.position);
  94676. } else {*/
  94677. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  94678. //}
  94679. if (impostor.object.rotationQuaternion) {
  94680. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  94681. }
  94682. }
  94683. };
  94684. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  94685. var body = impostor.physicsBody;
  94686. body.position.copy(newPosition);
  94687. body.orientation.copy(newRotation);
  94688. body.syncShapes();
  94689. body.awake();
  94690. };
  94691. /*private _getLastShape(body: any): any {
  94692. var lastShape = body.shapes;
  94693. while (lastShape.next) {
  94694. lastShape = lastShape.next;
  94695. }
  94696. return lastShape;
  94697. }*/
  94698. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  94699. impostor.physicsBody.linearVelocity.copy(velocity);
  94700. };
  94701. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  94702. impostor.physicsBody.angularVelocity.copy(velocity);
  94703. };
  94704. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  94705. var v = impostor.physicsBody.linearVelocity;
  94706. if (!v) {
  94707. return null;
  94708. }
  94709. return new BABYLON.Vector3(v.x, v.y, v.z);
  94710. };
  94711. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  94712. var v = impostor.physicsBody.angularVelocity;
  94713. if (!v) {
  94714. return null;
  94715. }
  94716. return new BABYLON.Vector3(v.x, v.y, v.z);
  94717. };
  94718. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  94719. var staticBody = mass === 0;
  94720. //this will actually set the body's density and not its mass.
  94721. //But this is how oimo treats the mass variable.
  94722. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  94723. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  94724. };
  94725. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  94726. return impostor.physicsBody.shapes.density;
  94727. };
  94728. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  94729. return impostor.physicsBody.shapes.friction;
  94730. };
  94731. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  94732. impostor.physicsBody.shapes.friction = friction;
  94733. };
  94734. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  94735. return impostor.physicsBody.shapes.restitution;
  94736. };
  94737. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  94738. impostor.physicsBody.shapes.restitution = restitution;
  94739. };
  94740. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  94741. impostor.physicsBody.sleep();
  94742. };
  94743. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  94744. impostor.physicsBody.awake();
  94745. };
  94746. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  94747. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  94748. if (minDistance !== void 0) {
  94749. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  94750. }
  94751. };
  94752. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  94753. //TODO separate rotational and transational motors.
  94754. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  94755. if (motor) {
  94756. motor.setMotor(speed, maxForce);
  94757. }
  94758. };
  94759. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  94760. //TODO separate rotational and transational motors.
  94761. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  94762. if (motor) {
  94763. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  94764. }
  94765. };
  94766. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  94767. var body = impostor.physicsBody;
  94768. mesh.position.x = body.position.x;
  94769. mesh.position.y = body.position.y;
  94770. mesh.position.z = body.position.z;
  94771. if (mesh.rotationQuaternion) {
  94772. mesh.rotationQuaternion.x = body.orientation.x;
  94773. mesh.rotationQuaternion.y = body.orientation.y;
  94774. mesh.rotationQuaternion.z = body.orientation.z;
  94775. mesh.rotationQuaternion.w = body.orientation.s;
  94776. }
  94777. };
  94778. OimoJSPlugin.prototype.getRadius = function (impostor) {
  94779. return impostor.physicsBody.shapes.radius;
  94780. };
  94781. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  94782. var shape = impostor.physicsBody.shapes;
  94783. result.x = shape.halfWidth * 2;
  94784. result.y = shape.halfHeight * 2;
  94785. result.z = shape.halfDepth * 2;
  94786. };
  94787. OimoJSPlugin.prototype.dispose = function () {
  94788. this.world.clear();
  94789. };
  94790. return OimoJSPlugin;
  94791. }());
  94792. BABYLON.OimoJSPlugin = OimoJSPlugin;
  94793. })(BABYLON || (BABYLON = {}));
  94794. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  94795. var BABYLON;
  94796. (function (BABYLON) {
  94797. /**
  94798. * Gets the current physics engine
  94799. * @returns a IPhysicsEngine or null if none attached
  94800. */
  94801. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  94802. return this._physicsEngine;
  94803. };
  94804. /**
  94805. * Enables physics to the current scene
  94806. * @param gravity defines the scene's gravity for the physics engine
  94807. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  94808. * @return a boolean indicating if the physics engine was initialized
  94809. */
  94810. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  94811. if (gravity === void 0) { gravity = null; }
  94812. if (this._physicsEngine) {
  94813. return true;
  94814. }
  94815. // Register the component to the scene
  94816. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  94817. if (!component) {
  94818. component = new PhysicsEngineSceneComponent(this);
  94819. this._addComponent(component);
  94820. }
  94821. try {
  94822. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  94823. return true;
  94824. }
  94825. catch (e) {
  94826. BABYLON.Tools.Error(e.message);
  94827. return false;
  94828. }
  94829. };
  94830. /**
  94831. * Disables and disposes the physics engine associated with the scene
  94832. */
  94833. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  94834. if (!this._physicsEngine) {
  94835. return;
  94836. }
  94837. this._physicsEngine.dispose();
  94838. this._physicsEngine = null;
  94839. };
  94840. /**
  94841. * Gets a boolean indicating if there is an active physics engine
  94842. * @returns a boolean indicating if there is an active physics engine
  94843. */
  94844. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  94845. return this._physicsEngine !== undefined;
  94846. };
  94847. /**
  94848. * Deletes a physics compound impostor
  94849. * @param compound defines the compound to delete
  94850. */
  94851. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  94852. var mesh = compound.parts[0].mesh;
  94853. if (mesh.physicsImpostor) {
  94854. mesh.physicsImpostor.dispose( /*true*/);
  94855. mesh.physicsImpostor = null;
  94856. }
  94857. };
  94858. /** @hidden */
  94859. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  94860. if (this._physicsEngine) {
  94861. this.onBeforePhysicsObservable.notifyObservers(this);
  94862. this._physicsEngine._step(step / 1000);
  94863. this.onAfterPhysicsObservable.notifyObservers(this);
  94864. }
  94865. };
  94866. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  94867. get: function () {
  94868. return this._physicsImpostor;
  94869. },
  94870. set: function (value) {
  94871. var _this = this;
  94872. if (this._physicsImpostor === value) {
  94873. return;
  94874. }
  94875. if (this._disposePhysicsObserver) {
  94876. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  94877. }
  94878. this._physicsImpostor = value;
  94879. if (value) {
  94880. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  94881. // Physics
  94882. if (_this.physicsImpostor) {
  94883. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  94884. _this.physicsImpostor = null;
  94885. }
  94886. });
  94887. }
  94888. },
  94889. enumerable: true,
  94890. configurable: true
  94891. });
  94892. /**
  94893. * Gets the current physics impostor
  94894. * @see http://doc.babylonjs.com/features/physics_engine
  94895. * @returns a physics impostor or null
  94896. */
  94897. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  94898. return this.physicsImpostor;
  94899. };
  94900. /**
  94901. * Apply a physic impulse to the mesh
  94902. * @param force defines the force to apply
  94903. * @param contactPoint defines where to apply the force
  94904. * @returns the current mesh
  94905. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  94906. */
  94907. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  94908. if (!this.physicsImpostor) {
  94909. return this;
  94910. }
  94911. this.physicsImpostor.applyImpulse(force, contactPoint);
  94912. return this;
  94913. };
  94914. /**
  94915. * Creates a physic joint between two meshes
  94916. * @param otherMesh defines the other mesh to use
  94917. * @param pivot1 defines the pivot to use on this mesh
  94918. * @param pivot2 defines the pivot to use on the other mesh
  94919. * @param options defines additional options (can be plugin dependent)
  94920. * @returns the current mesh
  94921. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  94922. */
  94923. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  94924. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  94925. return this;
  94926. }
  94927. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  94928. mainPivot: pivot1,
  94929. connectedPivot: pivot2,
  94930. nativeParams: options
  94931. });
  94932. return this;
  94933. };
  94934. /**
  94935. * Defines the physics engine scene component responsible to manage a physics engine
  94936. */
  94937. var PhysicsEngineSceneComponent = /** @class */ (function () {
  94938. /**
  94939. * Creates a new instance of the component for the given scene
  94940. * @param scene Defines the scene to register the component in
  94941. */
  94942. function PhysicsEngineSceneComponent(scene) {
  94943. var _this = this;
  94944. /**
  94945. * The component name helpful to identify the component in the list of scene components.
  94946. */
  94947. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  94948. this.scene = scene;
  94949. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  94950. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  94951. // Replace the function used to get the deterministic frame time
  94952. this.scene.getDeterministicFrameTime = function () {
  94953. if (_this.scene._physicsEngine) {
  94954. return _this.scene._physicsEngine.getTimeStep() * 1000;
  94955. }
  94956. return 1000.0 / 60.0;
  94957. };
  94958. }
  94959. /**
  94960. * Registers the component in a given scene
  94961. */
  94962. PhysicsEngineSceneComponent.prototype.register = function () {
  94963. };
  94964. /**
  94965. * Rebuilds the elements related to this component in case of
  94966. * context lost for instance.
  94967. */
  94968. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  94969. // Nothing to do for this component
  94970. };
  94971. /**
  94972. * Disposes the component and the associated ressources
  94973. */
  94974. PhysicsEngineSceneComponent.prototype.dispose = function () {
  94975. this.scene.onBeforePhysicsObservable.clear();
  94976. this.scene.onAfterPhysicsObservable.clear();
  94977. if (this.scene._physicsEngine) {
  94978. this.scene.disablePhysicsEngine();
  94979. }
  94980. };
  94981. return PhysicsEngineSceneComponent;
  94982. }());
  94983. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  94984. })(BABYLON || (BABYLON = {}));
  94985. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  94986. var BABYLON;
  94987. (function (BABYLON) {
  94988. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  94989. // All values and structures referenced from:
  94990. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  94991. var DDS_MAGIC = 0x20534444;
  94992. var
  94993. //DDSD_CAPS = 0x1,
  94994. //DDSD_HEIGHT = 0x2,
  94995. //DDSD_WIDTH = 0x4,
  94996. //DDSD_PITCH = 0x8,
  94997. //DDSD_PIXELFORMAT = 0x1000,
  94998. DDSD_MIPMAPCOUNT = 0x20000;
  94999. //DDSD_LINEARSIZE = 0x80000,
  95000. //DDSD_DEPTH = 0x800000;
  95001. // var DDSCAPS_COMPLEX = 0x8,
  95002. // DDSCAPS_MIPMAP = 0x400000,
  95003. // DDSCAPS_TEXTURE = 0x1000;
  95004. var DDSCAPS2_CUBEMAP = 0x200;
  95005. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  95006. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  95007. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  95008. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  95009. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  95010. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  95011. // DDSCAPS2_VOLUME = 0x200000;
  95012. var
  95013. //DDPF_ALPHAPIXELS = 0x1,
  95014. //DDPF_ALPHA = 0x2,
  95015. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  95016. //DDPF_YUV = 0x200,
  95017. DDPF_LUMINANCE = 0x20000;
  95018. function FourCCToInt32(value) {
  95019. return value.charCodeAt(0) +
  95020. (value.charCodeAt(1) << 8) +
  95021. (value.charCodeAt(2) << 16) +
  95022. (value.charCodeAt(3) << 24);
  95023. }
  95024. function Int32ToFourCC(value) {
  95025. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  95026. }
  95027. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95028. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95029. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95030. var FOURCC_DX10 = FourCCToInt32("DX10");
  95031. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95032. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95033. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95034. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95035. var headerLengthInt = 31; // The header length in 32 bit ints
  95036. // Offsets into the header array
  95037. var off_magic = 0;
  95038. var off_size = 1;
  95039. var off_flags = 2;
  95040. var off_height = 3;
  95041. var off_width = 4;
  95042. var off_mipmapCount = 7;
  95043. var off_pfFlags = 20;
  95044. var off_pfFourCC = 21;
  95045. var off_RGBbpp = 22;
  95046. var off_RMask = 23;
  95047. var off_GMask = 24;
  95048. var off_BMask = 25;
  95049. var off_AMask = 26;
  95050. // var off_caps1 = 27;
  95051. var off_caps2 = 28;
  95052. // var off_caps3 = 29;
  95053. // var off_caps4 = 30;
  95054. var off_dxgiFormat = 32;
  95055. ;
  95056. /**
  95057. * Class used to provide DDS decompression tools
  95058. */
  95059. var DDSTools = /** @class */ (function () {
  95060. function DDSTools() {
  95061. }
  95062. /**
  95063. * Gets DDS information from an array buffer
  95064. * @param arrayBuffer defines the array buffer to read data from
  95065. * @returns the DDS information
  95066. */
  95067. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95068. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95069. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95070. var mipmapCount = 1;
  95071. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95072. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95073. }
  95074. var fourCC = header[off_pfFourCC];
  95075. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95076. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95077. switch (fourCC) {
  95078. case FOURCC_D3DFMT_R16G16B16A16F:
  95079. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95080. break;
  95081. case FOURCC_D3DFMT_R32G32B32A32F:
  95082. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95083. break;
  95084. case FOURCC_DX10:
  95085. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95086. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95087. break;
  95088. }
  95089. }
  95090. return {
  95091. width: header[off_width],
  95092. height: header[off_height],
  95093. mipmapCount: mipmapCount,
  95094. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95095. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95096. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95097. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95098. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95099. dxgiFormat: dxgiFormat,
  95100. textureType: textureType
  95101. };
  95102. };
  95103. DDSTools._ToHalfFloat = function (value) {
  95104. if (!DDSTools._FloatView) {
  95105. DDSTools._FloatView = new Float32Array(1);
  95106. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95107. }
  95108. DDSTools._FloatView[0] = value;
  95109. var x = DDSTools._Int32View[0];
  95110. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95111. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95112. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95113. /* If zero, or denormal, or exponent underflows too much for a denormal
  95114. * half, return signed zero. */
  95115. if (e < 103) {
  95116. return bits;
  95117. }
  95118. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95119. if (e > 142) {
  95120. bits |= 0x7c00;
  95121. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95122. * not Inf, so make sure we set one mantissa bit too. */
  95123. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95124. return bits;
  95125. }
  95126. /* If exponent underflows but not too much, return a denormal */
  95127. if (e < 113) {
  95128. m |= 0x0800;
  95129. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95130. * to 1, which is OK. */
  95131. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95132. return bits;
  95133. }
  95134. bits |= ((e - 112) << 10) | (m >> 1);
  95135. bits += m & 1;
  95136. return bits;
  95137. };
  95138. DDSTools._FromHalfFloat = function (value) {
  95139. var s = (value & 0x8000) >> 15;
  95140. var e = (value & 0x7C00) >> 10;
  95141. var f = value & 0x03FF;
  95142. if (e === 0) {
  95143. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95144. }
  95145. else if (e == 0x1F) {
  95146. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95147. }
  95148. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95149. };
  95150. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95151. var destArray = new Float32Array(dataLength);
  95152. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95153. var index = 0;
  95154. for (var y = 0; y < height; y++) {
  95155. for (var x = 0; x < width; x++) {
  95156. var srcPos = (x + y * width) * 4;
  95157. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95158. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95159. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95160. if (DDSTools.StoreLODInAlphaChannel) {
  95161. destArray[index + 3] = lod;
  95162. }
  95163. else {
  95164. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95165. }
  95166. index += 4;
  95167. }
  95168. }
  95169. return destArray;
  95170. };
  95171. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95172. if (DDSTools.StoreLODInAlphaChannel) {
  95173. var destArray = new Uint16Array(dataLength);
  95174. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95175. var index = 0;
  95176. for (var y = 0; y < height; y++) {
  95177. for (var x = 0; x < width; x++) {
  95178. var srcPos = (x + y * width) * 4;
  95179. destArray[index] = srcData[srcPos];
  95180. destArray[index + 1] = srcData[srcPos + 1];
  95181. destArray[index + 2] = srcData[srcPos + 2];
  95182. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  95183. index += 4;
  95184. }
  95185. }
  95186. return destArray;
  95187. }
  95188. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  95189. };
  95190. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95191. if (DDSTools.StoreLODInAlphaChannel) {
  95192. var destArray = new Float32Array(dataLength);
  95193. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95194. var index = 0;
  95195. for (var y = 0; y < height; y++) {
  95196. for (var x = 0; x < width; x++) {
  95197. var srcPos = (x + y * width) * 4;
  95198. destArray[index] = srcData[srcPos];
  95199. destArray[index + 1] = srcData[srcPos + 1];
  95200. destArray[index + 2] = srcData[srcPos + 2];
  95201. destArray[index + 3] = lod;
  95202. index += 4;
  95203. }
  95204. }
  95205. return destArray;
  95206. }
  95207. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  95208. };
  95209. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95210. var destArray = new Uint8Array(dataLength);
  95211. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95212. var index = 0;
  95213. for (var y = 0; y < height; y++) {
  95214. for (var x = 0; x < width; x++) {
  95215. var srcPos = (x + y * width) * 4;
  95216. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  95217. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  95218. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  95219. if (DDSTools.StoreLODInAlphaChannel) {
  95220. destArray[index + 3] = lod;
  95221. }
  95222. else {
  95223. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  95224. }
  95225. index += 4;
  95226. }
  95227. }
  95228. return destArray;
  95229. };
  95230. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95231. var destArray = new Uint8Array(dataLength);
  95232. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95233. var index = 0;
  95234. for (var y = 0; y < height; y++) {
  95235. for (var x = 0; x < width; x++) {
  95236. var srcPos = (x + y * width) * 4;
  95237. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  95238. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  95239. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  95240. if (DDSTools.StoreLODInAlphaChannel) {
  95241. destArray[index + 3] = lod;
  95242. }
  95243. else {
  95244. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  95245. }
  95246. index += 4;
  95247. }
  95248. }
  95249. return destArray;
  95250. };
  95251. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  95252. var byteArray = new Uint8Array(dataLength);
  95253. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95254. var index = 0;
  95255. for (var y = 0; y < height; y++) {
  95256. for (var x = 0; x < width; x++) {
  95257. var srcPos = (x + y * width) * 4;
  95258. byteArray[index] = srcData[srcPos + rOffset];
  95259. byteArray[index + 1] = srcData[srcPos + gOffset];
  95260. byteArray[index + 2] = srcData[srcPos + bOffset];
  95261. byteArray[index + 3] = srcData[srcPos + aOffset];
  95262. index += 4;
  95263. }
  95264. }
  95265. return byteArray;
  95266. };
  95267. DDSTools._ExtractLongWordOrder = function (value) {
  95268. if (value === 0 || value === 255 || value === -16777216) {
  95269. return 0;
  95270. }
  95271. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  95272. };
  95273. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  95274. var byteArray = new Uint8Array(dataLength);
  95275. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95276. var index = 0;
  95277. for (var y = 0; y < height; y++) {
  95278. for (var x = 0; x < width; x++) {
  95279. var srcPos = (x + y * width) * 3;
  95280. byteArray[index] = srcData[srcPos + rOffset];
  95281. byteArray[index + 1] = srcData[srcPos + gOffset];
  95282. byteArray[index + 2] = srcData[srcPos + bOffset];
  95283. index += 3;
  95284. }
  95285. }
  95286. return byteArray;
  95287. };
  95288. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  95289. var byteArray = new Uint8Array(dataLength);
  95290. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  95291. var index = 0;
  95292. for (var y = 0; y < height; y++) {
  95293. for (var x = 0; x < width; x++) {
  95294. var srcPos = (x + y * width);
  95295. byteArray[index] = srcData[srcPos];
  95296. index++;
  95297. }
  95298. }
  95299. return byteArray;
  95300. };
  95301. /**
  95302. * Uploads DDS Levels to a Babylon Texture
  95303. * @hidden
  95304. */
  95305. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  95306. if (lodIndex === void 0) { lodIndex = -1; }
  95307. var sphericalPolynomialFaces = null;
  95308. if (info.sphericalPolynomial) {
  95309. sphericalPolynomialFaces = new Array();
  95310. }
  95311. var ext = engine.getCaps().s3tc;
  95312. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95313. var fourCC, width, height, dataLength = 0, dataOffset;
  95314. var byteArray, mipmapCount, mip;
  95315. var internalCompressedFormat = 0;
  95316. var blockBytes = 1;
  95317. if (header[off_magic] !== DDS_MAGIC) {
  95318. BABYLON.Tools.Error("Invalid magic number in DDS header");
  95319. return;
  95320. }
  95321. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  95322. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  95323. return;
  95324. }
  95325. if (info.isCompressed && !ext) {
  95326. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  95327. return;
  95328. }
  95329. var bpp = header[off_RGBbpp];
  95330. dataOffset = header[off_size] + 4;
  95331. var computeFormats = false;
  95332. if (info.isFourCC) {
  95333. fourCC = header[off_pfFourCC];
  95334. switch (fourCC) {
  95335. case FOURCC_DXT1:
  95336. blockBytes = 8;
  95337. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  95338. break;
  95339. case FOURCC_DXT3:
  95340. blockBytes = 16;
  95341. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  95342. break;
  95343. case FOURCC_DXT5:
  95344. blockBytes = 16;
  95345. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  95346. break;
  95347. case FOURCC_D3DFMT_R16G16B16A16F:
  95348. computeFormats = true;
  95349. break;
  95350. case FOURCC_D3DFMT_R32G32B32A32F:
  95351. computeFormats = true;
  95352. break;
  95353. case FOURCC_DX10:
  95354. // There is an additionnal header so dataOffset need to be changed
  95355. dataOffset += 5 * 4; // 5 uints
  95356. var supported = false;
  95357. switch (info.dxgiFormat) {
  95358. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  95359. computeFormats = true;
  95360. supported = true;
  95361. break;
  95362. case DXGI_FORMAT_B8G8R8X8_UNORM:
  95363. info.isRGB = true;
  95364. info.isFourCC = false;
  95365. bpp = 32;
  95366. supported = true;
  95367. break;
  95368. }
  95369. if (supported) {
  95370. break;
  95371. }
  95372. default:
  95373. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  95374. return;
  95375. }
  95376. }
  95377. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  95378. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  95379. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  95380. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  95381. if (computeFormats) {
  95382. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  95383. }
  95384. mipmapCount = 1;
  95385. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  95386. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95387. }
  95388. for (var face = 0; face < faces; face++) {
  95389. width = header[off_width];
  95390. height = header[off_height];
  95391. for (mip = 0; mip < mipmapCount; ++mip) {
  95392. if (lodIndex === -1 || lodIndex === mip) {
  95393. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  95394. var i = (lodIndex === -1) ? mip : 0;
  95395. if (!info.isCompressed && info.isFourCC) {
  95396. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95397. dataLength = width * height * 4;
  95398. var floatArray = null;
  95399. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  95400. if (bpp === 128) {
  95401. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95402. if (sphericalPolynomialFaces && i == 0) {
  95403. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95404. }
  95405. }
  95406. else if (bpp === 64) {
  95407. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95408. if (sphericalPolynomialFaces && i == 0) {
  95409. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95410. }
  95411. }
  95412. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95413. }
  95414. else {
  95415. if (bpp === 128) {
  95416. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95417. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95418. if (sphericalPolynomialFaces && i == 0) {
  95419. sphericalPolynomialFaces.push(floatArray);
  95420. }
  95421. }
  95422. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  95423. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95424. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95425. if (sphericalPolynomialFaces && i == 0) {
  95426. sphericalPolynomialFaces.push(floatArray);
  95427. }
  95428. }
  95429. else { // 64
  95430. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95431. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  95432. if (sphericalPolynomialFaces && i == 0) {
  95433. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  95434. }
  95435. }
  95436. }
  95437. if (floatArray) {
  95438. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  95439. }
  95440. }
  95441. else if (info.isRGB) {
  95442. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95443. if (bpp === 24) {
  95444. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  95445. dataLength = width * height * 3;
  95446. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  95447. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95448. }
  95449. else { // 32
  95450. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95451. dataLength = width * height * 4;
  95452. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  95453. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95454. }
  95455. }
  95456. else if (info.isLuminance) {
  95457. var unpackAlignment = engine._getUnpackAlignement();
  95458. var unpaddedRowSize = width;
  95459. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  95460. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  95461. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  95462. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  95463. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95464. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  95465. }
  95466. else {
  95467. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  95468. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  95469. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95470. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  95471. }
  95472. }
  95473. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  95474. width *= 0.5;
  95475. height *= 0.5;
  95476. width = Math.max(1.0, width);
  95477. height = Math.max(1.0, height);
  95478. }
  95479. if (currentFace !== undefined) {
  95480. // Loading a single face
  95481. break;
  95482. }
  95483. }
  95484. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  95485. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  95486. size: header[off_width],
  95487. right: sphericalPolynomialFaces[0],
  95488. left: sphericalPolynomialFaces[1],
  95489. up: sphericalPolynomialFaces[2],
  95490. down: sphericalPolynomialFaces[3],
  95491. front: sphericalPolynomialFaces[4],
  95492. back: sphericalPolynomialFaces[5],
  95493. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  95494. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  95495. gammaSpace: false,
  95496. });
  95497. }
  95498. else {
  95499. info.sphericalPolynomial = undefined;
  95500. }
  95501. };
  95502. /**
  95503. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  95504. */
  95505. DDSTools.StoreLODInAlphaChannel = false;
  95506. return DDSTools;
  95507. }());
  95508. BABYLON.DDSTools = DDSTools;
  95509. })(BABYLON || (BABYLON = {}));
  95510. //# sourceMappingURL=babylon.dds.js.map
  95511. var BABYLON;
  95512. (function (BABYLON) {
  95513. /**
  95514. * Implementation of the DDS Texture Loader.
  95515. */
  95516. var DDSTextureLoader = /** @class */ (function () {
  95517. function DDSTextureLoader() {
  95518. /**
  95519. * Defines wether the loader supports cascade loading the different faces.
  95520. */
  95521. this.supportCascades = true;
  95522. }
  95523. /**
  95524. * This returns if the loader support the current file information.
  95525. * @param extension defines the file extension of the file being loaded
  95526. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95527. * @param fallback defines the fallback internal texture if any
  95528. * @param isBase64 defines whether the texture is encoded as a base64
  95529. * @param isBuffer defines whether the texture data are stored as a buffer
  95530. * @returns true if the loader can load the specified file
  95531. */
  95532. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95533. return extension.indexOf(".dds") === 0;
  95534. };
  95535. /**
  95536. * Transform the url before loading if required.
  95537. * @param rootUrl the url of the texture
  95538. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95539. * @returns the transformed texture
  95540. */
  95541. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95542. return rootUrl;
  95543. };
  95544. /**
  95545. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95546. * @param rootUrl the url of the texture
  95547. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95548. * @returns the fallback texture
  95549. */
  95550. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95551. return null;
  95552. };
  95553. /**
  95554. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95555. * @param data contains the texture data
  95556. * @param texture defines the BabylonJS internal texture
  95557. * @param createPolynomials will be true if polynomials have been requested
  95558. * @param onLoad defines the callback to trigger once the texture is ready
  95559. * @param onError defines the callback to trigger in case of error
  95560. */
  95561. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  95562. var engine = texture.getEngine();
  95563. var info;
  95564. var loadMipmap = false;
  95565. if (Array.isArray(imgs)) {
  95566. for (var index = 0; index < imgs.length; index++) {
  95567. var data_1 = imgs[index];
  95568. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  95569. texture.width = info.width;
  95570. texture.height = info.height;
  95571. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  95572. engine._unpackFlipY(info.isCompressed);
  95573. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  95574. if (!info.isFourCC && info.mipmapCount === 1) {
  95575. engine.generateMipMapsForCubemap(texture);
  95576. }
  95577. }
  95578. }
  95579. else {
  95580. var data = imgs;
  95581. info = BABYLON.DDSTools.GetDDSInfo(data);
  95582. texture.width = info.width;
  95583. texture.height = info.height;
  95584. if (createPolynomials) {
  95585. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  95586. }
  95587. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  95588. engine._unpackFlipY(info.isCompressed);
  95589. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  95590. if (!info.isFourCC && info.mipmapCount === 1) {
  95591. engine.generateMipMapsForCubemap(texture);
  95592. }
  95593. }
  95594. engine._setCubeMapTextureParams(loadMipmap);
  95595. texture.isReady = true;
  95596. if (onLoad) {
  95597. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  95598. }
  95599. };
  95600. /**
  95601. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95602. * @param data contains the texture data
  95603. * @param texture defines the BabylonJS internal texture
  95604. * @param callback defines the method to call once ready to upload
  95605. */
  95606. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  95607. var info = BABYLON.DDSTools.GetDDSInfo(data);
  95608. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  95609. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  95610. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  95611. });
  95612. };
  95613. return DDSTextureLoader;
  95614. }());
  95615. // Register the loader.
  95616. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  95617. })(BABYLON || (BABYLON = {}));
  95618. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  95619. var BABYLON;
  95620. (function (BABYLON) {
  95621. /**
  95622. * Based on jsTGALoader - Javascript loader for TGA file
  95623. * By Vincent Thibault
  95624. * @see http://blog.robrowser.com/javascript-tga-loader.html
  95625. */
  95626. var TGATools = /** @class */ (function () {
  95627. function TGATools() {
  95628. }
  95629. /**
  95630. * Gets the header of a TGA file
  95631. * @param data defines the TGA data
  95632. * @returns the header
  95633. */
  95634. TGATools.GetTGAHeader = function (data) {
  95635. var offset = 0;
  95636. var header = {
  95637. id_length: data[offset++],
  95638. colormap_type: data[offset++],
  95639. image_type: data[offset++],
  95640. colormap_index: data[offset++] | data[offset++] << 8,
  95641. colormap_length: data[offset++] | data[offset++] << 8,
  95642. colormap_size: data[offset++],
  95643. origin: [
  95644. data[offset++] | data[offset++] << 8,
  95645. data[offset++] | data[offset++] << 8
  95646. ],
  95647. width: data[offset++] | data[offset++] << 8,
  95648. height: data[offset++] | data[offset++] << 8,
  95649. pixel_size: data[offset++],
  95650. flags: data[offset++]
  95651. };
  95652. return header;
  95653. };
  95654. /**
  95655. * Uploads TGA content to a Babylon Texture
  95656. * @hidden
  95657. */
  95658. TGATools.UploadContent = function (texture, data) {
  95659. // Not enough data to contain header ?
  95660. if (data.length < 19) {
  95661. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  95662. return;
  95663. }
  95664. // Read Header
  95665. var offset = 18;
  95666. var header = TGATools.GetTGAHeader(data);
  95667. // Assume it's a valid Targa file.
  95668. if (header.id_length + offset > data.length) {
  95669. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  95670. return;
  95671. }
  95672. // Skip not needed data
  95673. offset += header.id_length;
  95674. var use_rle = false;
  95675. var use_pal = false;
  95676. var use_grey = false;
  95677. // Get some informations.
  95678. switch (header.image_type) {
  95679. case TGATools._TYPE_RLE_INDEXED:
  95680. use_rle = true;
  95681. case TGATools._TYPE_INDEXED:
  95682. use_pal = true;
  95683. break;
  95684. case TGATools._TYPE_RLE_RGB:
  95685. use_rle = true;
  95686. case TGATools._TYPE_RGB:
  95687. // use_rgb = true;
  95688. break;
  95689. case TGATools._TYPE_RLE_GREY:
  95690. use_rle = true;
  95691. case TGATools._TYPE_GREY:
  95692. use_grey = true;
  95693. break;
  95694. }
  95695. var pixel_data;
  95696. // var numAlphaBits = header.flags & 0xf;
  95697. var pixel_size = header.pixel_size >> 3;
  95698. var pixel_total = header.width * header.height * pixel_size;
  95699. // Read palettes
  95700. var palettes;
  95701. if (use_pal) {
  95702. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  95703. }
  95704. // Read LRE
  95705. if (use_rle) {
  95706. pixel_data = new Uint8Array(pixel_total);
  95707. var c, count, i;
  95708. var localOffset = 0;
  95709. var pixels = new Uint8Array(pixel_size);
  95710. while (offset < pixel_total && localOffset < pixel_total) {
  95711. c = data[offset++];
  95712. count = (c & 0x7f) + 1;
  95713. // RLE pixels
  95714. if (c & 0x80) {
  95715. // Bind pixel tmp array
  95716. for (i = 0; i < pixel_size; ++i) {
  95717. pixels[i] = data[offset++];
  95718. }
  95719. // Copy pixel array
  95720. for (i = 0; i < count; ++i) {
  95721. pixel_data.set(pixels, localOffset + i * pixel_size);
  95722. }
  95723. localOffset += pixel_size * count;
  95724. }
  95725. // Raw pixels
  95726. else {
  95727. count *= pixel_size;
  95728. for (i = 0; i < count; ++i) {
  95729. pixel_data[localOffset + i] = data[offset++];
  95730. }
  95731. localOffset += count;
  95732. }
  95733. }
  95734. }
  95735. // RAW Pixels
  95736. else {
  95737. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  95738. }
  95739. // Load to texture
  95740. var x_start, y_start, x_step, y_step, y_end, x_end;
  95741. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  95742. default:
  95743. case TGATools._ORIGIN_UL:
  95744. x_start = 0;
  95745. x_step = 1;
  95746. x_end = header.width;
  95747. y_start = 0;
  95748. y_step = 1;
  95749. y_end = header.height;
  95750. break;
  95751. case TGATools._ORIGIN_BL:
  95752. x_start = 0;
  95753. x_step = 1;
  95754. x_end = header.width;
  95755. y_start = header.height - 1;
  95756. y_step = -1;
  95757. y_end = -1;
  95758. break;
  95759. case TGATools._ORIGIN_UR:
  95760. x_start = header.width - 1;
  95761. x_step = -1;
  95762. x_end = -1;
  95763. y_start = 0;
  95764. y_step = 1;
  95765. y_end = header.height;
  95766. break;
  95767. case TGATools._ORIGIN_BR:
  95768. x_start = header.width - 1;
  95769. x_step = -1;
  95770. x_end = -1;
  95771. y_start = header.height - 1;
  95772. y_step = -1;
  95773. y_end = -1;
  95774. break;
  95775. }
  95776. // Load the specify method
  95777. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  95778. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  95779. var engine = texture.getEngine();
  95780. engine._uploadDataToTextureDirectly(texture, imageData);
  95781. };
  95782. /** @hidden */
  95783. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95784. var image = pixel_data, colormap = palettes;
  95785. var width = header.width, height = header.height;
  95786. var color, i = 0, x, y;
  95787. var imageData = new Uint8Array(width * height * 4);
  95788. for (y = y_start; y !== y_end; y += y_step) {
  95789. for (x = x_start; x !== x_end; x += x_step, i++) {
  95790. color = image[i];
  95791. imageData[(x + width * y) * 4 + 3] = 255;
  95792. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  95793. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  95794. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  95795. }
  95796. }
  95797. return imageData;
  95798. };
  95799. /** @hidden */
  95800. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95801. var image = pixel_data;
  95802. var width = header.width, height = header.height;
  95803. var color, i = 0, x, y;
  95804. var imageData = new Uint8Array(width * height * 4);
  95805. for (y = y_start; y !== y_end; y += y_step) {
  95806. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95807. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  95808. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  95809. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  95810. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  95811. imageData[(x + width * y) * 4 + 0] = r;
  95812. imageData[(x + width * y) * 4 + 1] = g;
  95813. imageData[(x + width * y) * 4 + 2] = b;
  95814. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  95815. }
  95816. }
  95817. return imageData;
  95818. };
  95819. /** @hidden */
  95820. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95821. var image = pixel_data;
  95822. var width = header.width, height = header.height;
  95823. var i = 0, x, y;
  95824. var imageData = new Uint8Array(width * height * 4);
  95825. for (y = y_start; y !== y_end; y += y_step) {
  95826. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  95827. imageData[(x + width * y) * 4 + 3] = 255;
  95828. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95829. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95830. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95831. }
  95832. }
  95833. return imageData;
  95834. };
  95835. /** @hidden */
  95836. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95837. var image = pixel_data;
  95838. var width = header.width, height = header.height;
  95839. var i = 0, x, y;
  95840. var imageData = new Uint8Array(width * height * 4);
  95841. for (y = y_start; y !== y_end; y += y_step) {
  95842. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  95843. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95844. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95845. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95846. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  95847. }
  95848. }
  95849. return imageData;
  95850. };
  95851. /** @hidden */
  95852. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95853. var image = pixel_data;
  95854. var width = header.width, height = header.height;
  95855. var color, i = 0, x, y;
  95856. var imageData = new Uint8Array(width * height * 4);
  95857. for (y = y_start; y !== y_end; y += y_step) {
  95858. for (x = x_start; x !== x_end; x += x_step, i++) {
  95859. color = image[i];
  95860. imageData[(x + width * y) * 4 + 0] = color;
  95861. imageData[(x + width * y) * 4 + 1] = color;
  95862. imageData[(x + width * y) * 4 + 2] = color;
  95863. imageData[(x + width * y) * 4 + 3] = 255;
  95864. }
  95865. }
  95866. return imageData;
  95867. };
  95868. /** @hidden */
  95869. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95870. var image = pixel_data;
  95871. var width = header.width, height = header.height;
  95872. var i = 0, x, y;
  95873. var imageData = new Uint8Array(width * height * 4);
  95874. for (y = y_start; y !== y_end; y += y_step) {
  95875. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95876. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  95877. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  95878. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95879. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  95880. }
  95881. }
  95882. return imageData;
  95883. };
  95884. //private static _TYPE_NO_DATA = 0;
  95885. TGATools._TYPE_INDEXED = 1;
  95886. TGATools._TYPE_RGB = 2;
  95887. TGATools._TYPE_GREY = 3;
  95888. TGATools._TYPE_RLE_INDEXED = 9;
  95889. TGATools._TYPE_RLE_RGB = 10;
  95890. TGATools._TYPE_RLE_GREY = 11;
  95891. TGATools._ORIGIN_MASK = 0x30;
  95892. TGATools._ORIGIN_SHIFT = 0x04;
  95893. TGATools._ORIGIN_BL = 0x00;
  95894. TGATools._ORIGIN_BR = 0x01;
  95895. TGATools._ORIGIN_UL = 0x02;
  95896. TGATools._ORIGIN_UR = 0x03;
  95897. return TGATools;
  95898. }());
  95899. BABYLON.TGATools = TGATools;
  95900. })(BABYLON || (BABYLON = {}));
  95901. //# sourceMappingURL=babylon.tga.js.map
  95902. var BABYLON;
  95903. (function (BABYLON) {
  95904. /**
  95905. * Implementation of the TGA Texture Loader.
  95906. */
  95907. var TGATextureLoader = /** @class */ (function () {
  95908. function TGATextureLoader() {
  95909. /**
  95910. * Defines wether the loader supports cascade loading the different faces.
  95911. */
  95912. this.supportCascades = false;
  95913. }
  95914. /**
  95915. * This returns if the loader support the current file information.
  95916. * @param extension defines the file extension of the file being loaded
  95917. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95918. * @param fallback defines the fallback internal texture if any
  95919. * @param isBase64 defines whether the texture is encoded as a base64
  95920. * @param isBuffer defines whether the texture data are stored as a buffer
  95921. * @returns true if the loader can load the specified file
  95922. */
  95923. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95924. return extension.indexOf(".tga") === 0;
  95925. };
  95926. /**
  95927. * Transform the url before loading if required.
  95928. * @param rootUrl the url of the texture
  95929. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95930. * @returns the transformed texture
  95931. */
  95932. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95933. return rootUrl;
  95934. };
  95935. /**
  95936. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95937. * @param rootUrl the url of the texture
  95938. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95939. * @returns the fallback texture
  95940. */
  95941. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95942. return null;
  95943. };
  95944. /**
  95945. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95946. * @param data contains the texture data
  95947. * @param texture defines the BabylonJS internal texture
  95948. * @param createPolynomials will be true if polynomials have been requested
  95949. * @param onLoad defines the callback to trigger once the texture is ready
  95950. * @param onError defines the callback to trigger in case of error
  95951. */
  95952. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95953. throw ".env not supported in Cube.";
  95954. };
  95955. /**
  95956. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95957. * @param data contains the texture data
  95958. * @param texture defines the BabylonJS internal texture
  95959. * @param callback defines the method to call once ready to upload
  95960. */
  95961. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  95962. var uintData = new Uint8Array(data);
  95963. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  95964. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  95965. BABYLON.TGATools.UploadContent(texture, uintData);
  95966. });
  95967. };
  95968. return TGATextureLoader;
  95969. }());
  95970. // Register the loader.
  95971. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  95972. })(BABYLON || (BABYLON = {}));
  95973. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  95974. var BABYLON;
  95975. (function (BABYLON) {
  95976. /**
  95977. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  95978. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  95979. */
  95980. var KhronosTextureContainer = /** @class */ (function () {
  95981. /**
  95982. * Creates a new KhronosTextureContainer
  95983. * @param arrayBuffer contents of the KTX container file
  95984. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  95985. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  95986. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  95987. */
  95988. function KhronosTextureContainer(
  95989. /** contents of the KTX container file */
  95990. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  95991. this.arrayBuffer = arrayBuffer;
  95992. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  95993. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  95994. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  95995. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  95996. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  95997. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  95998. BABYLON.Tools.Error("texture missing KTX identifier");
  95999. return;
  96000. }
  96001. // load the reset of the header in native 32 bit int
  96002. var header = new Int32Array(this.arrayBuffer, 12, 13);
  96003. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  96004. var oppositeEndianess = header[0] === 0x01020304;
  96005. // read all the header elements in order they exist in the file, without modification (sans endainness)
  96006. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  96007. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  96008. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  96009. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  96010. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  96011. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  96012. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  96013. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  96014. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  96015. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  96016. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  96017. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  96018. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  96019. if (this.glType !== 0) {
  96020. BABYLON.Tools.Error("only compressed formats currently supported");
  96021. return;
  96022. }
  96023. else {
  96024. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  96025. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  96026. }
  96027. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96028. BABYLON.Tools.Error("only 2D textures currently supported");
  96029. return;
  96030. }
  96031. if (this.numberOfArrayElements !== 0) {
  96032. BABYLON.Tools.Error("texture arrays not currently supported");
  96033. return;
  96034. }
  96035. if (this.numberOfFaces !== facesExpected) {
  96036. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96037. return;
  96038. }
  96039. // we now have a completely validated file, so could use existence of loadType as success
  96040. // would need to make this more elaborate & adjust checks above to support more than one load type
  96041. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96042. }
  96043. //
  96044. /**
  96045. * Revert the endianness of a value.
  96046. * Not as fast hardware based, but will probably never need to use
  96047. * @param val defines the value to convert
  96048. * @returns the new value
  96049. */
  96050. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96051. return ((val & 0xFF) << 24)
  96052. | ((val & 0xFF00) << 8)
  96053. | ((val >> 8) & 0xFF00)
  96054. | ((val >> 24) & 0xFF);
  96055. };
  96056. /**
  96057. * Uploads KTX content to a Babylon Texture.
  96058. * It is assumed that the texture has already been created & is currently bound
  96059. * @hidden
  96060. */
  96061. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96062. switch (this.loadType) {
  96063. case KhronosTextureContainer.COMPRESSED_2D:
  96064. this._upload2DCompressedLevels(texture, loadMipmaps);
  96065. break;
  96066. case KhronosTextureContainer.TEX_2D:
  96067. case KhronosTextureContainer.COMPRESSED_3D:
  96068. case KhronosTextureContainer.TEX_3D:
  96069. }
  96070. };
  96071. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96072. // initialize width & height for level 1
  96073. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96074. var width = this.pixelWidth;
  96075. var height = this.pixelHeight;
  96076. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96077. for (var level = 0; level < mipmapCount; level++) {
  96078. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96079. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96080. for (var face = 0; face < this.numberOfFaces; face++) {
  96081. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96082. var engine = texture.getEngine();
  96083. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96084. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96085. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96086. }
  96087. width = Math.max(1.0, width * 0.5);
  96088. height = Math.max(1.0, height * 0.5);
  96089. }
  96090. };
  96091. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96092. // load types
  96093. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96094. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96095. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96096. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96097. return KhronosTextureContainer;
  96098. }());
  96099. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96100. })(BABYLON || (BABYLON = {}));
  96101. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96102. var BABYLON;
  96103. (function (BABYLON) {
  96104. /**
  96105. * Implementation of the KTX Texture Loader.
  96106. */
  96107. var KTXTextureLoader = /** @class */ (function () {
  96108. function KTXTextureLoader() {
  96109. /**
  96110. * Defines wether the loader supports cascade loading the different faces.
  96111. */
  96112. this.supportCascades = false;
  96113. }
  96114. /**
  96115. * This returns if the loader support the current file information.
  96116. * @param extension defines the file extension of the file being loaded
  96117. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96118. * @param fallback defines the fallback internal texture if any
  96119. * @param isBase64 defines whether the texture is encoded as a base64
  96120. * @param isBuffer defines whether the texture data are stored as a buffer
  96121. * @returns true if the loader can load the specified file
  96122. */
  96123. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96124. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96125. return true;
  96126. }
  96127. return false;
  96128. };
  96129. /**
  96130. * Transform the url before loading if required.
  96131. * @param rootUrl the url of the texture
  96132. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96133. * @returns the transformed texture
  96134. */
  96135. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96136. var lastDot = rootUrl.lastIndexOf('.');
  96137. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96138. };
  96139. /**
  96140. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96141. * @param rootUrl the url of the texture
  96142. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96143. * @returns the fallback texture
  96144. */
  96145. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96146. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96147. var exp = new RegExp("" + textureFormatInUse + "$");
  96148. return rootUrl.replace(exp, "");
  96149. };
  96150. /**
  96151. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96152. * @param data contains the texture data
  96153. * @param texture defines the BabylonJS internal texture
  96154. * @param createPolynomials will be true if polynomials have been requested
  96155. * @param onLoad defines the callback to trigger once the texture is ready
  96156. * @param onError defines the callback to trigger in case of error
  96157. */
  96158. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96159. if (Array.isArray(data)) {
  96160. return;
  96161. }
  96162. var engine = texture.getEngine();
  96163. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96164. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96165. engine._unpackFlipY(true);
  96166. ktx.uploadLevels(texture, texture.generateMipMaps);
  96167. texture.width = ktx.pixelWidth;
  96168. texture.height = ktx.pixelHeight;
  96169. engine._setCubeMapTextureParams(loadMipmap);
  96170. texture.isReady = true;
  96171. };
  96172. /**
  96173. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96174. * @param data contains the texture data
  96175. * @param texture defines the BabylonJS internal texture
  96176. * @param callback defines the method to call once ready to upload
  96177. */
  96178. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  96179. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  96180. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  96181. ktx.uploadLevels(texture, texture.generateMipMaps);
  96182. });
  96183. };
  96184. return KTXTextureLoader;
  96185. }());
  96186. // Register the loader.
  96187. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  96188. })(BABYLON || (BABYLON = {}));
  96189. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  96190. var BABYLON;
  96191. (function (BABYLON) {
  96192. /**
  96193. * Sets of helpers addressing the serialization and deserialization of environment texture
  96194. * stored in a BabylonJS env file.
  96195. * Those files are usually stored as .env files.
  96196. */
  96197. var EnvironmentTextureTools = /** @class */ (function () {
  96198. function EnvironmentTextureTools() {
  96199. }
  96200. /**
  96201. * Gets the environment info from an env file.
  96202. * @param data The array buffer containing the .env bytes.
  96203. * @returns the environment file info (the json header) if successfully parsed.
  96204. */
  96205. EnvironmentTextureTools.GetEnvInfo = function (data) {
  96206. var dataView = new DataView(data);
  96207. var pos = 0;
  96208. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96209. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  96210. BABYLON.Tools.Error('Not a babylon environment map');
  96211. return null;
  96212. }
  96213. }
  96214. // Read json manifest - collect characters up to null terminator
  96215. var manifestString = '';
  96216. var charCode = 0x00;
  96217. while ((charCode = dataView.getUint8(pos++))) {
  96218. manifestString += String.fromCharCode(charCode);
  96219. }
  96220. var manifest = JSON.parse(manifestString);
  96221. if (manifest.specular) {
  96222. // Extend the header with the position of the payload.
  96223. manifest.specular.specularDataPosition = pos;
  96224. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  96225. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  96226. }
  96227. return manifest;
  96228. };
  96229. /**
  96230. * Creates an environment texture from a loaded cube texture.
  96231. * @param texture defines the cube texture to convert in env file
  96232. * @return a promise containing the environment data if succesfull.
  96233. */
  96234. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  96235. var _this = this;
  96236. var internalTexture = texture.getInternalTexture();
  96237. if (!internalTexture) {
  96238. return Promise.reject("The cube texture is invalid.");
  96239. }
  96240. if (!texture._prefiltered) {
  96241. return Promise.reject("The cube texture is invalid (not prefiltered).");
  96242. }
  96243. var engine = internalTexture.getEngine();
  96244. if (engine && engine.premultipliedAlpha) {
  96245. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  96246. }
  96247. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  96248. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  96249. }
  96250. var canvas = engine.getRenderingCanvas();
  96251. if (!canvas) {
  96252. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  96253. }
  96254. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96255. if (!engine.getCaps().textureFloatRender) {
  96256. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96257. if (!engine.getCaps().textureHalfFloatRender) {
  96258. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  96259. }
  96260. }
  96261. var cubeWidth = internalTexture.width;
  96262. var hostingScene = new BABYLON.Scene(engine);
  96263. var specularTextures = {};
  96264. var promises = [];
  96265. // Read and collect all mipmaps data from the cube.
  96266. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  96267. mipmapsCount = Math.round(mipmapsCount);
  96268. var _loop_1 = function (i) {
  96269. var faceWidth = Math.pow(2, mipmapsCount - i);
  96270. var _loop_2 = function (face) {
  96271. var data = texture.readPixels(face, i);
  96272. // Creates a temp texture with the face data.
  96273. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  96274. // And rgbdEncode them.
  96275. var promise = new Promise(function (resolve, reject) {
  96276. 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);
  96277. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  96278. rgbdPostProcess.onApply = function (effect) {
  96279. effect._bindTexture("textureSampler", tempTexture);
  96280. };
  96281. // As the process needs to happen on the main canvas, keep track of the current size
  96282. var currentW = engine.getRenderWidth();
  96283. var currentH = engine.getRenderHeight();
  96284. // Set the desired size for the texture
  96285. engine.setSize(faceWidth, faceWidth);
  96286. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  96287. // Reading datas from WebGL
  96288. BABYLON.Tools.ToBlob(canvas, function (blob) {
  96289. var fileReader = new FileReader();
  96290. fileReader.onload = function (event) {
  96291. var arrayBuffer = event.target.result;
  96292. specularTextures[i * 6 + face] = arrayBuffer;
  96293. resolve();
  96294. };
  96295. fileReader.readAsArrayBuffer(blob);
  96296. });
  96297. // Reapply the previous canvas size
  96298. engine.setSize(currentW, currentH);
  96299. });
  96300. });
  96301. promises.push(promise);
  96302. };
  96303. // All faces of the cube.
  96304. for (var face = 0; face < 6; face++) {
  96305. _loop_2(face);
  96306. }
  96307. };
  96308. for (var i = 0; i <= mipmapsCount; i++) {
  96309. _loop_1(i);
  96310. }
  96311. // Once all the textures haves been collected as RGBD stored in PNGs
  96312. return Promise.all(promises).then(function () {
  96313. // We can delete the hosting scene keeping track of all the creation objects
  96314. hostingScene.dispose();
  96315. // Creates the json header for the env texture
  96316. var info = {
  96317. version: 1,
  96318. width: cubeWidth,
  96319. irradiance: _this._CreateEnvTextureIrradiance(texture),
  96320. specular: {
  96321. mipmaps: [],
  96322. lodGenerationScale: texture.lodGenerationScale
  96323. }
  96324. };
  96325. // Sets the specular image data information
  96326. var position = 0;
  96327. for (var i = 0; i <= mipmapsCount; i++) {
  96328. for (var face = 0; face < 6; face++) {
  96329. var byteLength = specularTextures[i * 6 + face].byteLength;
  96330. info.specular.mipmaps.push({
  96331. length: byteLength,
  96332. position: position
  96333. });
  96334. position += byteLength;
  96335. }
  96336. }
  96337. // Encode the JSON as an array buffer
  96338. var infoString = JSON.stringify(info);
  96339. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  96340. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  96341. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  96342. infoView[i] = infoString.charCodeAt(i);
  96343. }
  96344. // Ends up with a null terminator for easier parsing
  96345. infoView[infoString.length] = 0x00;
  96346. // Computes the final required size and creates the storage
  96347. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  96348. var finalBuffer = new ArrayBuffer(totalSize);
  96349. var finalBufferView = new Uint8Array(finalBuffer);
  96350. var dataView = new DataView(finalBuffer);
  96351. // Copy the magic bytes identifying the file in
  96352. var pos = 0;
  96353. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  96354. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  96355. }
  96356. // Add the json info
  96357. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  96358. pos += infoBuffer.byteLength;
  96359. // Finally inserts the texture data
  96360. for (var i = 0; i <= mipmapsCount; i++) {
  96361. for (var face = 0; face < 6; face++) {
  96362. var dataBuffer = specularTextures[i * 6 + face];
  96363. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  96364. pos += dataBuffer.byteLength;
  96365. }
  96366. }
  96367. // Voila
  96368. return finalBuffer;
  96369. });
  96370. };
  96371. /**
  96372. * Creates a JSON representation of the spherical data.
  96373. * @param texture defines the texture containing the polynomials
  96374. * @return the JSON representation of the spherical info
  96375. */
  96376. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  96377. var polynmials = texture.sphericalPolynomial;
  96378. if (polynmials == null) {
  96379. return null;
  96380. }
  96381. return {
  96382. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  96383. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  96384. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  96385. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  96386. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  96387. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  96388. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  96389. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  96390. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  96391. };
  96392. };
  96393. /**
  96394. * Uploads the texture info contained in the env file to the GPU.
  96395. * @param texture defines the internal texture to upload to
  96396. * @param arrayBuffer defines the buffer cotaining the data to load
  96397. * @param info defines the texture info retrieved through the GetEnvInfo method
  96398. * @returns a promise
  96399. */
  96400. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  96401. if (info.version !== 1) {
  96402. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  96403. }
  96404. var specularInfo = info.specular;
  96405. if (!specularInfo) {
  96406. // Nothing else parsed so far
  96407. return Promise.resolve();
  96408. }
  96409. // Double checks the enclosed info
  96410. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  96411. mipmapsCount = Math.round(mipmapsCount) + 1;
  96412. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  96413. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  96414. }
  96415. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  96416. var imageData = new Array(mipmapsCount);
  96417. for (var i = 0; i < mipmapsCount; i++) {
  96418. imageData[i] = new Array(6);
  96419. for (var face = 0; face < 6; face++) {
  96420. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  96421. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  96422. }
  96423. }
  96424. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  96425. };
  96426. /**
  96427. * Uploads the levels of image data to the GPU.
  96428. * @param texture defines the internal texture to upload to
  96429. * @param imageData defines the array buffer views of image data [mipmap][face]
  96430. * @returns a promise
  96431. */
  96432. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  96433. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  96434. throw new Error("Texture size must be a power of two");
  96435. }
  96436. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  96437. // Gets everything ready.
  96438. var engine = texture.getEngine();
  96439. var expandTexture = false;
  96440. var generateNonLODTextures = false;
  96441. var rgbdPostProcess = null;
  96442. var cubeRtt = null;
  96443. var lodTextures = null;
  96444. var caps = engine.getCaps();
  96445. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96446. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96447. texture.generateMipMaps = true;
  96448. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  96449. // Add extra process if texture lod is not supported
  96450. if (!caps.textureLOD) {
  96451. expandTexture = false;
  96452. generateNonLODTextures = true;
  96453. lodTextures = {};
  96454. }
  96455. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  96456. else if (engine.webGLVersion < 2) {
  96457. expandTexture = false;
  96458. }
  96459. // If half float available we can uncompress the texture
  96460. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  96461. expandTexture = true;
  96462. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96463. }
  96464. // If full float available we can uncompress the texture
  96465. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  96466. expandTexture = true;
  96467. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96468. }
  96469. // Expand the texture if possible
  96470. if (expandTexture) {
  96471. // Simply run through the decode PP
  96472. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  96473. texture._isRGBD = false;
  96474. texture.invertY = false;
  96475. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  96476. generateDepthBuffer: false,
  96477. generateMipMaps: true,
  96478. generateStencilBuffer: false,
  96479. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  96480. type: texture.type,
  96481. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  96482. });
  96483. }
  96484. else {
  96485. texture._isRGBD = true;
  96486. texture.invertY = true;
  96487. // In case of missing support, applies the same patch than DDS files.
  96488. if (generateNonLODTextures) {
  96489. var mipSlices = 3;
  96490. var scale = texture._lodGenerationScale;
  96491. var offset = texture._lodGenerationOffset;
  96492. for (var i = 0; i < mipSlices; i++) {
  96493. //compute LOD from even spacing in smoothness (matching shader calculation)
  96494. var smoothness = i / (mipSlices - 1);
  96495. var roughness = 1 - smoothness;
  96496. var minLODIndex = offset; // roughness = 0
  96497. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  96498. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  96499. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  96500. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  96501. glTextureFromLod.isCube = true;
  96502. glTextureFromLod.invertY = true;
  96503. glTextureFromLod.generateMipMaps = false;
  96504. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  96505. // Wrap in a base texture for easy binding.
  96506. var lodTexture = new BABYLON.BaseTexture(null);
  96507. lodTexture.isCube = true;
  96508. lodTexture._texture = glTextureFromLod;
  96509. lodTextures[mipmapIndex] = lodTexture;
  96510. switch (i) {
  96511. case 0:
  96512. texture._lodTextureLow = lodTexture;
  96513. break;
  96514. case 1:
  96515. texture._lodTextureMid = lodTexture;
  96516. break;
  96517. case 2:
  96518. texture._lodTextureHigh = lodTexture;
  96519. break;
  96520. }
  96521. }
  96522. }
  96523. }
  96524. var promises = [];
  96525. var _loop_3 = function (i) {
  96526. var _loop_4 = function (face) {
  96527. // Constructs an image element from image data
  96528. var bytes = imageData[i][face];
  96529. var blob = new Blob([bytes], { type: 'image/png' });
  96530. var url = URL.createObjectURL(blob);
  96531. var image = new Image();
  96532. image.src = url;
  96533. // Enqueue promise to upload to the texture.
  96534. var promise = new Promise(function (resolve, reject) {
  96535. image.onload = function () {
  96536. if (expandTexture) {
  96537. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  96538. reject(message);
  96539. }, image);
  96540. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  96541. // Uncompress the data to a RTT
  96542. rgbdPostProcess.onApply = function (effect) {
  96543. effect._bindTexture("textureSampler", tempTexture_1);
  96544. effect.setFloat2("scale", 1, 1);
  96545. };
  96546. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  96547. // Cleanup
  96548. engine.restoreDefaultFramebuffer();
  96549. tempTexture_1.dispose();
  96550. window.URL.revokeObjectURL(url);
  96551. resolve();
  96552. });
  96553. }
  96554. else {
  96555. engine._uploadImageToTexture(texture, image, face, i);
  96556. // Upload the face to the non lod texture support
  96557. if (generateNonLODTextures) {
  96558. var lodTexture = lodTextures[i];
  96559. if (lodTexture) {
  96560. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  96561. }
  96562. }
  96563. resolve();
  96564. }
  96565. };
  96566. image.onerror = function (error) {
  96567. reject(error);
  96568. };
  96569. });
  96570. promises.push(promise);
  96571. };
  96572. // All faces
  96573. for (var face = 0; face < 6; face++) {
  96574. _loop_4(face);
  96575. }
  96576. };
  96577. // All mipmaps up to provided number of images
  96578. for (var i = 0; i < imageData.length; i++) {
  96579. _loop_3(i);
  96580. }
  96581. // Fill remaining mipmaps with black textures.
  96582. if (imageData.length < mipmapsCount) {
  96583. var data = void 0;
  96584. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  96585. var dataLength = size * size * 4;
  96586. switch (texture.type) {
  96587. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  96588. data = new Uint8Array(dataLength);
  96589. break;
  96590. }
  96591. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  96592. data = new Uint16Array(dataLength);
  96593. break;
  96594. }
  96595. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  96596. data = new Float32Array(dataLength);
  96597. break;
  96598. }
  96599. }
  96600. for (var i = imageData.length; i < mipmapsCount; i++) {
  96601. for (var face = 0; face < 6; face++) {
  96602. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  96603. }
  96604. }
  96605. }
  96606. // Once all done, finishes the cleanup and return
  96607. return Promise.all(promises).then(function () {
  96608. // Release temp RTT.
  96609. if (cubeRtt) {
  96610. engine._releaseFramebufferObjects(cubeRtt);
  96611. cubeRtt._swapAndDie(texture);
  96612. }
  96613. // Release temp Post Process.
  96614. if (rgbdPostProcess) {
  96615. rgbdPostProcess.dispose();
  96616. }
  96617. // Flag internal texture as ready in case they are in use.
  96618. if (generateNonLODTextures) {
  96619. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  96620. texture._lodTextureHigh._texture.isReady = true;
  96621. }
  96622. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  96623. texture._lodTextureMid._texture.isReady = true;
  96624. }
  96625. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  96626. texture._lodTextureLow._texture.isReady = true;
  96627. }
  96628. }
  96629. });
  96630. };
  96631. /**
  96632. * Uploads spherical polynomials information to the texture.
  96633. * @param texture defines the texture we are trying to upload the information to
  96634. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  96635. */
  96636. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  96637. if (info.version !== 1) {
  96638. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  96639. }
  96640. var irradianceInfo = info.irradiance;
  96641. if (!irradianceInfo) {
  96642. return;
  96643. }
  96644. var sp = new BABYLON.SphericalPolynomial();
  96645. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  96646. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  96647. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  96648. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  96649. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  96650. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  96651. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  96652. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  96653. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  96654. texture._sphericalPolynomial = sp;
  96655. };
  96656. /**
  96657. * Magic number identifying the env file.
  96658. */
  96659. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  96660. return EnvironmentTextureTools;
  96661. }());
  96662. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  96663. })(BABYLON || (BABYLON = {}));
  96664. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  96665. var BABYLON;
  96666. (function (BABYLON) {
  96667. /**
  96668. * Implementation of the ENV Texture Loader.
  96669. */
  96670. var ENVTextureLoader = /** @class */ (function () {
  96671. function ENVTextureLoader() {
  96672. /**
  96673. * Defines wether the loader supports cascade loading the different faces.
  96674. */
  96675. this.supportCascades = false;
  96676. }
  96677. /**
  96678. * This returns if the loader support the current file information.
  96679. * @param extension defines the file extension of the file being loaded
  96680. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96681. * @param fallback defines the fallback internal texture if any
  96682. * @param isBase64 defines whether the texture is encoded as a base64
  96683. * @param isBuffer defines whether the texture data are stored as a buffer
  96684. * @returns true if the loader can load the specified file
  96685. */
  96686. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96687. return extension.indexOf(".env") === 0;
  96688. };
  96689. /**
  96690. * Transform the url before loading if required.
  96691. * @param rootUrl the url of the texture
  96692. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96693. * @returns the transformed texture
  96694. */
  96695. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96696. return rootUrl;
  96697. };
  96698. /**
  96699. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96700. * @param rootUrl the url of the texture
  96701. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96702. * @returns the fallback texture
  96703. */
  96704. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96705. return null;
  96706. };
  96707. /**
  96708. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96709. * @param data contains the texture data
  96710. * @param texture defines the BabylonJS internal texture
  96711. * @param createPolynomials will be true if polynomials have been requested
  96712. * @param onLoad defines the callback to trigger once the texture is ready
  96713. * @param onError defines the callback to trigger in case of error
  96714. */
  96715. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96716. if (Array.isArray(data)) {
  96717. return;
  96718. }
  96719. data = data;
  96720. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  96721. if (info) {
  96722. texture.width = info.width;
  96723. texture.height = info.width;
  96724. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  96725. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  96726. texture.isReady = true;
  96727. if (onLoad) {
  96728. onLoad();
  96729. }
  96730. });
  96731. }
  96732. else if (onError) {
  96733. onError("Can not parse the environment file", null);
  96734. }
  96735. };
  96736. /**
  96737. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96738. * @param data contains the texture data
  96739. * @param texture defines the BabylonJS internal texture
  96740. * @param callback defines the method to call once ready to upload
  96741. */
  96742. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  96743. throw ".env not supported in 2d.";
  96744. };
  96745. return ENVTextureLoader;
  96746. }());
  96747. // Register the loader.
  96748. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  96749. })(BABYLON || (BABYLON = {}));
  96750. //# sourceMappingURL=babylon.envTextureLoader.js.map
  96751. var BABYLON;
  96752. (function (BABYLON) {
  96753. /**
  96754. * Renders a layer on top of an existing scene
  96755. */
  96756. var UtilityLayerRenderer = /** @class */ (function () {
  96757. /**
  96758. * Instantiates a UtilityLayerRenderer
  96759. * @param originalScene the original scene that will be rendered on top of
  96760. */
  96761. function UtilityLayerRenderer(
  96762. /** the original scene that will be rendered on top of */
  96763. originalScene) {
  96764. var _this = this;
  96765. this.originalScene = originalScene;
  96766. this._pointerCaptures = {};
  96767. this._lastPointerEvents = {};
  96768. /**
  96769. * If the utility layer should automatically be rendered on top of existing scene
  96770. */
  96771. this.shouldRender = true;
  96772. /**
  96773. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  96774. */
  96775. this.onlyCheckPointerDownEvents = true;
  96776. /**
  96777. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  96778. */
  96779. this.processAllEvents = false;
  96780. /**
  96781. * Observable raised when the pointer move from the utility layer scene to the main scene
  96782. */
  96783. this.onPointerOutObservable = new BABYLON.Observable();
  96784. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  96785. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  96786. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  96787. this.utilityLayerScene._allowPostProcessClearColor = false;
  96788. originalScene.getEngine().scenes.pop();
  96789. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  96790. this.utilityLayerScene.detachControl();
  96791. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  96792. if (!_this.processAllEvents) {
  96793. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  96794. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  96795. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  96796. return;
  96797. }
  96798. }
  96799. var pointerEvent = (prePointerInfo.event);
  96800. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  96801. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96802. return;
  96803. }
  96804. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  96805. if (!prePointerInfo.ray && utilityScenePick) {
  96806. prePointerInfo.ray = utilityScenePick.ray;
  96807. }
  96808. // always fire the prepointer oversvable
  96809. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  96810. // allow every non pointer down event to flow to the utility layer
  96811. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  96812. if (!prePointerInfo.skipOnPointerObservable) {
  96813. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96814. }
  96815. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  96816. _this._pointerCaptures[pointerEvent.pointerId] = false;
  96817. }
  96818. return;
  96819. }
  96820. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  96821. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  96822. if (utilityScenePick && utilityScenePick.hit) {
  96823. if (!prePointerInfo.skipOnPointerObservable) {
  96824. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  96825. }
  96826. prePointerInfo.skipOnPointerObservable = true;
  96827. }
  96828. }
  96829. else {
  96830. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  96831. var pointerEvent_1 = (prePointerInfo.event);
  96832. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  96833. if (originalScenePick && utilityScenePick) {
  96834. // No pick in utility scene
  96835. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  96836. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96837. // We touched an utility mesh present in the main scene
  96838. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96839. prePointerInfo.skipOnPointerObservable = true;
  96840. }
  96841. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96842. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  96843. }
  96844. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96845. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96846. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96847. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96848. }
  96849. }
  96850. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  96851. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  96852. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  96853. // If a previous utility layer set this, do not unset this
  96854. if (!prePointerInfo.skipOnPointerObservable) {
  96855. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  96856. }
  96857. }
  96858. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  96859. // We have a pick in both scenes but main is closer than utility
  96860. // We touched an utility mesh present in the main scene
  96861. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96862. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96863. prePointerInfo.skipOnPointerObservable = true;
  96864. }
  96865. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96866. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96867. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96868. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96869. }
  96870. }
  96871. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  96872. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  96873. }
  96874. }
  96875. }
  96876. });
  96877. // Render directly on top of existing scene without clearing
  96878. this.utilityLayerScene.autoClear = false;
  96879. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  96880. if (_this.shouldRender) {
  96881. _this.render();
  96882. }
  96883. });
  96884. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  96885. _this.dispose();
  96886. });
  96887. this._updateCamera();
  96888. }
  96889. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  96890. /**
  96891. * 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)
  96892. */
  96893. get: function () {
  96894. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  96895. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96896. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96897. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96898. });
  96899. }
  96900. return UtilityLayerRenderer._DefaultUtilityLayer;
  96901. },
  96902. enumerable: true,
  96903. configurable: true
  96904. });
  96905. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  96906. /**
  96907. * 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)
  96908. */
  96909. get: function () {
  96910. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  96911. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96912. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  96913. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96914. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96915. });
  96916. }
  96917. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  96918. },
  96919. enumerable: true,
  96920. configurable: true
  96921. });
  96922. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  96923. if (!prePointerInfo.skipOnPointerObservable) {
  96924. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  96925. this._lastPointerEvents[pointerEvent.pointerId] = true;
  96926. }
  96927. };
  96928. /**
  96929. * Renders the utility layers scene on top of the original scene
  96930. */
  96931. UtilityLayerRenderer.prototype.render = function () {
  96932. this._updateCamera();
  96933. if (this.utilityLayerScene.activeCamera) {
  96934. // Set the camera's scene to utility layers scene
  96935. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  96936. var camera = this.utilityLayerScene.activeCamera;
  96937. camera._scene = this.utilityLayerScene;
  96938. if (camera.leftCamera) {
  96939. camera.leftCamera._scene = this.utilityLayerScene;
  96940. }
  96941. if (camera.rightCamera) {
  96942. camera.rightCamera._scene = this.utilityLayerScene;
  96943. }
  96944. this.utilityLayerScene.render(false);
  96945. // Reset camera's scene back to original
  96946. camera._scene = oldScene;
  96947. if (camera.leftCamera) {
  96948. camera.leftCamera._scene = oldScene;
  96949. }
  96950. if (camera.rightCamera) {
  96951. camera.rightCamera._scene = oldScene;
  96952. }
  96953. }
  96954. };
  96955. /**
  96956. * Disposes of the renderer
  96957. */
  96958. UtilityLayerRenderer.prototype.dispose = function () {
  96959. this.onPointerOutObservable.clear();
  96960. if (this._afterRenderObserver) {
  96961. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  96962. }
  96963. if (this._sceneDisposeObserver) {
  96964. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96965. }
  96966. if (this._originalPointerObserver) {
  96967. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  96968. }
  96969. this.utilityLayerScene.dispose();
  96970. };
  96971. UtilityLayerRenderer.prototype._updateCamera = function () {
  96972. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  96973. };
  96974. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96975. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96976. return UtilityLayerRenderer;
  96977. }());
  96978. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  96979. })(BABYLON || (BABYLON = {}));
  96980. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  96981. //# sourceMappingURL=babylon.behavior.js.map
  96982. var BABYLON;
  96983. (function (BABYLON) {
  96984. /**
  96985. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  96986. */
  96987. var PointerDragBehavior = /** @class */ (function () {
  96988. /**
  96989. * Creates a pointer drag behavior that can be attached to a mesh
  96990. * @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)
  96991. */
  96992. function PointerDragBehavior(options) {
  96993. /**
  96994. * 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)
  96995. */
  96996. this.maxDragAngle = 0;
  96997. /**
  96998. * @hidden
  96999. */
  97000. this._useAlternatePickedPointAboveMaxDragAngle = false;
  97001. /**
  97002. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97003. */
  97004. this.currentDraggingPointerID = -1;
  97005. /**
  97006. * If the behavior is currently in a dragging state
  97007. */
  97008. this.dragging = false;
  97009. /**
  97010. * 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)
  97011. */
  97012. this.dragDeltaRatio = 0.2;
  97013. /**
  97014. * If the drag plane orientation should be updated during the dragging (Default: true)
  97015. */
  97016. this.updateDragPlane = true;
  97017. // Debug mode will display drag planes to help visualize behavior
  97018. this._debugMode = false;
  97019. this._moving = false;
  97020. /**
  97021. * Fires each time the attached mesh is dragged with the pointer
  97022. * * delta between last drag position and current drag position in world space
  97023. * * dragDistance along the drag axis
  97024. * * dragPlaneNormal normal of the current drag plane used during the drag
  97025. * * dragPlanePoint in world space where the drag intersects the drag plane
  97026. */
  97027. this.onDragObservable = new BABYLON.Observable();
  97028. /**
  97029. * Fires each time a drag begins (eg. mouse down on mesh)
  97030. */
  97031. this.onDragStartObservable = new BABYLON.Observable();
  97032. /**
  97033. * Fires each time a drag ends (eg. mouse release after drag)
  97034. */
  97035. this.onDragEndObservable = new BABYLON.Observable();
  97036. /**
  97037. * If the attached mesh should be moved when dragged
  97038. */
  97039. this.moveAttached = true;
  97040. /**
  97041. * If the drag behavior will react to drag events (Default: true)
  97042. */
  97043. this.enabled = true;
  97044. /**
  97045. * If camera controls should be detached during the drag
  97046. */
  97047. this.detachCameraControls = true;
  97048. /**
  97049. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97050. */
  97051. this.useObjectOrienationForDragging = true;
  97052. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97053. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97054. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97055. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97056. this._attachedElement = null;
  97057. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97058. this._lastPointerRay = {};
  97059. this._dragDelta = new BABYLON.Vector3();
  97060. // Variables to avoid instantiation in the below method
  97061. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97062. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97063. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97064. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97065. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97066. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97067. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97068. this._options = options ? options : {};
  97069. var optionCount = 0;
  97070. if (this._options.dragAxis) {
  97071. optionCount++;
  97072. }
  97073. if (this._options.dragPlaneNormal) {
  97074. optionCount++;
  97075. }
  97076. if (optionCount > 1) {
  97077. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97078. }
  97079. }
  97080. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97081. /**
  97082. * The name of the behavior
  97083. */
  97084. get: function () {
  97085. return "PointerDrag";
  97086. },
  97087. enumerable: true,
  97088. configurable: true
  97089. });
  97090. /**
  97091. * Initializes the behavior
  97092. */
  97093. PointerDragBehavior.prototype.init = function () { };
  97094. /**
  97095. * Attaches the drag behavior the passed in mesh
  97096. * @param ownerNode The mesh that will be dragged around once attached
  97097. */
  97098. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97099. var _this = this;
  97100. this._scene = ownerNode.getScene();
  97101. this._attachedNode = ownerNode;
  97102. // Initialize drag plane to not interfere with existing scene
  97103. if (!PointerDragBehavior._planeScene) {
  97104. if (this._debugMode) {
  97105. PointerDragBehavior._planeScene = this._scene;
  97106. }
  97107. else {
  97108. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97109. PointerDragBehavior._planeScene.detachControl();
  97110. this._scene.getEngine().scenes.pop();
  97111. this._scene.onDisposeObservable.addOnce(function () {
  97112. PointerDragBehavior._planeScene.dispose();
  97113. PointerDragBehavior._planeScene = null;
  97114. });
  97115. }
  97116. }
  97117. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97118. // State of the drag
  97119. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97120. var pickPredicate = function (m) {
  97121. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97122. };
  97123. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97124. if (!_this.enabled) {
  97125. return;
  97126. }
  97127. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97128. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97129. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97130. }
  97131. }
  97132. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97133. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97134. _this.releaseDrag();
  97135. }
  97136. }
  97137. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97138. var pointerId = pointerInfo.event.pointerId;
  97139. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97140. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97141. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97142. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97143. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97144. }
  97145. _this.currentDraggingPointerID = pointerId;
  97146. }
  97147. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97148. if (!_this._lastPointerRay[pointerId]) {
  97149. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97150. }
  97151. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97152. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97153. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97154. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97155. _this._moveDrag(pointerInfo.pickInfo.ray);
  97156. }
  97157. }
  97158. }
  97159. });
  97160. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97161. if (_this._moving && _this.moveAttached) {
  97162. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97163. // Slowly move mesh to avoid jitter
  97164. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97165. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97166. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97167. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97168. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  97169. }
  97170. });
  97171. };
  97172. /**
  97173. * Force relase the drag action by code.
  97174. */
  97175. PointerDragBehavior.prototype.releaseDrag = function () {
  97176. this.dragging = false;
  97177. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  97178. this.currentDraggingPointerID = -1;
  97179. this._moving = false;
  97180. // Reattach camera controls
  97181. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97182. this._scene.activeCamera.attachControl(this._attachedElement, true);
  97183. }
  97184. };
  97185. /**
  97186. * Simulates the start of a pointer drag event on the behavior
  97187. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  97188. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  97189. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  97190. */
  97191. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  97192. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  97193. this._startDrag(pointerId, fromRay, startPickedPoint);
  97194. var lastRay = this._lastPointerRay[pointerId];
  97195. if (pointerId === PointerDragBehavior._AnyMouseID) {
  97196. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  97197. }
  97198. if (lastRay) {
  97199. // if there was a last pointer ray drag the object there
  97200. this._moveDrag(lastRay);
  97201. }
  97202. };
  97203. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  97204. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  97205. return;
  97206. }
  97207. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  97208. // Create start ray from the camera to the object
  97209. if (fromRay) {
  97210. this._startDragRay.direction.copyFrom(fromRay.direction);
  97211. this._startDragRay.origin.copyFrom(fromRay.origin);
  97212. }
  97213. else {
  97214. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  97215. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  97216. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  97217. }
  97218. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  97219. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  97220. if (pickedPoint) {
  97221. this.dragging = true;
  97222. this.currentDraggingPointerID = pointerId;
  97223. this.lastDragPosition.copyFrom(pickedPoint);
  97224. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  97225. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  97226. // Detatch camera controls
  97227. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97228. if (this._scene.activeCamera.inputs.attachedElement) {
  97229. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  97230. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  97231. }
  97232. else {
  97233. this._attachedElement = null;
  97234. }
  97235. }
  97236. }
  97237. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  97238. };
  97239. PointerDragBehavior.prototype._moveDrag = function (ray) {
  97240. this._moving = true;
  97241. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  97242. if (pickedPoint) {
  97243. if (this.updateDragPlane) {
  97244. this._updateDragPlanePosition(ray, pickedPoint);
  97245. }
  97246. var dragLength = 0;
  97247. // depending on the drag mode option drag accordingly
  97248. if (this._options.dragAxis) {
  97249. // Convert local drag axis to world
  97250. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  97251. // Project delta drag from the drag plane onto the drag axis
  97252. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  97253. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  97254. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  97255. }
  97256. else {
  97257. dragLength = this._dragDelta.length();
  97258. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  97259. }
  97260. this._targetPosition.addInPlace(this._dragDelta);
  97261. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  97262. this.lastDragPosition.copyFrom(pickedPoint);
  97263. }
  97264. };
  97265. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  97266. var _this = this;
  97267. if (!ray) {
  97268. return null;
  97269. }
  97270. // Calculate angle between plane normal and ray
  97271. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  97272. // Correct if ray is casted from oposite side
  97273. if (angle > Math.PI / 2) {
  97274. angle = Math.PI - angle;
  97275. }
  97276. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  97277. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  97278. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  97279. // Invert ray direction along the towards object axis
  97280. this._tmpVector.copyFrom(ray.direction);
  97281. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  97282. this._alternatePickedPoint.normalize();
  97283. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  97284. this._tmpVector.addInPlace(this._alternatePickedPoint);
  97285. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  97286. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  97287. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  97288. this._alternatePickedPoint.addInPlace(this._tmpVector);
  97289. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  97290. return this._alternatePickedPoint;
  97291. }
  97292. else {
  97293. return null;
  97294. }
  97295. }
  97296. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  97297. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  97298. return pickResult.pickedPoint;
  97299. }
  97300. else {
  97301. return null;
  97302. }
  97303. };
  97304. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  97305. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  97306. this._pointA.copyFrom(dragPlanePosition);
  97307. if (this._options.dragAxis) {
  97308. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  97309. // Calculate plane normal in direction of camera but perpendicular to drag axis
  97310. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  97311. ray.origin.subtractToRef(this._pointA, this._pointC);
  97312. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  97313. // Get perpendicular line from direction to camera and drag axis
  97314. this._pointB.subtractToRef(this._pointA, this._lineA);
  97315. this._pointC.subtractToRef(this._pointA, this._lineB);
  97316. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  97317. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  97318. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  97319. this._lookAt.normalize();
  97320. this._dragPlane.position.copyFrom(this._pointA);
  97321. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  97322. this._dragPlane.lookAt(this._lookAt);
  97323. }
  97324. else if (this._options.dragPlaneNormal) {
  97325. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  97326. this._dragPlane.position.copyFrom(this._pointA);
  97327. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  97328. this._dragPlane.lookAt(this._lookAt);
  97329. }
  97330. else {
  97331. this._dragPlane.position.copyFrom(this._pointA);
  97332. this._dragPlane.lookAt(ray.origin);
  97333. }
  97334. this._dragPlane.computeWorldMatrix(true);
  97335. };
  97336. /**
  97337. * Detaches the behavior from the mesh
  97338. */
  97339. PointerDragBehavior.prototype.detach = function () {
  97340. if (this._pointerObserver) {
  97341. this._scene.onPointerObservable.remove(this._pointerObserver);
  97342. }
  97343. if (this._beforeRenderObserver) {
  97344. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  97345. }
  97346. };
  97347. PointerDragBehavior._AnyMouseID = -2;
  97348. return PointerDragBehavior;
  97349. }());
  97350. BABYLON.PointerDragBehavior = PointerDragBehavior;
  97351. })(BABYLON || (BABYLON = {}));
  97352. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  97353. var BABYLON;
  97354. (function (BABYLON) {
  97355. /**
  97356. * A behavior that when attached to a mesh will allow the mesh to be scaled
  97357. */
  97358. var MultiPointerScaleBehavior = /** @class */ (function () {
  97359. /**
  97360. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  97361. */
  97362. function MultiPointerScaleBehavior() {
  97363. this._startDistance = 0;
  97364. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  97365. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  97366. this._sceneRenderObserver = null;
  97367. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  97368. this._dragBehaviorA.moveAttached = false;
  97369. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  97370. this._dragBehaviorB.moveAttached = false;
  97371. }
  97372. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  97373. /**
  97374. * The name of the behavior
  97375. */
  97376. get: function () {
  97377. return "MultiPointerScale";
  97378. },
  97379. enumerable: true,
  97380. configurable: true
  97381. });
  97382. /**
  97383. * Initializes the behavior
  97384. */
  97385. MultiPointerScaleBehavior.prototype.init = function () { };
  97386. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  97387. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  97388. };
  97389. /**
  97390. * Attaches the scale behavior the passed in mesh
  97391. * @param ownerNode The mesh that will be scaled around once attached
  97392. */
  97393. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  97394. var _this = this;
  97395. this._ownerNode = ownerNode;
  97396. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  97397. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  97398. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97399. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  97400. _this._dragBehaviorA.releaseDrag();
  97401. }
  97402. else {
  97403. _this._initialScale.copyFrom(ownerNode.scaling);
  97404. _this._startDistance = _this._getCurrentDistance();
  97405. }
  97406. }
  97407. });
  97408. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  97409. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97410. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  97411. _this._dragBehaviorB.releaseDrag();
  97412. }
  97413. else {
  97414. _this._initialScale.copyFrom(ownerNode.scaling);
  97415. _this._startDistance = _this._getCurrentDistance();
  97416. }
  97417. }
  97418. });
  97419. // Once both drag behaviors are active scale based on the distance between the two pointers
  97420. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  97421. behavior.onDragObservable.add(function () {
  97422. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97423. var ratio = _this._getCurrentDistance() / _this._startDistance;
  97424. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  97425. }
  97426. });
  97427. });
  97428. ownerNode.addBehavior(this._dragBehaviorA);
  97429. ownerNode.addBehavior(this._dragBehaviorB);
  97430. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  97431. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  97432. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  97433. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  97434. if (change.length() > 0.01) {
  97435. ownerNode.scaling.addInPlace(change);
  97436. }
  97437. }
  97438. });
  97439. };
  97440. /**
  97441. * Detaches the behavior from the mesh
  97442. */
  97443. MultiPointerScaleBehavior.prototype.detach = function () {
  97444. var _this = this;
  97445. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  97446. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  97447. behavior.onDragStartObservable.clear();
  97448. behavior.onDragObservable.clear();
  97449. _this._ownerNode.removeBehavior(behavior);
  97450. });
  97451. };
  97452. return MultiPointerScaleBehavior;
  97453. }());
  97454. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  97455. })(BABYLON || (BABYLON = {}));
  97456. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  97457. var BABYLON;
  97458. (function (BABYLON) {
  97459. /**
  97460. * 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
  97461. */
  97462. var SixDofDragBehavior = /** @class */ (function () {
  97463. /**
  97464. * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  97465. */
  97466. function SixDofDragBehavior() {
  97467. this._sceneRenderObserver = null;
  97468. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97469. this._moving = false;
  97470. this._startingOrientation = new BABYLON.Quaternion();
  97471. /**
  97472. * 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)
  97473. */
  97474. this.zDragFactor = 3;
  97475. /**
  97476. * If the behavior is currently in a dragging state
  97477. */
  97478. this.dragging = false;
  97479. /**
  97480. * 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)
  97481. */
  97482. this.dragDeltaRatio = 0.2;
  97483. /**
  97484. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97485. */
  97486. this.currentDraggingPointerID = -1;
  97487. /**
  97488. * If camera controls should be detached during the drag
  97489. */
  97490. this.detachCameraControls = true;
  97491. /**
  97492. * Fires each time a drag starts
  97493. */
  97494. this.onDragStartObservable = new BABYLON.Observable();
  97495. /**
  97496. * Fires each time a drag ends (eg. mouse release after drag)
  97497. */
  97498. this.onDragEndObservable = new BABYLON.Observable();
  97499. }
  97500. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  97501. /**
  97502. * The name of the behavior
  97503. */
  97504. get: function () {
  97505. return "SixDofDrag";
  97506. },
  97507. enumerable: true,
  97508. configurable: true
  97509. });
  97510. /**
  97511. * Initializes the behavior
  97512. */
  97513. SixDofDragBehavior.prototype.init = function () { };
  97514. /**
  97515. * Attaches the scale behavior the passed in mesh
  97516. * @param ownerNode The mesh that will be scaled around once attached
  97517. */
  97518. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  97519. var _this = this;
  97520. this._ownerNode = ownerNode;
  97521. this._scene = this._ownerNode.getScene();
  97522. if (!SixDofDragBehavior._virtualScene) {
  97523. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  97524. this._scene.getEngine().scenes.pop();
  97525. }
  97526. var pickedMesh = null;
  97527. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  97528. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  97529. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  97530. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  97531. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  97532. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  97533. var pickPredicate = function (m) {
  97534. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  97535. };
  97536. var attachedElement = null;
  97537. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97538. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97539. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97540. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  97541. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  97542. }
  97543. pickedMesh = _this._ownerNode;
  97544. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  97545. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  97546. // Set position and orientation of the controller
  97547. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  97548. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  97549. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  97550. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97551. pickedMesh.computeWorldMatrix();
  97552. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  97553. if (!pickedMesh.rotationQuaternion) {
  97554. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  97555. }
  97556. var oldParent = pickedMesh.parent;
  97557. pickedMesh.setParent(null);
  97558. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  97559. pickedMesh.setParent(oldParent);
  97560. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  97561. // Update state
  97562. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  97563. _this.dragging = true;
  97564. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  97565. // Detatch camera controls
  97566. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  97567. if (_this._scene.activeCamera.inputs.attachedElement) {
  97568. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  97569. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  97570. }
  97571. else {
  97572. attachedElement = null;
  97573. }
  97574. }
  97575. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  97576. _this.onDragStartObservable.notifyObservers({});
  97577. }
  97578. }
  97579. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97580. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97581. _this.dragging = false;
  97582. _this._moving = false;
  97583. _this.currentDraggingPointerID = -1;
  97584. pickedMesh = null;
  97585. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97586. // Reattach camera controls
  97587. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  97588. _this._scene.activeCamera.attachControl(attachedElement, true);
  97589. }
  97590. _this.onDragEndObservable.notifyObservers({});
  97591. }
  97592. }
  97593. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97594. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  97595. var zDragFactor = _this.zDragFactor;
  97596. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  97597. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  97598. zDragFactor = 0;
  97599. }
  97600. // Calculate controller drag distance in controller space
  97601. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  97602. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  97603. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  97604. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  97605. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  97606. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  97607. if (_this._virtualDragMesh.position.z < 0) {
  97608. _this._virtualDragMesh.position.z = 0;
  97609. }
  97610. // Update the controller position
  97611. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  97612. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  97613. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  97614. // Move the virtualObjectsPosition into the picked mesh's space if needed
  97615. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  97616. if (pickedMesh.parent) {
  97617. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  97618. }
  97619. if (!_this._moving) {
  97620. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  97621. }
  97622. _this._moving = true;
  97623. }
  97624. }
  97625. });
  97626. var tmpQuaternion = new BABYLON.Quaternion();
  97627. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  97628. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  97629. if (_this.dragging && _this._moving && pickedMesh) {
  97630. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  97631. // Slowly move mesh to avoid jitter
  97632. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  97633. // Get change in rotation
  97634. tmpQuaternion.copyFrom(_this._startingOrientation);
  97635. tmpQuaternion.x = -tmpQuaternion.x;
  97636. tmpQuaternion.y = -tmpQuaternion.y;
  97637. tmpQuaternion.z = -tmpQuaternion.z;
  97638. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  97639. // Convert change in rotation to only y axis rotation
  97640. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  97641. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  97642. // Slowly move mesh to avoid jitter
  97643. var oldParent = pickedMesh.parent;
  97644. pickedMesh.setParent(null);
  97645. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  97646. pickedMesh.setParent(oldParent);
  97647. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  97648. }
  97649. });
  97650. };
  97651. /**
  97652. * Detaches the behavior from the mesh
  97653. */
  97654. SixDofDragBehavior.prototype.detach = function () {
  97655. if (this._scene) {
  97656. this._scene.onPointerObservable.remove(this._pointerObserver);
  97657. }
  97658. if (this._ownerNode) {
  97659. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  97660. }
  97661. if (this._virtualOriginMesh) {
  97662. this._virtualOriginMesh.dispose();
  97663. }
  97664. if (this._virtualDragMesh) {
  97665. this._virtualDragMesh.dispose();
  97666. }
  97667. this.onDragEndObservable.clear();
  97668. this.onDragStartObservable.clear();
  97669. };
  97670. return SixDofDragBehavior;
  97671. }());
  97672. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  97673. })(BABYLON || (BABYLON = {}));
  97674. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  97675. var BABYLON;
  97676. (function (BABYLON) {
  97677. /**
  97678. * @hidden
  97679. */
  97680. var FaceDirectionInfo = /** @class */ (function () {
  97681. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  97682. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  97683. if (diff === void 0) { diff = 0; }
  97684. if (ignore === void 0) { ignore = false; }
  97685. this.direction = direction;
  97686. this.rotatedDirection = rotatedDirection;
  97687. this.diff = diff;
  97688. this.ignore = ignore;
  97689. }
  97690. return FaceDirectionInfo;
  97691. }());
  97692. /**
  97693. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  97694. */
  97695. var AttachToBoxBehavior = /** @class */ (function () {
  97696. /**
  97697. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  97698. * @param ui The transform node that should be attched to the mesh
  97699. */
  97700. function AttachToBoxBehavior(ui) {
  97701. this.ui = ui;
  97702. /**
  97703. * The name of the behavior
  97704. */
  97705. this.name = "AttachToBoxBehavior";
  97706. /**
  97707. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  97708. */
  97709. this.distanceAwayFromFace = 0.15;
  97710. /**
  97711. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  97712. */
  97713. this.distanceAwayFromBottomOfFace = 0.15;
  97714. 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))];
  97715. this._tmpMatrix = new BABYLON.Matrix();
  97716. this._tmpVector = new BABYLON.Vector3();
  97717. this._zeroVector = BABYLON.Vector3.Zero();
  97718. this._lookAtTmpMatrix = new BABYLON.Matrix();
  97719. /* Does nothing */
  97720. }
  97721. /**
  97722. * Initializes the behavior
  97723. */
  97724. AttachToBoxBehavior.prototype.init = function () {
  97725. /* Does nothing */
  97726. };
  97727. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  97728. var _this = this;
  97729. // Go over each face and calculate the angle between the face's normal and targetDirection
  97730. this._faceVectors.forEach(function (v) {
  97731. if (!_this._target.rotationQuaternion) {
  97732. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  97733. }
  97734. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  97735. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  97736. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  97737. });
  97738. // Return the face information of the one with the normal closeset to target direction
  97739. return this._faceVectors.reduce(function (min, p) {
  97740. if (min.ignore) {
  97741. return p;
  97742. }
  97743. else if (p.ignore) {
  97744. return min;
  97745. }
  97746. else {
  97747. return min.diff < p.diff ? min : p;
  97748. }
  97749. }, this._faceVectors[0]);
  97750. };
  97751. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  97752. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  97753. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  97754. this._lookAtTmpMatrix.invert();
  97755. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  97756. };
  97757. /**
  97758. * Attaches the AttachToBoxBehavior to the passed in mesh
  97759. * @param target The mesh that the specified node will be attached to
  97760. */
  97761. AttachToBoxBehavior.prototype.attach = function (target) {
  97762. var _this = this;
  97763. this._target = target;
  97764. this._scene = this._target.getScene();
  97765. // Every frame, update the app bars position
  97766. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97767. if (!_this._scene.activeCamera) {
  97768. return;
  97769. }
  97770. // Find the face closest to the cameras position
  97771. var cameraPos = _this._scene.activeCamera.position;
  97772. if (_this._scene.activeCamera.devicePosition) {
  97773. cameraPos = _this._scene.activeCamera.devicePosition;
  97774. }
  97775. var facing = _this._closestFace(cameraPos.subtract(target.position));
  97776. if (_this._scene.activeCamera.leftCamera) {
  97777. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  97778. }
  97779. else {
  97780. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  97781. }
  97782. // Get camera up direction
  97783. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  97784. // Ignore faces to not select a parrelel face for the up vector of the UI
  97785. _this._faceVectors.forEach(function (v) {
  97786. if (facing.direction.x && v.direction.x) {
  97787. v.ignore = true;
  97788. }
  97789. if (facing.direction.y && v.direction.y) {
  97790. v.ignore = true;
  97791. }
  97792. if (facing.direction.z && v.direction.z) {
  97793. v.ignore = true;
  97794. }
  97795. });
  97796. var facingUp = _this._closestFace(_this._tmpVector);
  97797. // Unignore faces
  97798. _this._faceVectors.forEach(function (v) {
  97799. v.ignore = false;
  97800. });
  97801. // Position the app bar on that face
  97802. _this.ui.position.copyFrom(target.position);
  97803. if (facing.direction.x) {
  97804. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97805. _this.ui.position.addInPlace(_this._tmpVector);
  97806. }
  97807. if (facing.direction.y) {
  97808. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97809. _this.ui.position.addInPlace(_this._tmpVector);
  97810. }
  97811. if (facing.direction.z) {
  97812. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  97813. _this.ui.position.addInPlace(_this._tmpVector);
  97814. }
  97815. // Rotate to be oriented properly to the camera
  97816. if (!_this.ui.rotationQuaternion) {
  97817. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  97818. }
  97819. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  97820. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  97821. // Place ui the correct distance from the bottom of the mesh
  97822. if (facingUp.direction.x) {
  97823. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  97824. }
  97825. if (facingUp.direction.y) {
  97826. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  97827. }
  97828. if (facingUp.direction.z) {
  97829. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  97830. }
  97831. _this.ui.position.addInPlace(_this._tmpVector);
  97832. });
  97833. };
  97834. /**
  97835. * Detaches the behavior from the mesh
  97836. */
  97837. AttachToBoxBehavior.prototype.detach = function () {
  97838. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  97839. };
  97840. return AttachToBoxBehavior;
  97841. }());
  97842. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  97843. })(BABYLON || (BABYLON = {}));
  97844. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  97845. var BABYLON;
  97846. (function (BABYLON) {
  97847. /**
  97848. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  97849. */
  97850. var FadeInOutBehavior = /** @class */ (function () {
  97851. /**
  97852. * Instatiates the FadeInOutBehavior
  97853. */
  97854. function FadeInOutBehavior() {
  97855. var _this = this;
  97856. /**
  97857. * Time in milliseconds to delay before fading in (Default: 0)
  97858. */
  97859. this.delay = 0;
  97860. /**
  97861. * Time in milliseconds for the mesh to fade in (Default: 300)
  97862. */
  97863. this.fadeInTime = 300;
  97864. this._millisecondsPerFrame = 1000 / 60;
  97865. this._hovered = false;
  97866. this._hoverValue = 0;
  97867. this._ownerNode = null;
  97868. this._update = function () {
  97869. if (_this._ownerNode) {
  97870. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  97871. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  97872. if (_this._ownerNode.visibility > 1) {
  97873. _this._setAllVisibility(_this._ownerNode, 1);
  97874. _this._hoverValue = _this.fadeInTime + _this.delay;
  97875. return;
  97876. }
  97877. else if (_this._ownerNode.visibility < 0) {
  97878. _this._setAllVisibility(_this._ownerNode, 0);
  97879. if (_this._hoverValue < 0) {
  97880. _this._hoverValue = 0;
  97881. return;
  97882. }
  97883. }
  97884. setTimeout(_this._update, _this._millisecondsPerFrame);
  97885. }
  97886. };
  97887. }
  97888. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  97889. /**
  97890. * The name of the behavior
  97891. */
  97892. get: function () {
  97893. return "FadeInOut";
  97894. },
  97895. enumerable: true,
  97896. configurable: true
  97897. });
  97898. /**
  97899. * Initializes the behavior
  97900. */
  97901. FadeInOutBehavior.prototype.init = function () {
  97902. };
  97903. /**
  97904. * Attaches the fade behavior on the passed in mesh
  97905. * @param ownerNode The mesh that will be faded in/out once attached
  97906. */
  97907. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  97908. this._ownerNode = ownerNode;
  97909. this._setAllVisibility(this._ownerNode, 0);
  97910. };
  97911. /**
  97912. * Detaches the behavior from the mesh
  97913. */
  97914. FadeInOutBehavior.prototype.detach = function () {
  97915. this._ownerNode = null;
  97916. };
  97917. /**
  97918. * Triggers the mesh to begin fading in or out
  97919. * @param value if the object should fade in or out (true to fade in)
  97920. */
  97921. FadeInOutBehavior.prototype.fadeIn = function (value) {
  97922. this._hovered = value;
  97923. this._update();
  97924. };
  97925. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  97926. var _this = this;
  97927. mesh.visibility = value;
  97928. mesh.getChildMeshes().forEach(function (c) {
  97929. _this._setAllVisibility(c, value);
  97930. });
  97931. };
  97932. return FadeInOutBehavior;
  97933. }());
  97934. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  97935. })(BABYLON || (BABYLON = {}));
  97936. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  97937. var BABYLON;
  97938. (function (BABYLON) {
  97939. /**
  97940. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  97941. */
  97942. var Gizmo = /** @class */ (function () {
  97943. /**
  97944. * Creates a gizmo
  97945. * @param gizmoLayer The utility layer the gizmo will be added to
  97946. */
  97947. function Gizmo(
  97948. /** The utility layer the gizmo will be added to */
  97949. gizmoLayer) {
  97950. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97951. var _this = this;
  97952. this.gizmoLayer = gizmoLayer;
  97953. /**
  97954. * Ratio for the scale of the gizmo (Default: 1)
  97955. */
  97956. this.scaleRatio = 1;
  97957. this._tmpMatrix = new BABYLON.Matrix();
  97958. /**
  97959. * If a custom mesh has been set (Default: false)
  97960. */
  97961. this._customMeshSet = false;
  97962. /**
  97963. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  97964. */
  97965. this.updateGizmoRotationToMatchAttachedMesh = true;
  97966. /**
  97967. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  97968. */
  97969. this.updateGizmoPositionToMatchAttachedMesh = true;
  97970. /**
  97971. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  97972. */
  97973. this._updateScale = true;
  97974. this._interactionsEnabled = true;
  97975. this._tempVector = new BABYLON.Vector3();
  97976. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  97977. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  97978. _this._update();
  97979. });
  97980. this.attachedMesh = null;
  97981. }
  97982. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  97983. /**
  97984. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  97985. * * When set, interactions will be enabled
  97986. */
  97987. get: function () {
  97988. return this._attachedMesh;
  97989. },
  97990. set: function (value) {
  97991. this._attachedMesh = value;
  97992. this._rootMesh.setEnabled(value ? true : false);
  97993. this._attachedMeshChanged(value);
  97994. },
  97995. enumerable: true,
  97996. configurable: true
  97997. });
  97998. /**
  97999. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98000. * @param mesh The mesh to replace the default mesh of the gizmo
  98001. */
  98002. Gizmo.prototype.setCustomMesh = function (mesh) {
  98003. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  98004. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  98005. }
  98006. this._rootMesh.getChildMeshes().forEach(function (c) {
  98007. c.dispose();
  98008. });
  98009. mesh.parent = this._rootMesh;
  98010. this._customMeshSet = true;
  98011. };
  98012. Gizmo.prototype._attachedMeshChanged = function (value) {
  98013. };
  98014. /**
  98015. * @hidden
  98016. * Updates the gizmo to match the attached mesh's position/rotation
  98017. */
  98018. Gizmo.prototype._update = function () {
  98019. if (this.attachedMesh) {
  98020. if (this.updateGizmoRotationToMatchAttachedMesh) {
  98021. if (!this._rootMesh.rotationQuaternion) {
  98022. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  98023. }
  98024. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  98025. this._tempVector.copyFrom(this.attachedMesh.scaling);
  98026. if (this.attachedMesh.scaling.x < 0) {
  98027. this.attachedMesh.scaling.x *= -1;
  98028. }
  98029. if (this.attachedMesh.scaling.y < 0) {
  98030. this.attachedMesh.scaling.y *= -1;
  98031. }
  98032. if (this.attachedMesh.scaling.z < 0) {
  98033. this.attachedMesh.scaling.z *= -1;
  98034. }
  98035. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98036. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98037. this.attachedMesh.computeWorldMatrix();
  98038. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98039. }
  98040. else if (this._rootMesh.rotationQuaternion) {
  98041. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98042. }
  98043. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98044. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98045. }
  98046. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98047. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98048. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98049. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98050. }
  98051. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98052. var dist = this._tempVector.length() * this.scaleRatio;
  98053. this._rootMesh.scaling.set(dist, dist, dist);
  98054. }
  98055. }
  98056. };
  98057. /**
  98058. * Disposes of the gizmo
  98059. */
  98060. Gizmo.prototype.dispose = function () {
  98061. this._rootMesh.dispose();
  98062. if (this._beforeRenderObserver) {
  98063. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98064. }
  98065. };
  98066. return Gizmo;
  98067. }());
  98068. BABYLON.Gizmo = Gizmo;
  98069. })(BABYLON || (BABYLON = {}));
  98070. //# sourceMappingURL=babylon.gizmo.js.map
  98071. var BABYLON;
  98072. (function (BABYLON) {
  98073. /**
  98074. * Single axis drag gizmo
  98075. */
  98076. var AxisDragGizmo = /** @class */ (function (_super) {
  98077. __extends(AxisDragGizmo, _super);
  98078. /**
  98079. * Creates an AxisDragGizmo
  98080. * @param gizmoLayer The utility layer the gizmo will be added to
  98081. * @param dragAxis The axis which the gizmo will be able to drag on
  98082. * @param color The color of the gizmo
  98083. */
  98084. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98085. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98086. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98087. var _this = _super.call(this, gizmoLayer) || this;
  98088. _this._pointerObserver = null;
  98089. /**
  98090. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98091. */
  98092. _this.snapDistance = 0;
  98093. /**
  98094. * Event that fires each time the gizmo snaps to a new location.
  98095. * * snapDistance is the the change in distance
  98096. */
  98097. _this.onSnapObservable = new BABYLON.Observable();
  98098. // Create Material
  98099. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98100. coloredMaterial.disableLighting = true;
  98101. coloredMaterial.emissiveColor = color;
  98102. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98103. hoverMaterial.disableLighting = true;
  98104. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98105. // Build mesh on root node
  98106. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98107. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98108. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98109. arrowTail.color = coloredMaterial.emissiveColor;
  98110. arrow.addChild(arrowMesh);
  98111. arrow.addChild(arrowTail);
  98112. // Position arrow pointing in its drag axis
  98113. arrowMesh.scaling.scaleInPlace(0.05);
  98114. arrowMesh.material = coloredMaterial;
  98115. arrowMesh.rotation.x = Math.PI / 2;
  98116. arrowMesh.position.z += 0.3;
  98117. arrowTail.scaling.scaleInPlace(0.26);
  98118. arrowTail.rotation.x = Math.PI / 2;
  98119. arrowTail.material = coloredMaterial;
  98120. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98121. arrow.scaling.scaleInPlace(1 / 3);
  98122. _this._rootMesh.addChild(arrow);
  98123. var currentSnapDragDistance = 0;
  98124. var tmpVector = new BABYLON.Vector3();
  98125. var tmpSnapEvent = { snapDistance: 0 };
  98126. // Add drag behavior to handle events when the gizmo is dragged
  98127. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98128. _this.dragBehavior.moveAttached = false;
  98129. _this._rootMesh.addBehavior(_this.dragBehavior);
  98130. var localDelta = new BABYLON.Vector3();
  98131. var tmpMatrix = new BABYLON.Matrix();
  98132. _this.dragBehavior.onDragObservable.add(function (event) {
  98133. if (_this.attachedMesh) {
  98134. // Convert delta to local translation if it has a parent
  98135. if (_this.attachedMesh.parent) {
  98136. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98137. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98138. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98139. }
  98140. else {
  98141. localDelta.copyFrom(event.delta);
  98142. }
  98143. // Snapping logic
  98144. if (_this.snapDistance == 0) {
  98145. _this.attachedMesh.position.addInPlace(localDelta);
  98146. }
  98147. else {
  98148. currentSnapDragDistance += event.dragDistance;
  98149. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98150. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98151. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98152. localDelta.normalizeToRef(tmpVector);
  98153. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98154. _this.attachedMesh.position.addInPlace(tmpVector);
  98155. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98156. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98157. }
  98158. }
  98159. }
  98160. });
  98161. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98162. if (_this._customMeshSet) {
  98163. return;
  98164. }
  98165. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98166. var material = isHovered ? hoverMaterial : coloredMaterial;
  98167. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98168. m.material = material;
  98169. if (m.color) {
  98170. m.color = material.emissiveColor;
  98171. }
  98172. });
  98173. });
  98174. return _this;
  98175. }
  98176. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  98177. if (this.dragBehavior) {
  98178. this.dragBehavior.enabled = value ? true : false;
  98179. }
  98180. };
  98181. /**
  98182. * Disposes of the gizmo
  98183. */
  98184. AxisDragGizmo.prototype.dispose = function () {
  98185. this.onSnapObservable.clear();
  98186. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98187. this.dragBehavior.detach();
  98188. _super.prototype.dispose.call(this);
  98189. };
  98190. return AxisDragGizmo;
  98191. }(BABYLON.Gizmo));
  98192. BABYLON.AxisDragGizmo = AxisDragGizmo;
  98193. })(BABYLON || (BABYLON = {}));
  98194. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  98195. var BABYLON;
  98196. (function (BABYLON) {
  98197. /**
  98198. * Single axis scale gizmo
  98199. */
  98200. var AxisScaleGizmo = /** @class */ (function (_super) {
  98201. __extends(AxisScaleGizmo, _super);
  98202. /**
  98203. * Creates an AxisScaleGizmo
  98204. * @param gizmoLayer The utility layer the gizmo will be added to
  98205. * @param dragAxis The axis which the gizmo will be able to scale on
  98206. * @param color The color of the gizmo
  98207. */
  98208. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  98209. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98210. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98211. var _this = _super.call(this, gizmoLayer) || this;
  98212. _this._pointerObserver = null;
  98213. /**
  98214. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98215. */
  98216. _this.snapDistance = 0;
  98217. /**
  98218. * Event that fires each time the gizmo snaps to a new location.
  98219. * * snapDistance is the the change in distance
  98220. */
  98221. _this.onSnapObservable = new BABYLON.Observable();
  98222. /**
  98223. * If the scaling operation should be done on all axis (default: false)
  98224. */
  98225. _this.uniformScaling = false;
  98226. // Create Material
  98227. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98228. _this._coloredMaterial.disableLighting = true;
  98229. _this._coloredMaterial.emissiveColor = color;
  98230. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98231. hoverMaterial.disableLighting = true;
  98232. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98233. // Build mesh on root node
  98234. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98235. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  98236. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98237. arrowTail.color = _this._coloredMaterial.emissiveColor;
  98238. arrow.addChild(arrowMesh);
  98239. arrow.addChild(arrowTail);
  98240. // Position arrow pointing in its drag axis
  98241. arrowMesh.scaling.scaleInPlace(0.1);
  98242. arrowMesh.material = _this._coloredMaterial;
  98243. arrowMesh.rotation.x = Math.PI / 2;
  98244. arrowMesh.position.z += 0.3;
  98245. arrowTail.scaling.scaleInPlace(0.26);
  98246. arrowTail.rotation.x = Math.PI / 2;
  98247. arrowTail.material = _this._coloredMaterial;
  98248. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98249. _this._rootMesh.addChild(arrow);
  98250. arrow.scaling.scaleInPlace(1 / 3);
  98251. // Add drag behavior to handle events when the gizmo is dragged
  98252. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98253. _this.dragBehavior.moveAttached = false;
  98254. _this._rootMesh.addBehavior(_this.dragBehavior);
  98255. var currentSnapDragDistance = 0;
  98256. var tmpVector = new BABYLON.Vector3();
  98257. var tmpSnapEvent = { snapDistance: 0 };
  98258. _this.dragBehavior.onDragObservable.add(function (event) {
  98259. if (_this.attachedMesh) {
  98260. // Snapping logic
  98261. var snapped = false;
  98262. var dragSteps = 0;
  98263. if (_this.uniformScaling) {
  98264. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  98265. if (tmpVector.y < 0) {
  98266. tmpVector.scaleInPlace(-1);
  98267. }
  98268. }
  98269. else {
  98270. tmpVector.copyFrom(dragAxis);
  98271. }
  98272. if (_this.snapDistance == 0) {
  98273. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  98274. }
  98275. else {
  98276. currentSnapDragDistance += event.dragDistance;
  98277. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98278. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  98279. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98280. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  98281. snapped = true;
  98282. }
  98283. else {
  98284. tmpVector.scaleInPlace(0);
  98285. }
  98286. }
  98287. _this.attachedMesh.scaling.addInPlace(tmpVector);
  98288. if (snapped) {
  98289. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98290. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98291. }
  98292. }
  98293. });
  98294. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98295. if (_this._customMeshSet) {
  98296. return;
  98297. }
  98298. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98299. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  98300. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98301. m.material = material;
  98302. if (m.color) {
  98303. m.color = material.emissiveColor;
  98304. }
  98305. });
  98306. });
  98307. return _this;
  98308. }
  98309. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  98310. if (this.dragBehavior) {
  98311. this.dragBehavior.enabled = value ? true : false;
  98312. }
  98313. };
  98314. /**
  98315. * Disposes of the gizmo
  98316. */
  98317. AxisScaleGizmo.prototype.dispose = function () {
  98318. this.onSnapObservable.clear();
  98319. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98320. this.dragBehavior.detach();
  98321. _super.prototype.dispose.call(this);
  98322. };
  98323. /**
  98324. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98325. * @param mesh The mesh to replace the default mesh of the gizmo
  98326. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  98327. */
  98328. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  98329. var _this = this;
  98330. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  98331. _super.prototype.setCustomMesh.call(this, mesh);
  98332. if (useGizmoMaterial) {
  98333. this._rootMesh.getChildMeshes().forEach(function (m) {
  98334. m.material = _this._coloredMaterial;
  98335. if (m.color) {
  98336. m.color = _this._coloredMaterial.emissiveColor;
  98337. }
  98338. });
  98339. this._customMeshSet = false;
  98340. }
  98341. };
  98342. return AxisScaleGizmo;
  98343. }(BABYLON.Gizmo));
  98344. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  98345. })(BABYLON || (BABYLON = {}));
  98346. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  98347. var BABYLON;
  98348. (function (BABYLON) {
  98349. /**
  98350. * Single plane rotation gizmo
  98351. */
  98352. var PlaneRotationGizmo = /** @class */ (function (_super) {
  98353. __extends(PlaneRotationGizmo, _super);
  98354. /**
  98355. * Creates a PlaneRotationGizmo
  98356. * @param gizmoLayer The utility layer the gizmo will be added to
  98357. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  98358. * @param color The color of the gizmo
  98359. */
  98360. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  98361. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98362. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98363. var _this = _super.call(this, gizmoLayer) || this;
  98364. _this._pointerObserver = null;
  98365. /**
  98366. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  98367. */
  98368. _this.snapDistance = 0;
  98369. /**
  98370. * Event that fires each time the gizmo snaps to a new location.
  98371. * * snapDistance is the the change in distance
  98372. */
  98373. _this.onSnapObservable = new BABYLON.Observable();
  98374. // Create Material
  98375. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98376. coloredMaterial.disableLighting = true;
  98377. coloredMaterial.emissiveColor = color;
  98378. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98379. hoverMaterial.disableLighting = true;
  98380. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98381. // Build mesh on root node
  98382. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98383. // Create circle out of lines
  98384. var tessellation = 20;
  98385. var radius = 0.8;
  98386. var points = new Array();
  98387. for (var i = 0; i < tessellation; i++) {
  98388. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  98389. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  98390. }
  98391. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  98392. rotationMesh.color = coloredMaterial.emissiveColor;
  98393. // Position arrow pointing in its drag axis
  98394. rotationMesh.scaling.scaleInPlace(0.26);
  98395. rotationMesh.material = coloredMaterial;
  98396. rotationMesh.rotation.x = Math.PI / 2;
  98397. parentMesh.addChild(rotationMesh);
  98398. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  98399. _this._rootMesh.addChild(parentMesh);
  98400. parentMesh.scaling.scaleInPlace(1 / 3);
  98401. // Add drag behavior to handle events when the gizmo is dragged
  98402. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  98403. _this.dragBehavior.moveAttached = false;
  98404. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  98405. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  98406. _this._rootMesh.addBehavior(_this.dragBehavior);
  98407. var lastDragPosition = new BABYLON.Vector3();
  98408. _this.dragBehavior.onDragStartObservable.add(function (e) {
  98409. if (_this.attachedMesh) {
  98410. lastDragPosition.copyFrom(e.dragPlanePoint);
  98411. }
  98412. });
  98413. var rotationMatrix = new BABYLON.Matrix();
  98414. var planeNormalTowardsCamera = new BABYLON.Vector3();
  98415. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  98416. var tmpSnapEvent = { snapDistance: 0 };
  98417. var currentSnapDragDistance = 0;
  98418. var tmpMatrix = new BABYLON.Matrix();
  98419. var tmpVector = new BABYLON.Vector3();
  98420. var amountToRotate = new BABYLON.Quaternion();
  98421. _this.dragBehavior.onDragObservable.add(function (event) {
  98422. if (_this.attachedMesh) {
  98423. if (!_this.attachedMesh.rotationQuaternion) {
  98424. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98425. }
  98426. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  98427. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  98428. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  98429. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  98430. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  98431. var angle = Math.atan2(cross.length(), dot);
  98432. planeNormalTowardsCamera.copyFrom(planeNormal);
  98433. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  98434. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  98435. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  98436. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  98437. }
  98438. // Flip up vector depending on which side the camera is on
  98439. if (gizmoLayer.utilityLayerScene.activeCamera) {
  98440. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  98441. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  98442. planeNormalTowardsCamera.scaleInPlace(-1);
  98443. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  98444. }
  98445. }
  98446. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  98447. if (halfCircleSide)
  98448. angle = -angle;
  98449. // Snapping logic
  98450. var snapped = false;
  98451. if (_this.snapDistance != 0) {
  98452. currentSnapDragDistance += angle;
  98453. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98454. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  98455. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98456. angle = _this.snapDistance * dragSteps;
  98457. snapped = true;
  98458. }
  98459. else {
  98460. angle = 0;
  98461. }
  98462. }
  98463. // If the mesh has a parent, convert needed world rotation to local rotation
  98464. tmpMatrix.reset();
  98465. if (_this.attachedMesh.parent) {
  98466. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98467. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  98468. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  98469. }
  98470. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  98471. var quaternionCoefficient = Math.sin(angle / 2);
  98472. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  98473. // 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
  98474. if (tmpMatrix.determinant() > 0) {
  98475. amountToRotate.toEulerAnglesToRef(tmpVector);
  98476. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  98477. }
  98478. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  98479. // Rotate selected mesh quaternion over fixed axis
  98480. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  98481. }
  98482. else {
  98483. // Rotate selected mesh quaternion over rotated axis
  98484. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  98485. }
  98486. lastDragPosition.copyFrom(event.dragPlanePoint);
  98487. if (snapped) {
  98488. tmpSnapEvent.snapDistance = angle;
  98489. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98490. }
  98491. }
  98492. });
  98493. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98494. if (_this._customMeshSet) {
  98495. return;
  98496. }
  98497. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98498. var material = isHovered ? hoverMaterial : coloredMaterial;
  98499. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98500. m.material = material;
  98501. if (m.color) {
  98502. m.color = material.emissiveColor;
  98503. }
  98504. });
  98505. });
  98506. return _this;
  98507. }
  98508. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  98509. if (this.dragBehavior) {
  98510. this.dragBehavior.enabled = value ? true : false;
  98511. }
  98512. };
  98513. /**
  98514. * Disposes of the gizmo
  98515. */
  98516. PlaneRotationGizmo.prototype.dispose = function () {
  98517. this.onSnapObservable.clear();
  98518. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98519. this.dragBehavior.detach();
  98520. _super.prototype.dispose.call(this);
  98521. };
  98522. return PlaneRotationGizmo;
  98523. }(BABYLON.Gizmo));
  98524. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  98525. })(BABYLON || (BABYLON = {}));
  98526. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  98527. var BABYLON;
  98528. (function (BABYLON) {
  98529. /**
  98530. * Gizmo that enables dragging a mesh along 3 axis
  98531. */
  98532. var PositionGizmo = /** @class */ (function (_super) {
  98533. __extends(PositionGizmo, _super);
  98534. /**
  98535. * Creates a PositionGizmo
  98536. * @param gizmoLayer The utility layer the gizmo will be added to
  98537. */
  98538. function PositionGizmo(gizmoLayer) {
  98539. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98540. var _this = _super.call(this, gizmoLayer) || this;
  98541. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98542. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98543. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98544. _this.attachedMesh = null;
  98545. return _this;
  98546. }
  98547. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  98548. set: function (mesh) {
  98549. if (this.xGizmo) {
  98550. this.xGizmo.attachedMesh = mesh;
  98551. this.yGizmo.attachedMesh = mesh;
  98552. this.zGizmo.attachedMesh = mesh;
  98553. }
  98554. },
  98555. enumerable: true,
  98556. configurable: true
  98557. });
  98558. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98559. get: function () {
  98560. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98561. },
  98562. set: function (value) {
  98563. if (this.xGizmo) {
  98564. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98565. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98566. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98567. }
  98568. },
  98569. enumerable: true,
  98570. configurable: true
  98571. });
  98572. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  98573. get: function () {
  98574. return this.xGizmo.snapDistance;
  98575. },
  98576. /**
  98577. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98578. */
  98579. set: function (value) {
  98580. if (this.xGizmo) {
  98581. this.xGizmo.snapDistance = value;
  98582. this.yGizmo.snapDistance = value;
  98583. this.zGizmo.snapDistance = value;
  98584. }
  98585. },
  98586. enumerable: true,
  98587. configurable: true
  98588. });
  98589. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  98590. get: function () {
  98591. return this.xGizmo.scaleRatio;
  98592. },
  98593. /**
  98594. * Ratio for the scale of the gizmo (Default: 1)
  98595. */
  98596. set: function (value) {
  98597. if (this.xGizmo) {
  98598. this.xGizmo.scaleRatio = value;
  98599. this.yGizmo.scaleRatio = value;
  98600. this.zGizmo.scaleRatio = value;
  98601. }
  98602. },
  98603. enumerable: true,
  98604. configurable: true
  98605. });
  98606. /**
  98607. * Disposes of the gizmo
  98608. */
  98609. PositionGizmo.prototype.dispose = function () {
  98610. this.xGizmo.dispose();
  98611. this.yGizmo.dispose();
  98612. this.zGizmo.dispose();
  98613. };
  98614. /**
  98615. * CustomMeshes are not supported by this gizmo
  98616. * @param mesh The mesh to replace the default mesh of the gizmo
  98617. */
  98618. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  98619. 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)");
  98620. };
  98621. return PositionGizmo;
  98622. }(BABYLON.Gizmo));
  98623. BABYLON.PositionGizmo = PositionGizmo;
  98624. })(BABYLON || (BABYLON = {}));
  98625. //# sourceMappingURL=babylon.positionGizmo.js.map
  98626. var BABYLON;
  98627. (function (BABYLON) {
  98628. /**
  98629. * Gizmo that enables rotating a mesh along 3 axis
  98630. */
  98631. var RotationGizmo = /** @class */ (function (_super) {
  98632. __extends(RotationGizmo, _super);
  98633. /**
  98634. * Creates a RotationGizmo
  98635. * @param gizmoLayer The utility layer the gizmo will be added to
  98636. */
  98637. function RotationGizmo(gizmoLayer) {
  98638. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98639. var _this = _super.call(this, gizmoLayer) || this;
  98640. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98641. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98642. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98643. _this.attachedMesh = null;
  98644. return _this;
  98645. }
  98646. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  98647. set: function (mesh) {
  98648. if (this.xGizmo) {
  98649. this.xGizmo.attachedMesh = mesh;
  98650. this.yGizmo.attachedMesh = mesh;
  98651. this.zGizmo.attachedMesh = mesh;
  98652. }
  98653. },
  98654. enumerable: true,
  98655. configurable: true
  98656. });
  98657. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98658. get: function () {
  98659. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98660. },
  98661. set: function (value) {
  98662. if (this.xGizmo) {
  98663. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98664. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98665. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98666. }
  98667. },
  98668. enumerable: true,
  98669. configurable: true
  98670. });
  98671. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  98672. get: function () {
  98673. return this.xGizmo.snapDistance;
  98674. },
  98675. /**
  98676. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98677. */
  98678. set: function (value) {
  98679. if (this.xGizmo) {
  98680. this.xGizmo.snapDistance = value;
  98681. this.yGizmo.snapDistance = value;
  98682. this.zGizmo.snapDistance = value;
  98683. }
  98684. },
  98685. enumerable: true,
  98686. configurable: true
  98687. });
  98688. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  98689. get: function () {
  98690. return this.xGizmo.scaleRatio;
  98691. },
  98692. /**
  98693. * Ratio for the scale of the gizmo (Default: 1)
  98694. */
  98695. set: function (value) {
  98696. if (this.xGizmo) {
  98697. this.xGizmo.scaleRatio = value;
  98698. this.yGizmo.scaleRatio = value;
  98699. this.zGizmo.scaleRatio = value;
  98700. }
  98701. },
  98702. enumerable: true,
  98703. configurable: true
  98704. });
  98705. /**
  98706. * Disposes of the gizmo
  98707. */
  98708. RotationGizmo.prototype.dispose = function () {
  98709. this.xGizmo.dispose();
  98710. this.yGizmo.dispose();
  98711. this.zGizmo.dispose();
  98712. };
  98713. /**
  98714. * CustomMeshes are not supported by this gizmo
  98715. * @param mesh The mesh to replace the default mesh of the gizmo
  98716. */
  98717. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  98718. 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)");
  98719. };
  98720. return RotationGizmo;
  98721. }(BABYLON.Gizmo));
  98722. BABYLON.RotationGizmo = RotationGizmo;
  98723. })(BABYLON || (BABYLON = {}));
  98724. //# sourceMappingURL=babylon.rotationGizmo.js.map
  98725. var BABYLON;
  98726. (function (BABYLON) {
  98727. /**
  98728. * Gizmo that enables scaling a mesh along 3 axis
  98729. */
  98730. var ScaleGizmo = /** @class */ (function (_super) {
  98731. __extends(ScaleGizmo, _super);
  98732. /**
  98733. * Creates a ScaleGizmo
  98734. * @param gizmoLayer The utility layer the gizmo will be added to
  98735. */
  98736. function ScaleGizmo(gizmoLayer) {
  98737. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98738. var _this = _super.call(this, gizmoLayer) || this;
  98739. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  98740. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  98741. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  98742. // Create uniform scale gizmo
  98743. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  98744. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98745. _this.uniformScaleGizmo.uniformScaling = true;
  98746. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  98747. octahedron.scaling.scaleInPlace(0.007);
  98748. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  98749. _this.attachedMesh = null;
  98750. return _this;
  98751. }
  98752. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  98753. set: function (mesh) {
  98754. if (this.xGizmo) {
  98755. this.xGizmo.attachedMesh = mesh;
  98756. this.yGizmo.attachedMesh = mesh;
  98757. this.zGizmo.attachedMesh = mesh;
  98758. this.uniformScaleGizmo.attachedMesh = mesh;
  98759. }
  98760. },
  98761. enumerable: true,
  98762. configurable: true
  98763. });
  98764. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  98765. get: function () {
  98766. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  98767. },
  98768. set: function (value) {
  98769. if (this.xGizmo) {
  98770. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98771. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98772. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  98773. }
  98774. },
  98775. enumerable: true,
  98776. configurable: true
  98777. });
  98778. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  98779. get: function () {
  98780. return this.xGizmo.snapDistance;
  98781. },
  98782. /**
  98783. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98784. */
  98785. set: function (value) {
  98786. if (this.xGizmo) {
  98787. this.xGizmo.snapDistance = value;
  98788. this.yGizmo.snapDistance = value;
  98789. this.zGizmo.snapDistance = value;
  98790. this.uniformScaleGizmo.snapDistance = value;
  98791. }
  98792. },
  98793. enumerable: true,
  98794. configurable: true
  98795. });
  98796. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  98797. get: function () {
  98798. return this.xGizmo.scaleRatio;
  98799. },
  98800. /**
  98801. * Ratio for the scale of the gizmo (Default: 1)
  98802. */
  98803. set: function (value) {
  98804. if (this.xGizmo) {
  98805. this.xGizmo.scaleRatio = value;
  98806. this.yGizmo.scaleRatio = value;
  98807. this.zGizmo.scaleRatio = value;
  98808. this.uniformScaleGizmo.scaleRatio = value;
  98809. }
  98810. },
  98811. enumerable: true,
  98812. configurable: true
  98813. });
  98814. /**
  98815. * Disposes of the gizmo
  98816. */
  98817. ScaleGizmo.prototype.dispose = function () {
  98818. this.xGizmo.dispose();
  98819. this.yGizmo.dispose();
  98820. this.zGizmo.dispose();
  98821. this.uniformScaleGizmo.dispose();
  98822. };
  98823. return ScaleGizmo;
  98824. }(BABYLON.Gizmo));
  98825. BABYLON.ScaleGizmo = ScaleGizmo;
  98826. })(BABYLON || (BABYLON = {}));
  98827. //# sourceMappingURL=babylon.scaleGizmo.js.map
  98828. var BABYLON;
  98829. (function (BABYLON) {
  98830. /**
  98831. * Bounding box gizmo
  98832. */
  98833. var BoundingBoxGizmo = /** @class */ (function (_super) {
  98834. __extends(BoundingBoxGizmo, _super);
  98835. /**
  98836. * Creates an BoundingBoxGizmo
  98837. * @param gizmoLayer The utility layer the gizmo will be added to
  98838. * @param color The color of the gizmo
  98839. */
  98840. function BoundingBoxGizmo(color, gizmoLayer) {
  98841. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98842. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  98843. var _this = _super.call(this, gizmoLayer) || this;
  98844. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  98845. _this._renderObserver = null;
  98846. _this._pointerObserver = null;
  98847. _this._scaleDragSpeed = 0.2;
  98848. _this._tmpQuaternion = new BABYLON.Quaternion();
  98849. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  98850. _this._tmpRotationMatrix = new BABYLON.Matrix();
  98851. /**
  98852. * 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)
  98853. */
  98854. _this.ignoreChildren = false;
  98855. /**
  98856. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  98857. */
  98858. _this.includeChildPredicate = null;
  98859. /**
  98860. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  98861. */
  98862. _this.rotationSphereSize = 0.1;
  98863. /**
  98864. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  98865. */
  98866. _this.scaleBoxSize = 0.1;
  98867. /**
  98868. * 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)
  98869. */
  98870. _this.fixedDragMeshScreenSize = false;
  98871. /**
  98872. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  98873. */
  98874. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  98875. /**
  98876. * Fired when a rotation sphere or scale box is dragged
  98877. */
  98878. _this.onDragStartObservable = new BABYLON.Observable();
  98879. /**
  98880. * Fired when a scale box is dragged
  98881. */
  98882. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  98883. /**
  98884. * Fired when a scale box drag is ended
  98885. */
  98886. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  98887. /**
  98888. * Fired when a rotation sphere is dragged
  98889. */
  98890. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  98891. /**
  98892. * Fired when a rotation sphere drag is ended
  98893. */
  98894. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  98895. /**
  98896. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  98897. */
  98898. _this.scalePivot = null;
  98899. _this._existingMeshScale = new BABYLON.Vector3();
  98900. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  98901. _this._updateScale = false;
  98902. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  98903. // Create Materials
  98904. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98905. coloredMaterial.disableLighting = true;
  98906. coloredMaterial.emissiveColor = color;
  98907. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98908. hoverColoredMaterial.disableLighting = true;
  98909. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98910. // Build bounding box out of lines
  98911. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98912. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  98913. var lines = [];
  98914. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  98915. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  98916. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  98917. 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));
  98918. 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));
  98919. 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));
  98920. 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));
  98921. 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));
  98922. 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));
  98923. 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));
  98924. 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));
  98925. 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));
  98926. lines.forEach(function (l) {
  98927. l.color = color;
  98928. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  98929. l.isPickable = false;
  98930. _this._lineBoundingBox.addChild(l);
  98931. });
  98932. _this._rootMesh.addChild(_this._lineBoundingBox);
  98933. // Create rotation spheres
  98934. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98935. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  98936. var _loop_1 = function (i_1) {
  98937. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  98938. sphere.rotationQuaternion = new BABYLON.Quaternion();
  98939. sphere.material = coloredMaterial;
  98940. // Drag behavior
  98941. _dragBehavior = new BABYLON.PointerDragBehavior({});
  98942. _dragBehavior.moveAttached = false;
  98943. _dragBehavior.updateDragPlane = false;
  98944. sphere.addBehavior(_dragBehavior);
  98945. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  98946. var totalTurnAmountOfDrag = 0;
  98947. _dragBehavior.onDragStartObservable.add(function (event) {
  98948. startingTurnDirection.copyFrom(sphere.forward);
  98949. totalTurnAmountOfDrag = 0;
  98950. });
  98951. _dragBehavior.onDragObservable.add(function (event) {
  98952. _this.onRotationSphereDragObservable.notifyObservers({});
  98953. if (_this.attachedMesh) {
  98954. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98955. var worldDragDirection = startingTurnDirection;
  98956. // Project the world right on to the drag plane
  98957. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  98958. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  98959. // project drag delta on to the resulting drag axis and rotate based on that
  98960. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  98961. // Make rotation relative to size of mesh.
  98962. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98963. // Rotate based on axis
  98964. if (!_this.attachedMesh.rotationQuaternion) {
  98965. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98966. }
  98967. if (!_this._anchorMesh.rotationQuaternion) {
  98968. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  98969. }
  98970. // Do not allow the object to turn more than a full circle
  98971. totalTurnAmountOfDrag += projectDist;
  98972. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  98973. if (i_1 >= 8) {
  98974. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  98975. }
  98976. else if (i_1 >= 4) {
  98977. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  98978. }
  98979. else {
  98980. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  98981. }
  98982. // Rotate around center of bounding box
  98983. _this._anchorMesh.addChild(_this.attachedMesh);
  98984. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  98985. _this._anchorMesh.removeChild(_this.attachedMesh);
  98986. }
  98987. _this.updateBoundingBox();
  98988. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98989. }
  98990. });
  98991. // Selection/deselection
  98992. _dragBehavior.onDragStartObservable.add(function () {
  98993. _this.onDragStartObservable.notifyObservers({});
  98994. _this._selectNode(sphere);
  98995. });
  98996. _dragBehavior.onDragEndObservable.add(function () {
  98997. _this.onRotationSphereDragEndObservable.notifyObservers({});
  98998. _this._selectNode(null);
  98999. });
  99000. this_1._rotateSpheresParent.addChild(sphere);
  99001. };
  99002. var this_1 = this, _dragBehavior;
  99003. for (var i_1 = 0; i_1 < 12; i_1++) {
  99004. _loop_1(i_1);
  99005. }
  99006. _this._rootMesh.addChild(_this._rotateSpheresParent);
  99007. // Create scale cubes
  99008. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99009. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  99010. for (var i = 0; i < 2; i++) {
  99011. for (var j = 0; j < 2; j++) {
  99012. var _loop_2 = function () {
  99013. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  99014. box.material = coloredMaterial;
  99015. // Dragging logic
  99016. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  99017. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99018. _dragBehavior.moveAttached = false;
  99019. box.addBehavior(_dragBehavior);
  99020. _dragBehavior.onDragObservable.add(function (event) {
  99021. _this.onScaleBoxDragObservable.notifyObservers({});
  99022. if (_this.attachedMesh) {
  99023. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99024. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99025. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  99026. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99027. _this.updateBoundingBox();
  99028. if (_this.scalePivot) {
  99029. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99030. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99031. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99032. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99033. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99034. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99035. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99036. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99037. }
  99038. else {
  99039. // Scale from the position of the opposite corner
  99040. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99041. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99042. }
  99043. _this._anchorMesh.addChild(_this.attachedMesh);
  99044. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99045. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99046. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99047. }
  99048. _this._anchorMesh.removeChild(_this.attachedMesh);
  99049. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99050. }
  99051. });
  99052. // Selection/deselection
  99053. _dragBehavior.onDragStartObservable.add(function () {
  99054. _this.onDragStartObservable.notifyObservers({});
  99055. _this._selectNode(box);
  99056. });
  99057. _dragBehavior.onDragEndObservable.add(function () {
  99058. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99059. _this._selectNode(null);
  99060. });
  99061. this_2._scaleBoxesParent.addChild(box);
  99062. };
  99063. var this_2 = this, _dragBehavior;
  99064. for (var k = 0; k < 2; k++) {
  99065. _loop_2();
  99066. }
  99067. }
  99068. }
  99069. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99070. // Hover color change
  99071. var pointerIds = new Array();
  99072. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99073. if (!pointerIds[pointerInfo.event.pointerId]) {
  99074. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99075. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99076. pointerIds[pointerInfo.event.pointerId] = mesh;
  99077. mesh.material = hoverColoredMaterial;
  99078. }
  99079. });
  99080. }
  99081. else {
  99082. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99083. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99084. delete pointerIds[pointerInfo.event.pointerId];
  99085. }
  99086. }
  99087. });
  99088. // Update bounding box positions
  99089. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99090. // Only update the bouding box if scaling has changed
  99091. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99092. _this.updateBoundingBox();
  99093. }
  99094. });
  99095. _this.updateBoundingBox();
  99096. return _this;
  99097. }
  99098. /** @hidden */
  99099. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99100. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99101. // Save old pivot and set pivot to 0,0,0
  99102. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99103. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99104. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99105. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99106. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99107. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99108. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99109. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99110. }
  99111. }
  99112. BoundingBoxGizmo._PivotCached++;
  99113. };
  99114. /** @hidden */
  99115. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99116. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99117. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99118. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99119. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99120. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99121. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99122. }
  99123. this._PivotCached--;
  99124. };
  99125. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99126. if (value) {
  99127. // Reset anchor mesh to match attached mesh's scale
  99128. // This is needed to avoid invalid box/sphere position on first drag
  99129. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99130. this._anchorMesh.addChild(value);
  99131. this._anchorMesh.removeChild(value);
  99132. BoundingBoxGizmo._RestorePivotPoint(value);
  99133. this.updateBoundingBox();
  99134. }
  99135. };
  99136. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99137. this._rotateSpheresParent.getChildMeshes()
  99138. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99139. m.isVisible = (!selectedMesh || m == selectedMesh);
  99140. });
  99141. };
  99142. /**
  99143. * Updates the bounding box information for the Gizmo
  99144. */
  99145. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99146. if (this.attachedMesh) {
  99147. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99148. this._update();
  99149. // Rotate based on axis
  99150. if (!this.attachedMesh.rotationQuaternion) {
  99151. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99152. }
  99153. if (!this._anchorMesh.rotationQuaternion) {
  99154. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99155. }
  99156. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99157. // Store original position and reset mesh to origin before computing the bounding box
  99158. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99159. this._tmpVector.copyFrom(this.attachedMesh.position);
  99160. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99161. this.attachedMesh.position.set(0, 0, 0);
  99162. // Update bounding dimensions/positions
  99163. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99164. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99165. // Update gizmo to match bounding box scaling and rotation
  99166. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99167. 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);
  99168. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  99169. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  99170. this._lineBoundingBox.computeWorldMatrix();
  99171. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  99172. // restore position/rotation values
  99173. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  99174. this.attachedMesh.position.copyFrom(this._tmpVector);
  99175. }
  99176. // Update rotation sphere locations
  99177. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  99178. for (var i = 0; i < 3; i++) {
  99179. for (var j = 0; j < 2; j++) {
  99180. for (var k = 0; k < 2; k++) {
  99181. var index = ((i * 4) + (j * 2)) + k;
  99182. if (i == 0) {
  99183. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99184. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99185. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99186. }
  99187. if (i == 1) {
  99188. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  99189. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99190. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99191. }
  99192. if (i == 2) {
  99193. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  99194. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99195. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99196. }
  99197. if (this.fixedDragMeshScreenSize) {
  99198. this._rootMesh.computeWorldMatrix();
  99199. this._rotateSpheresParent.computeWorldMatrix();
  99200. rotateSpheres[index].computeWorldMatrix();
  99201. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99202. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99203. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99204. }
  99205. else {
  99206. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  99207. }
  99208. }
  99209. }
  99210. }
  99211. // Update scale box locations
  99212. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  99213. for (var i = 0; i < 2; i++) {
  99214. for (var j = 0; j < 2; j++) {
  99215. for (var k = 0; k < 2; k++) {
  99216. var index = ((i * 4) + (j * 2)) + k;
  99217. if (scaleBoxes[index]) {
  99218. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99219. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99220. if (this.fixedDragMeshScreenSize) {
  99221. this._rootMesh.computeWorldMatrix();
  99222. this._scaleBoxesParent.computeWorldMatrix();
  99223. scaleBoxes[index].computeWorldMatrix();
  99224. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  99225. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  99226. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  99227. }
  99228. else {
  99229. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  99230. }
  99231. }
  99232. }
  99233. }
  99234. }
  99235. if (this.attachedMesh) {
  99236. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  99237. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  99238. }
  99239. };
  99240. /**
  99241. * Enables rotation on the specified axis and disables rotation on the others
  99242. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  99243. */
  99244. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  99245. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  99246. if (i < 4) {
  99247. m.setEnabled(axis.indexOf("x") != -1);
  99248. }
  99249. else if (i < 8) {
  99250. m.setEnabled(axis.indexOf("y") != -1);
  99251. }
  99252. else {
  99253. m.setEnabled(axis.indexOf("z") != -1);
  99254. }
  99255. });
  99256. };
  99257. /**
  99258. * Disposes of the gizmo
  99259. */
  99260. BoundingBoxGizmo.prototype.dispose = function () {
  99261. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99262. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  99263. this._lineBoundingBox.dispose();
  99264. this._rotateSpheresParent.dispose();
  99265. this._scaleBoxesParent.dispose();
  99266. _super.prototype.dispose.call(this);
  99267. };
  99268. /**
  99269. * 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)
  99270. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  99271. * @returns the bounding box mesh with the passed in mesh as a child
  99272. */
  99273. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  99274. var makeNotPickable = function (root) {
  99275. root.isPickable = false;
  99276. root.getChildMeshes().forEach(function (c) {
  99277. makeNotPickable(c);
  99278. });
  99279. };
  99280. makeNotPickable(mesh);
  99281. // Reset position to get boudning box from origin with no rotation
  99282. if (!mesh.rotationQuaternion) {
  99283. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  99284. }
  99285. var oldPos = mesh.position.clone();
  99286. var oldRot = mesh.rotationQuaternion.clone();
  99287. mesh.rotationQuaternion.set(0, 0, 0, 1);
  99288. mesh.position.set(0, 0, 0);
  99289. // Update bounding dimensions/positions
  99290. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  99291. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  99292. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  99293. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  99294. // Restore original positions
  99295. mesh.addChild(box);
  99296. mesh.rotationQuaternion.copyFrom(oldRot);
  99297. mesh.position.copyFrom(oldPos);
  99298. // Reverse parenting
  99299. mesh.removeChild(box);
  99300. box.addChild(mesh);
  99301. box.visibility = 0;
  99302. return box;
  99303. };
  99304. /**
  99305. * CustomMeshes are not supported by this gizmo
  99306. * @param mesh The mesh to replace the default mesh of the gizmo
  99307. */
  99308. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  99309. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  99310. };
  99311. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  99312. // store/remove pivot point should only be applied during their outermost calls
  99313. BoundingBoxGizmo._PivotCached = 0;
  99314. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  99315. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  99316. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  99317. return BoundingBoxGizmo;
  99318. }(BABYLON.Gizmo));
  99319. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  99320. })(BABYLON || (BABYLON = {}));
  99321. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  99322. var BABYLON;
  99323. (function (BABYLON) {
  99324. /**
  99325. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  99326. */
  99327. var GizmoManager = /** @class */ (function () {
  99328. /**
  99329. * Instatiates a gizmo manager
  99330. * @param scene the scene to overlay the gizmos on top of
  99331. */
  99332. function GizmoManager(scene) {
  99333. var _this = this;
  99334. this.scene = scene;
  99335. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  99336. this._pointerObserver = null;
  99337. this._attachedMesh = null;
  99338. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  99339. /**
  99340. * When bounding box gizmo is enabled, this can be used to track drag/end events
  99341. */
  99342. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  99343. /**
  99344. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  99345. */
  99346. this.attachableMeshes = null;
  99347. /**
  99348. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  99349. */
  99350. this.usePointerToAttachGizmos = true;
  99351. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  99352. // Instatiate/dispose gizmos based on pointer actions
  99353. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  99354. if (!_this.usePointerToAttachGizmos) {
  99355. return;
  99356. }
  99357. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99358. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  99359. var node = pointerInfo.pickInfo.pickedMesh;
  99360. if (_this.attachableMeshes == null) {
  99361. // Attach to the most parent node
  99362. while (node && node.parent != null) {
  99363. node = node.parent;
  99364. }
  99365. }
  99366. else {
  99367. // Attach to the parent node that is an attachableMesh
  99368. var found = false;
  99369. _this.attachableMeshes.forEach(function (mesh) {
  99370. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  99371. node = mesh;
  99372. found = true;
  99373. }
  99374. });
  99375. if (!found) {
  99376. node = null;
  99377. }
  99378. }
  99379. if (node instanceof BABYLON.AbstractMesh) {
  99380. _this.attachToMesh(node);
  99381. }
  99382. else {
  99383. _this.attachToMesh(null);
  99384. }
  99385. }
  99386. else {
  99387. _this.attachToMesh(null);
  99388. }
  99389. }
  99390. });
  99391. }
  99392. /**
  99393. * Attaches a set of gizmos to the specified mesh
  99394. * @param mesh The mesh the gizmo's should be attached to
  99395. */
  99396. GizmoManager.prototype.attachToMesh = function (mesh) {
  99397. if (this._attachedMesh) {
  99398. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  99399. }
  99400. this._attachedMesh = mesh;
  99401. for (var key in this.gizmos) {
  99402. var gizmo = (this.gizmos[key]);
  99403. if (gizmo && this._gizmosEnabled[key]) {
  99404. gizmo.attachedMesh = mesh;
  99405. }
  99406. }
  99407. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  99408. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  99409. }
  99410. };
  99411. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  99412. get: function () {
  99413. return this._gizmosEnabled.positionGizmo;
  99414. },
  99415. /**
  99416. * If the position gizmo is enabled
  99417. */
  99418. set: function (value) {
  99419. if (value) {
  99420. if (!this.gizmos.positionGizmo) {
  99421. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  99422. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99423. }
  99424. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  99425. }
  99426. else if (this.gizmos.positionGizmo) {
  99427. this.gizmos.positionGizmo.attachedMesh = null;
  99428. }
  99429. this._gizmosEnabled.positionGizmo = value;
  99430. },
  99431. enumerable: true,
  99432. configurable: true
  99433. });
  99434. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  99435. get: function () {
  99436. return this._gizmosEnabled.rotationGizmo;
  99437. },
  99438. /**
  99439. * If the rotation gizmo is enabled
  99440. */
  99441. set: function (value) {
  99442. if (value) {
  99443. if (!this.gizmos.rotationGizmo) {
  99444. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  99445. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99446. }
  99447. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  99448. }
  99449. else if (this.gizmos.rotationGizmo) {
  99450. this.gizmos.rotationGizmo.attachedMesh = null;
  99451. }
  99452. this._gizmosEnabled.rotationGizmo = value;
  99453. },
  99454. enumerable: true,
  99455. configurable: true
  99456. });
  99457. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  99458. get: function () {
  99459. return this._gizmosEnabled.scaleGizmo;
  99460. },
  99461. /**
  99462. * If the scale gizmo is enabled
  99463. */
  99464. set: function (value) {
  99465. if (value) {
  99466. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  99467. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  99468. }
  99469. else if (this.gizmos.scaleGizmo) {
  99470. this.gizmos.scaleGizmo.attachedMesh = null;
  99471. }
  99472. this._gizmosEnabled.scaleGizmo = value;
  99473. },
  99474. enumerable: true,
  99475. configurable: true
  99476. });
  99477. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  99478. get: function () {
  99479. return this._gizmosEnabled.boundingBoxGizmo;
  99480. },
  99481. /**
  99482. * If the boundingBox gizmo is enabled
  99483. */
  99484. set: function (value) {
  99485. if (value) {
  99486. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  99487. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  99488. if (this._attachedMesh) {
  99489. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  99490. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  99491. }
  99492. }
  99493. else if (this.gizmos.boundingBoxGizmo) {
  99494. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  99495. }
  99496. this._gizmosEnabled.boundingBoxGizmo = value;
  99497. },
  99498. enumerable: true,
  99499. configurable: true
  99500. });
  99501. /**
  99502. * Disposes of the gizmo manager
  99503. */
  99504. GizmoManager.prototype.dispose = function () {
  99505. this.scene.onPointerObservable.remove(this._pointerObserver);
  99506. for (var key in this.gizmos) {
  99507. var gizmo = (this.gizmos[key]);
  99508. if (gizmo) {
  99509. gizmo.dispose();
  99510. }
  99511. }
  99512. this.boundingBoxDragBehavior.detach();
  99513. };
  99514. return GizmoManager;
  99515. }());
  99516. BABYLON.GizmoManager = GizmoManager;
  99517. })(BABYLON || (BABYLON = {}));
  99518. //# sourceMappingURL=babylon.gizmoManager.js.map
  99519. var BABYLON;
  99520. (function (BABYLON) {
  99521. /**
  99522. * Defines a target to use with MorphTargetManager
  99523. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  99524. */
  99525. var MorphTarget = /** @class */ (function () {
  99526. /**
  99527. * Creates a new MorphTarget
  99528. * @param name defines the name of the target
  99529. * @param influence defines the influence to use
  99530. */
  99531. function MorphTarget(
  99532. /** defines the name of the target */
  99533. name, influence, scene) {
  99534. if (influence === void 0) { influence = 0; }
  99535. if (scene === void 0) { scene = null; }
  99536. this.name = name;
  99537. /**
  99538. * Gets or sets the list of animations
  99539. */
  99540. this.animations = new Array();
  99541. this._positions = null;
  99542. this._normals = null;
  99543. this._tangents = null;
  99544. /**
  99545. * Observable raised when the influence changes
  99546. */
  99547. this.onInfluenceChanged = new BABYLON.Observable();
  99548. this._animationPropertiesOverride = null;
  99549. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99550. this.influence = influence;
  99551. }
  99552. Object.defineProperty(MorphTarget.prototype, "influence", {
  99553. /**
  99554. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  99555. */
  99556. get: function () {
  99557. return this._influence;
  99558. },
  99559. set: function (influence) {
  99560. if (this._influence === influence) {
  99561. return;
  99562. }
  99563. var previous = this._influence;
  99564. this._influence = influence;
  99565. if (this.onInfluenceChanged.hasObservers) {
  99566. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  99567. }
  99568. },
  99569. enumerable: true,
  99570. configurable: true
  99571. });
  99572. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  99573. /**
  99574. * Gets or sets the animation properties override
  99575. */
  99576. get: function () {
  99577. if (!this._animationPropertiesOverride && this._scene) {
  99578. return this._scene.animationPropertiesOverride;
  99579. }
  99580. return this._animationPropertiesOverride;
  99581. },
  99582. set: function (value) {
  99583. this._animationPropertiesOverride = value;
  99584. },
  99585. enumerable: true,
  99586. configurable: true
  99587. });
  99588. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  99589. /**
  99590. * Gets a boolean defining if the target contains position data
  99591. */
  99592. get: function () {
  99593. return !!this._positions;
  99594. },
  99595. enumerable: true,
  99596. configurable: true
  99597. });
  99598. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  99599. /**
  99600. * Gets a boolean defining if the target contains normal data
  99601. */
  99602. get: function () {
  99603. return !!this._normals;
  99604. },
  99605. enumerable: true,
  99606. configurable: true
  99607. });
  99608. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  99609. /**
  99610. * Gets a boolean defining if the target contains tangent data
  99611. */
  99612. get: function () {
  99613. return !!this._tangents;
  99614. },
  99615. enumerable: true,
  99616. configurable: true
  99617. });
  99618. /**
  99619. * Affects position data to this target
  99620. * @param data defines the position data to use
  99621. */
  99622. MorphTarget.prototype.setPositions = function (data) {
  99623. this._positions = data;
  99624. };
  99625. /**
  99626. * Gets the position data stored in this target
  99627. * @returns a FloatArray containing the position data (or null if not present)
  99628. */
  99629. MorphTarget.prototype.getPositions = function () {
  99630. return this._positions;
  99631. };
  99632. /**
  99633. * Affects normal data to this target
  99634. * @param data defines the normal data to use
  99635. */
  99636. MorphTarget.prototype.setNormals = function (data) {
  99637. this._normals = data;
  99638. };
  99639. /**
  99640. * Gets the normal data stored in this target
  99641. * @returns a FloatArray containing the normal data (or null if not present)
  99642. */
  99643. MorphTarget.prototype.getNormals = function () {
  99644. return this._normals;
  99645. };
  99646. /**
  99647. * Affects tangent data to this target
  99648. * @param data defines the tangent data to use
  99649. */
  99650. MorphTarget.prototype.setTangents = function (data) {
  99651. this._tangents = data;
  99652. };
  99653. /**
  99654. * Gets the tangent data stored in this target
  99655. * @returns a FloatArray containing the tangent data (or null if not present)
  99656. */
  99657. MorphTarget.prototype.getTangents = function () {
  99658. return this._tangents;
  99659. };
  99660. /**
  99661. * Serializes the current target into a Serialization object
  99662. * @returns the serialized object
  99663. */
  99664. MorphTarget.prototype.serialize = function () {
  99665. var serializationObject = {};
  99666. serializationObject.name = this.name;
  99667. serializationObject.influence = this.influence;
  99668. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  99669. if (this.hasNormals) {
  99670. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  99671. }
  99672. if (this.hasTangents) {
  99673. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  99674. }
  99675. // Animations
  99676. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  99677. return serializationObject;
  99678. };
  99679. // Statics
  99680. /**
  99681. * Creates a new target from serialized data
  99682. * @param serializationObject defines the serialized data to use
  99683. * @returns a new MorphTarget
  99684. */
  99685. MorphTarget.Parse = function (serializationObject) {
  99686. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  99687. result.setPositions(serializationObject.positions);
  99688. if (serializationObject.normals) {
  99689. result.setNormals(serializationObject.normals);
  99690. }
  99691. if (serializationObject.tangents) {
  99692. result.setTangents(serializationObject.tangents);
  99693. }
  99694. // Animations
  99695. if (serializationObject.animations) {
  99696. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  99697. var parsedAnimation = serializationObject.animations[animationIndex];
  99698. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  99699. }
  99700. }
  99701. return result;
  99702. };
  99703. /**
  99704. * Creates a MorphTarget from mesh data
  99705. * @param mesh defines the source mesh
  99706. * @param name defines the name to use for the new target
  99707. * @param influence defines the influence to attach to the target
  99708. * @returns a new MorphTarget
  99709. */
  99710. MorphTarget.FromMesh = function (mesh, name, influence) {
  99711. if (!name) {
  99712. name = mesh.name;
  99713. }
  99714. var result = new MorphTarget(name, influence, mesh.getScene());
  99715. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  99716. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  99717. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  99718. }
  99719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  99720. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  99721. }
  99722. return result;
  99723. };
  99724. return MorphTarget;
  99725. }());
  99726. BABYLON.MorphTarget = MorphTarget;
  99727. })(BABYLON || (BABYLON = {}));
  99728. //# sourceMappingURL=babylon.morphTarget.js.map
  99729. var BABYLON;
  99730. (function (BABYLON) {
  99731. /**
  99732. * This class is used to deform meshes using morphing between different targets
  99733. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  99734. */
  99735. var MorphTargetManager = /** @class */ (function () {
  99736. /**
  99737. * Creates a new MorphTargetManager
  99738. * @param scene defines the current scene
  99739. */
  99740. function MorphTargetManager(scene) {
  99741. if (scene === void 0) { scene = null; }
  99742. this._targets = new Array();
  99743. this._targetObservable = new Array();
  99744. this._activeTargets = new BABYLON.SmartArray(16);
  99745. this._supportsNormals = false;
  99746. this._supportsTangents = false;
  99747. this._vertexCount = 0;
  99748. this._uniqueId = 0;
  99749. this._tempInfluences = new Array();
  99750. if (!scene) {
  99751. scene = BABYLON.Engine.LastCreatedScene;
  99752. }
  99753. this._scene = scene;
  99754. if (this._scene) {
  99755. this._scene.morphTargetManagers.push(this);
  99756. this._uniqueId = this._scene.getUniqueId();
  99757. }
  99758. }
  99759. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  99760. /**
  99761. * Gets the unique ID of this manager
  99762. */
  99763. get: function () {
  99764. return this._uniqueId;
  99765. },
  99766. enumerable: true,
  99767. configurable: true
  99768. });
  99769. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  99770. /**
  99771. * Gets the number of vertices handled by this manager
  99772. */
  99773. get: function () {
  99774. return this._vertexCount;
  99775. },
  99776. enumerable: true,
  99777. configurable: true
  99778. });
  99779. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  99780. /**
  99781. * Gets a boolean indicating if this manager supports morphing of normals
  99782. */
  99783. get: function () {
  99784. return this._supportsNormals;
  99785. },
  99786. enumerable: true,
  99787. configurable: true
  99788. });
  99789. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  99790. /**
  99791. * Gets a boolean indicating if this manager supports morphing of tangents
  99792. */
  99793. get: function () {
  99794. return this._supportsTangents;
  99795. },
  99796. enumerable: true,
  99797. configurable: true
  99798. });
  99799. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  99800. /**
  99801. * Gets the number of targets stored in this manager
  99802. */
  99803. get: function () {
  99804. return this._targets.length;
  99805. },
  99806. enumerable: true,
  99807. configurable: true
  99808. });
  99809. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  99810. /**
  99811. * Gets the number of influencers (ie. the number of targets with influences > 0)
  99812. */
  99813. get: function () {
  99814. return this._activeTargets.length;
  99815. },
  99816. enumerable: true,
  99817. configurable: true
  99818. });
  99819. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  99820. /**
  99821. * Gets the list of influences (one per target)
  99822. */
  99823. get: function () {
  99824. return this._influences;
  99825. },
  99826. enumerable: true,
  99827. configurable: true
  99828. });
  99829. /**
  99830. * Gets the active target at specified index. An active target is a target with an influence > 0
  99831. * @param index defines the index to check
  99832. * @returns the requested target
  99833. */
  99834. MorphTargetManager.prototype.getActiveTarget = function (index) {
  99835. return this._activeTargets.data[index];
  99836. };
  99837. /**
  99838. * Gets the target at specified index
  99839. * @param index defines the index to check
  99840. * @returns the requested target
  99841. */
  99842. MorphTargetManager.prototype.getTarget = function (index) {
  99843. return this._targets[index];
  99844. };
  99845. /**
  99846. * Add a new target to this manager
  99847. * @param target defines the target to add
  99848. */
  99849. MorphTargetManager.prototype.addTarget = function (target) {
  99850. var _this = this;
  99851. this._targets.push(target);
  99852. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  99853. _this._syncActiveTargets(needUpdate);
  99854. }));
  99855. this._syncActiveTargets(true);
  99856. };
  99857. /**
  99858. * Removes a target from the manager
  99859. * @param target defines the target to remove
  99860. */
  99861. MorphTargetManager.prototype.removeTarget = function (target) {
  99862. var index = this._targets.indexOf(target);
  99863. if (index >= 0) {
  99864. this._targets.splice(index, 1);
  99865. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  99866. this._syncActiveTargets(true);
  99867. }
  99868. };
  99869. /**
  99870. * Serializes the current manager into a Serialization object
  99871. * @returns the serialized object
  99872. */
  99873. MorphTargetManager.prototype.serialize = function () {
  99874. var serializationObject = {};
  99875. serializationObject.id = this.uniqueId;
  99876. serializationObject.targets = [];
  99877. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99878. var target = _a[_i];
  99879. serializationObject.targets.push(target.serialize());
  99880. }
  99881. return serializationObject;
  99882. };
  99883. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  99884. var influenceCount = 0;
  99885. this._activeTargets.reset();
  99886. this._supportsNormals = true;
  99887. this._supportsTangents = true;
  99888. this._vertexCount = 0;
  99889. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99890. var target = _a[_i];
  99891. this._activeTargets.push(target);
  99892. this._tempInfluences[influenceCount++] = target.influence;
  99893. var positions = target.getPositions();
  99894. if (positions) {
  99895. this._supportsNormals = this._supportsNormals && target.hasNormals;
  99896. this._supportsTangents = this._supportsTangents && target.hasTangents;
  99897. var vertexCount = positions.length / 3;
  99898. if (this._vertexCount === 0) {
  99899. this._vertexCount = vertexCount;
  99900. }
  99901. else if (this._vertexCount !== vertexCount) {
  99902. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  99903. return;
  99904. }
  99905. }
  99906. }
  99907. if (!this._influences || this._influences.length !== influenceCount) {
  99908. this._influences = new Float32Array(influenceCount);
  99909. }
  99910. for (var index = 0; index < influenceCount; index++) {
  99911. this._influences[index] = this._tempInfluences[index];
  99912. }
  99913. if (needUpdate) {
  99914. this.synchronize();
  99915. }
  99916. };
  99917. /**
  99918. * Syncrhonize the targets with all the meshes using this morph target manager
  99919. */
  99920. MorphTargetManager.prototype.synchronize = function () {
  99921. if (!this._scene) {
  99922. return;
  99923. }
  99924. // Flag meshes as dirty to resync with the active targets
  99925. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  99926. var mesh = _a[_i];
  99927. if (mesh.morphTargetManager === this) {
  99928. mesh._syncGeometryWithMorphTargetManager();
  99929. }
  99930. }
  99931. };
  99932. // Statics
  99933. /**
  99934. * Creates a new MorphTargetManager from serialized data
  99935. * @param serializationObject defines the serialized data
  99936. * @param scene defines the hosting scene
  99937. * @returns the new MorphTargetManager
  99938. */
  99939. MorphTargetManager.Parse = function (serializationObject, scene) {
  99940. var result = new MorphTargetManager(scene);
  99941. result._uniqueId = serializationObject.id;
  99942. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  99943. var targetData = _a[_i];
  99944. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  99945. }
  99946. return result;
  99947. };
  99948. return MorphTargetManager;
  99949. }());
  99950. BABYLON.MorphTargetManager = MorphTargetManager;
  99951. })(BABYLON || (BABYLON = {}));
  99952. //# sourceMappingURL=babylon.morphTargetManager.js.map
  99953. var BABYLON;
  99954. (function (BABYLON) {
  99955. var Octree = /** @class */ (function () {
  99956. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  99957. if (maxDepth === void 0) { maxDepth = 2; }
  99958. this.maxDepth = maxDepth;
  99959. this.dynamicContent = new Array();
  99960. this._maxBlockCapacity = maxBlockCapacity || 64;
  99961. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  99962. this._creationFunc = creationFunc;
  99963. }
  99964. // Methods
  99965. Octree.prototype.update = function (worldMin, worldMax, entries) {
  99966. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  99967. };
  99968. Octree.prototype.addMesh = function (entry) {
  99969. for (var index = 0; index < this.blocks.length; index++) {
  99970. var block = this.blocks[index];
  99971. block.addEntry(entry);
  99972. }
  99973. };
  99974. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  99975. this._selectionContent.reset();
  99976. for (var index = 0; index < this.blocks.length; index++) {
  99977. var block = this.blocks[index];
  99978. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  99979. }
  99980. if (allowDuplicate) {
  99981. this._selectionContent.concat(this.dynamicContent);
  99982. }
  99983. else {
  99984. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99985. }
  99986. return this._selectionContent;
  99987. };
  99988. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  99989. this._selectionContent.reset();
  99990. for (var index = 0; index < this.blocks.length; index++) {
  99991. var block = this.blocks[index];
  99992. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  99993. }
  99994. if (allowDuplicate) {
  99995. this._selectionContent.concat(this.dynamicContent);
  99996. }
  99997. else {
  99998. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99999. }
  100000. return this._selectionContent;
  100001. };
  100002. Octree.prototype.intersectsRay = function (ray) {
  100003. this._selectionContent.reset();
  100004. for (var index = 0; index < this.blocks.length; index++) {
  100005. var block = this.blocks[index];
  100006. block.intersectsRay(ray, this._selectionContent);
  100007. }
  100008. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100009. return this._selectionContent;
  100010. };
  100011. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  100012. target.blocks = new Array();
  100013. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100014. // Segmenting space
  100015. for (var x = 0; x < 2; x++) {
  100016. for (var y = 0; y < 2; y++) {
  100017. for (var z = 0; z < 2; z++) {
  100018. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  100019. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  100020. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  100021. block.addEntries(entries);
  100022. target.blocks.push(block);
  100023. }
  100024. }
  100025. }
  100026. };
  100027. Octree.CreationFuncForMeshes = function (entry, block) {
  100028. var boundingInfo = entry.getBoundingInfo();
  100029. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100030. block.entries.push(entry);
  100031. }
  100032. };
  100033. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100034. var boundingInfo = entry.getBoundingInfo();
  100035. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100036. block.entries.push(entry);
  100037. }
  100038. };
  100039. return Octree;
  100040. }());
  100041. BABYLON.Octree = Octree;
  100042. })(BABYLON || (BABYLON = {}));
  100043. //# sourceMappingURL=babylon.octree.js.map
  100044. var BABYLON;
  100045. (function (BABYLON) {
  100046. /**
  100047. * Class used to store a cell in an octree
  100048. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100049. */
  100050. var OctreeBlock = /** @class */ (function () {
  100051. /**
  100052. * Creates a new block
  100053. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100054. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100055. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100056. * @param depth defines the current depth of this block in the octree
  100057. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100058. * @param creationFunc defines a callback to call when an element is added to the block
  100059. */
  100060. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100061. /**
  100062. * Gets the content of the current block
  100063. */
  100064. this.entries = new Array();
  100065. this._boundingVectors = new Array();
  100066. this._capacity = capacity;
  100067. this._depth = depth;
  100068. this._maxDepth = maxDepth;
  100069. this._creationFunc = creationFunc;
  100070. this._minPoint = minPoint;
  100071. this._maxPoint = maxPoint;
  100072. this._boundingVectors.push(minPoint.clone());
  100073. this._boundingVectors.push(maxPoint.clone());
  100074. this._boundingVectors.push(minPoint.clone());
  100075. this._boundingVectors[2].x = maxPoint.x;
  100076. this._boundingVectors.push(minPoint.clone());
  100077. this._boundingVectors[3].y = maxPoint.y;
  100078. this._boundingVectors.push(minPoint.clone());
  100079. this._boundingVectors[4].z = maxPoint.z;
  100080. this._boundingVectors.push(maxPoint.clone());
  100081. this._boundingVectors[5].z = minPoint.z;
  100082. this._boundingVectors.push(maxPoint.clone());
  100083. this._boundingVectors[6].x = minPoint.x;
  100084. this._boundingVectors.push(maxPoint.clone());
  100085. this._boundingVectors[7].y = minPoint.y;
  100086. }
  100087. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100088. // Property
  100089. /**
  100090. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100091. */
  100092. get: function () {
  100093. return this._capacity;
  100094. },
  100095. enumerable: true,
  100096. configurable: true
  100097. });
  100098. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100099. /**
  100100. * Gets the minimum vector (in world space) of the block's bounding box
  100101. */
  100102. get: function () {
  100103. return this._minPoint;
  100104. },
  100105. enumerable: true,
  100106. configurable: true
  100107. });
  100108. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100109. /**
  100110. * Gets the maximum vector (in world space) of the block's bounding box
  100111. */
  100112. get: function () {
  100113. return this._maxPoint;
  100114. },
  100115. enumerable: true,
  100116. configurable: true
  100117. });
  100118. // Methods
  100119. /**
  100120. * Add a new element to this block
  100121. * @param entry defines the element to add
  100122. */
  100123. OctreeBlock.prototype.addEntry = function (entry) {
  100124. if (this.blocks) {
  100125. for (var index = 0; index < this.blocks.length; index++) {
  100126. var block = this.blocks[index];
  100127. block.addEntry(entry);
  100128. }
  100129. return;
  100130. }
  100131. this._creationFunc(entry, this);
  100132. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  100133. this.createInnerBlocks();
  100134. }
  100135. };
  100136. /**
  100137. * Add an array of elements to this block
  100138. * @param entries defines the array of elements to add
  100139. */
  100140. OctreeBlock.prototype.addEntries = function (entries) {
  100141. for (var index = 0; index < entries.length; index++) {
  100142. var mesh = entries[index];
  100143. this.addEntry(mesh);
  100144. }
  100145. };
  100146. /**
  100147. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  100148. * @param frustumPlanes defines the frustum planes to test
  100149. * @param selection defines the array to store current content if selection is positive
  100150. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100151. */
  100152. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  100153. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  100154. if (this.blocks) {
  100155. for (var index = 0; index < this.blocks.length; index++) {
  100156. var block = this.blocks[index];
  100157. block.select(frustumPlanes, selection, allowDuplicate);
  100158. }
  100159. return;
  100160. }
  100161. if (allowDuplicate) {
  100162. selection.concat(this.entries);
  100163. }
  100164. else {
  100165. selection.concatWithNoDuplicate(this.entries);
  100166. }
  100167. }
  100168. };
  100169. /**
  100170. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  100171. * @param sphereCenter defines the bounding sphere center
  100172. * @param sphereRadius defines the bounding sphere radius
  100173. * @param selection defines the array to store current content if selection is positive
  100174. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100175. */
  100176. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  100177. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  100178. if (this.blocks) {
  100179. for (var index = 0; index < this.blocks.length; index++) {
  100180. var block = this.blocks[index];
  100181. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  100182. }
  100183. return;
  100184. }
  100185. if (allowDuplicate) {
  100186. selection.concat(this.entries);
  100187. }
  100188. else {
  100189. selection.concatWithNoDuplicate(this.entries);
  100190. }
  100191. }
  100192. };
  100193. /**
  100194. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  100195. * @param ray defines the ray to test with
  100196. * @param selection defines the array to store current content if selection is positive
  100197. */
  100198. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  100199. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  100200. if (this.blocks) {
  100201. for (var index = 0; index < this.blocks.length; index++) {
  100202. var block = this.blocks[index];
  100203. block.intersectsRay(ray, selection);
  100204. }
  100205. return;
  100206. }
  100207. selection.concatWithNoDuplicate(this.entries);
  100208. }
  100209. };
  100210. /**
  100211. * Subdivide the content into child blocks (this block will then be empty)
  100212. */
  100213. OctreeBlock.prototype.createInnerBlocks = function () {
  100214. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  100215. };
  100216. return OctreeBlock;
  100217. }());
  100218. BABYLON.OctreeBlock = OctreeBlock;
  100219. })(BABYLON || (BABYLON = {}));
  100220. //# sourceMappingURL=babylon.octreeBlock.js.map
  100221. var BABYLON;
  100222. (function (BABYLON) {
  100223. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  100224. if (maxCapacity === void 0) { maxCapacity = 64; }
  100225. if (maxDepth === void 0) { maxDepth = 2; }
  100226. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  100227. if (!component) {
  100228. component = new OctreeSceneComponent(this);
  100229. this._addComponent(component);
  100230. }
  100231. if (!this._selectionOctree) {
  100232. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  100233. }
  100234. var worldExtends = this.getWorldExtends();
  100235. // Update octree
  100236. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  100237. return this._selectionOctree;
  100238. };
  100239. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  100240. get: function () {
  100241. return this._selectionOctree;
  100242. },
  100243. enumerable: true,
  100244. configurable: true
  100245. });
  100246. /**
  100247. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  100248. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  100249. * @param maxCapacity defines the maximum size of each block (64 by default)
  100250. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  100251. * @returns the new octree
  100252. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  100253. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100254. */
  100255. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  100256. if (maxCapacity === void 0) { maxCapacity = 64; }
  100257. if (maxDepth === void 0) { maxDepth = 2; }
  100258. var scene = this.getScene();
  100259. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  100260. if (!component) {
  100261. component = new OctreeSceneComponent(scene);
  100262. scene._addComponent(component);
  100263. }
  100264. if (!this._submeshesOctree) {
  100265. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  100266. }
  100267. this.computeWorldMatrix(true);
  100268. var boundingInfo = this.getBoundingInfo();
  100269. // Update octree
  100270. var bbox = boundingInfo.boundingBox;
  100271. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  100272. return this._submeshesOctree;
  100273. };
  100274. /**
  100275. * Defines the octree scene component responsible to manage any octrees
  100276. * in a given scene.
  100277. */
  100278. var OctreeSceneComponent = /** @class */ (function () {
  100279. /**
  100280. * Creates a new instance of the component for the given scene
  100281. * @param scene Defines the scene to register the component in
  100282. */
  100283. function OctreeSceneComponent(scene) {
  100284. /**
  100285. * The component name helpfull to identify the component in the list of scene components.
  100286. */
  100287. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  100288. /**
  100289. * Indicates if the meshes have been checked to make sure they are isEnabled()
  100290. */
  100291. this.checksIsEnabled = true;
  100292. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  100293. this.scene = scene;
  100294. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  100295. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  100296. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  100297. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  100298. }
  100299. /**
  100300. * Registers the component in a given scene
  100301. */
  100302. OctreeSceneComponent.prototype.register = function () {
  100303. var _this = this;
  100304. this.scene.onMeshRemovedObservable.add(function (mesh) {
  100305. var sceneOctree = _this.scene.selectionOctree;
  100306. if (sceneOctree !== undefined && sceneOctree !== null) {
  100307. var index = sceneOctree.dynamicContent.indexOf(mesh);
  100308. if (index !== -1) {
  100309. sceneOctree.dynamicContent.splice(index, 1);
  100310. }
  100311. }
  100312. });
  100313. this.scene.onMeshImportedObservable.add(function (mesh) {
  100314. var sceneOctree = _this.scene.selectionOctree;
  100315. if (sceneOctree !== undefined && sceneOctree !== null) {
  100316. sceneOctree.addMesh(mesh);
  100317. }
  100318. });
  100319. };
  100320. /**
  100321. * Return the list of active meshes
  100322. * @returns the list of active meshes
  100323. */
  100324. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  100325. if (this.scene._selectionOctree) {
  100326. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  100327. return selection;
  100328. }
  100329. return this.scene._getDefaultMeshCandidates();
  100330. };
  100331. /**
  100332. * Return the list of active sub meshes
  100333. * @param mesh The mesh to get the candidates sub meshes from
  100334. * @returns the list of active sub meshes
  100335. */
  100336. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  100337. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  100338. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  100339. return intersections;
  100340. }
  100341. return this.scene._getDefaultSubMeshCandidates(mesh);
  100342. };
  100343. /**
  100344. * Return the list of sub meshes intersecting with a given local ray
  100345. * @param mesh defines the mesh to find the submesh for
  100346. * @param localRay defines the ray in local space
  100347. * @returns the list of intersecting sub meshes
  100348. */
  100349. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  100350. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  100351. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  100352. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  100353. return intersections;
  100354. }
  100355. return this.scene._getDefaultSubMeshCandidates(mesh);
  100356. };
  100357. /**
  100358. * Return the list of sub meshes colliding with a collider
  100359. * @param mesh defines the mesh to find the submesh for
  100360. * @param collider defines the collider to evaluate the collision against
  100361. * @returns the list of colliding sub meshes
  100362. */
  100363. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  100364. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  100365. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  100366. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  100367. return intersections;
  100368. }
  100369. return this.scene._getDefaultSubMeshCandidates(mesh);
  100370. };
  100371. /**
  100372. * Rebuilds the elements related to this component in case of
  100373. * context lost for instance.
  100374. */
  100375. OctreeSceneComponent.prototype.rebuild = function () {
  100376. // Nothing to do here.
  100377. };
  100378. /**
  100379. * Disposes the component and the associated ressources.
  100380. */
  100381. OctreeSceneComponent.prototype.dispose = function () {
  100382. // Nothing to do here.
  100383. };
  100384. return OctreeSceneComponent;
  100385. }());
  100386. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  100387. })(BABYLON || (BABYLON = {}));
  100388. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  100389. var BABYLON;
  100390. (function (BABYLON) {
  100391. /**
  100392. * Postprocess used to generate anaglyphic rendering
  100393. */
  100394. var AnaglyphPostProcess = /** @class */ (function (_super) {
  100395. __extends(AnaglyphPostProcess, _super);
  100396. /**
  100397. * Creates a new AnaglyphPostProcess
  100398. * @param name defines postprocess name
  100399. * @param options defines creation options or target ratio scale
  100400. * @param rigCameras defines cameras using this postprocess
  100401. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  100402. * @param engine defines hosting engine
  100403. * @param reusable defines if the postprocess will be reused multiple times per frame
  100404. */
  100405. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  100406. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  100407. _this._passedProcess = rigCameras[0]._rigPostProcess;
  100408. _this.onApplyObservable.add(function (effect) {
  100409. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  100410. });
  100411. return _this;
  100412. }
  100413. return AnaglyphPostProcess;
  100414. }(BABYLON.PostProcess));
  100415. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  100416. })(BABYLON || (BABYLON = {}));
  100417. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  100418. var BABYLON;
  100419. (function (BABYLON) {
  100420. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  100421. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100422. });
  100423. /**
  100424. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  100425. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100426. */
  100427. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  100428. __extends(AnaglyphArcRotateCamera, _super);
  100429. /**
  100430. * Creates a new AnaglyphArcRotateCamera
  100431. * @param name defines camera name
  100432. * @param alpha defines alpha angle (in radians)
  100433. * @param beta defines beta angle (in radians)
  100434. * @param radius defines radius
  100435. * @param target defines camera target
  100436. * @param interaxialDistance defines distance between each color axis
  100437. * @param scene defines the hosting scene
  100438. */
  100439. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  100440. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100441. _this.interaxialDistance = interaxialDistance;
  100442. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100443. return _this;
  100444. }
  100445. /**
  100446. * Gets camera class name
  100447. * @returns AnaglyphArcRotateCamera
  100448. */
  100449. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  100450. return "AnaglyphArcRotateCamera";
  100451. };
  100452. return AnaglyphArcRotateCamera;
  100453. }(BABYLON.ArcRotateCamera));
  100454. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  100455. })(BABYLON || (BABYLON = {}));
  100456. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  100457. var BABYLON;
  100458. (function (BABYLON) {
  100459. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  100460. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100461. });
  100462. /**
  100463. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  100464. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100465. */
  100466. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  100467. __extends(AnaglyphFreeCamera, _super);
  100468. /**
  100469. * Creates a new AnaglyphFreeCamera
  100470. * @param name defines camera name
  100471. * @param position defines initial position
  100472. * @param interaxialDistance defines distance between each color axis
  100473. * @param scene defines the hosting scene
  100474. */
  100475. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  100476. var _this = _super.call(this, name, position, scene) || this;
  100477. _this.interaxialDistance = interaxialDistance;
  100478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100479. return _this;
  100480. }
  100481. /**
  100482. * Gets camera class name
  100483. * @returns AnaglyphFreeCamera
  100484. */
  100485. AnaglyphFreeCamera.prototype.getClassName = function () {
  100486. return "AnaglyphFreeCamera";
  100487. };
  100488. return AnaglyphFreeCamera;
  100489. }(BABYLON.FreeCamera));
  100490. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  100491. })(BABYLON || (BABYLON = {}));
  100492. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  100493. var BABYLON;
  100494. (function (BABYLON) {
  100495. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  100496. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100497. });
  100498. /**
  100499. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  100500. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100501. */
  100502. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  100503. __extends(AnaglyphGamepadCamera, _super);
  100504. /**
  100505. * Creates a new AnaglyphGamepadCamera
  100506. * @param name defines camera name
  100507. * @param position defines initial position
  100508. * @param interaxialDistance defines distance between each color axis
  100509. * @param scene defines the hosting scene
  100510. */
  100511. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  100512. var _this = _super.call(this, name, position, scene) || this;
  100513. _this.interaxialDistance = interaxialDistance;
  100514. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100515. return _this;
  100516. }
  100517. /**
  100518. * Gets camera class name
  100519. * @returns AnaglyphGamepadCamera
  100520. */
  100521. AnaglyphGamepadCamera.prototype.getClassName = function () {
  100522. return "AnaglyphGamepadCamera";
  100523. };
  100524. return AnaglyphGamepadCamera;
  100525. }(BABYLON.GamepadCamera));
  100526. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  100527. })(BABYLON || (BABYLON = {}));
  100528. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  100529. var BABYLON;
  100530. (function (BABYLON) {
  100531. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  100532. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  100533. });
  100534. /**
  100535. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  100536. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  100537. */
  100538. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  100539. __extends(AnaglyphUniversalCamera, _super);
  100540. /**
  100541. * Creates a new AnaglyphUniversalCamera
  100542. * @param name defines camera name
  100543. * @param position defines initial position
  100544. * @param interaxialDistance defines distance between each color axis
  100545. * @param scene defines the hosting scene
  100546. */
  100547. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  100548. var _this = _super.call(this, name, position, scene) || this;
  100549. _this.interaxialDistance = interaxialDistance;
  100550. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  100551. return _this;
  100552. }
  100553. /**
  100554. * Gets camera class name
  100555. * @returns AnaglyphUniversalCamera
  100556. */
  100557. AnaglyphUniversalCamera.prototype.getClassName = function () {
  100558. return "AnaglyphUniversalCamera";
  100559. };
  100560. return AnaglyphUniversalCamera;
  100561. }(BABYLON.UniversalCamera));
  100562. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  100563. })(BABYLON || (BABYLON = {}));
  100564. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  100565. var BABYLON;
  100566. (function (BABYLON) {
  100567. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  100568. __extends(StereoscopicInterlacePostProcess, _super);
  100569. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  100570. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  100571. _this._passedProcess = rigCameras[0]._rigPostProcess;
  100572. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  100573. _this.onSizeChangedObservable.add(function () {
  100574. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  100575. });
  100576. _this.onApplyObservable.add(function (effect) {
  100577. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  100578. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  100579. });
  100580. return _this;
  100581. }
  100582. return StereoscopicInterlacePostProcess;
  100583. }(BABYLON.PostProcess));
  100584. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  100585. })(BABYLON || (BABYLON = {}));
  100586. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  100587. var BABYLON;
  100588. (function (BABYLON) {
  100589. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  100590. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100591. });
  100592. /**
  100593. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  100594. * @see http://doc.babylonjs.com/features/cameras
  100595. */
  100596. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  100597. __extends(StereoscopicArcRotateCamera, _super);
  100598. /**
  100599. * Creates a new StereoscopicArcRotateCamera
  100600. * @param name defines camera name
  100601. * @param alpha defines alpha angle (in radians)
  100602. * @param beta defines beta angle (in radians)
  100603. * @param radius defines radius
  100604. * @param target defines camera target
  100605. * @param interaxialDistance defines distance between each color axis
  100606. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100607. * @param scene defines the hosting scene
  100608. */
  100609. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  100610. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100611. _this.interaxialDistance = interaxialDistance;
  100612. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100613. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100614. return _this;
  100615. }
  100616. /**
  100617. * Gets camera class name
  100618. * @returns StereoscopicArcRotateCamera
  100619. */
  100620. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  100621. return "StereoscopicArcRotateCamera";
  100622. };
  100623. return StereoscopicArcRotateCamera;
  100624. }(BABYLON.ArcRotateCamera));
  100625. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  100626. })(BABYLON || (BABYLON = {}));
  100627. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  100628. var BABYLON;
  100629. (function (BABYLON) {
  100630. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  100631. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100632. });
  100633. /**
  100634. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  100635. * @see http://doc.babylonjs.com/features/cameras
  100636. */
  100637. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  100638. __extends(StereoscopicFreeCamera, _super);
  100639. /**
  100640. * Creates a new StereoscopicFreeCamera
  100641. * @param name defines camera name
  100642. * @param position defines initial position
  100643. * @param interaxialDistance defines distance between each color axis
  100644. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100645. * @param scene defines the hosting scene
  100646. */
  100647. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100648. var _this = _super.call(this, name, position, scene) || this;
  100649. _this.interaxialDistance = interaxialDistance;
  100650. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100651. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100652. return _this;
  100653. }
  100654. /**
  100655. * Gets camera class name
  100656. * @returns StereoscopicFreeCamera
  100657. */
  100658. StereoscopicFreeCamera.prototype.getClassName = function () {
  100659. return "StereoscopicFreeCamera";
  100660. };
  100661. return StereoscopicFreeCamera;
  100662. }(BABYLON.FreeCamera));
  100663. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  100664. })(BABYLON || (BABYLON = {}));
  100665. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  100666. var BABYLON;
  100667. (function (BABYLON) {
  100668. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  100669. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100670. });
  100671. /**
  100672. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  100673. * @see http://doc.babylonjs.com/features/cameras
  100674. */
  100675. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  100676. __extends(StereoscopicGamepadCamera, _super);
  100677. /**
  100678. * Creates a new StereoscopicGamepadCamera
  100679. * @param name defines camera name
  100680. * @param position defines initial position
  100681. * @param interaxialDistance defines distance between each color axis
  100682. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100683. * @param scene defines the hosting scene
  100684. */
  100685. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100686. var _this = _super.call(this, name, position, scene) || this;
  100687. _this.interaxialDistance = interaxialDistance;
  100688. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100689. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100690. return _this;
  100691. }
  100692. /**
  100693. * Gets camera class name
  100694. * @returns StereoscopicGamepadCamera
  100695. */
  100696. StereoscopicGamepadCamera.prototype.getClassName = function () {
  100697. return "StereoscopicGamepadCamera";
  100698. };
  100699. return StereoscopicGamepadCamera;
  100700. }(BABYLON.GamepadCamera));
  100701. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  100702. })(BABYLON || (BABYLON = {}));
  100703. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  100704. var BABYLON;
  100705. (function (BABYLON) {
  100706. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  100707. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  100708. });
  100709. /**
  100710. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  100711. * @see http://doc.babylonjs.com/features/cameras
  100712. */
  100713. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  100714. __extends(StereoscopicUniversalCamera, _super);
  100715. /**
  100716. * Creates a new StereoscopicUniversalCamera
  100717. * @param name defines camera name
  100718. * @param position defines initial position
  100719. * @param interaxialDistance defines distance between each color axis
  100720. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  100721. * @param scene defines the hosting scene
  100722. */
  100723. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  100724. var _this = _super.call(this, name, position, scene) || this;
  100725. _this.interaxialDistance = interaxialDistance;
  100726. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  100727. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  100728. return _this;
  100729. }
  100730. /**
  100731. * Gets camera class name
  100732. * @returns StereoscopicUniversalCamera
  100733. */
  100734. StereoscopicUniversalCamera.prototype.getClassName = function () {
  100735. return "StereoscopicUniversalCamera";
  100736. };
  100737. return StereoscopicUniversalCamera;
  100738. }(BABYLON.UniversalCamera));
  100739. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  100740. })(BABYLON || (BABYLON = {}));
  100741. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  100742. var BABYLON;
  100743. (function (BABYLON) {
  100744. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  100745. __extends(VRDistortionCorrectionPostProcess, _super);
  100746. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  100747. var _this = _super.call(this, name, "vrDistortionCorrection", [
  100748. 'LensCenter',
  100749. 'Scale',
  100750. 'ScaleIn',
  100751. 'HmdWarpParam'
  100752. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  100753. _this._isRightEye = isRightEye;
  100754. _this._distortionFactors = vrMetrics.distortionK;
  100755. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  100756. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  100757. _this.adaptScaleToCurrentViewport = true;
  100758. _this.onSizeChangedObservable.add(function () {
  100759. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  100760. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  100761. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  100762. });
  100763. _this.onApplyObservable.add(function (effect) {
  100764. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  100765. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  100766. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  100767. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  100768. });
  100769. return _this;
  100770. }
  100771. return VRDistortionCorrectionPostProcess;
  100772. }(BABYLON.PostProcess));
  100773. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  100774. })(BABYLON || (BABYLON = {}));
  100775. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  100776. var BABYLON;
  100777. (function (BABYLON) {
  100778. /**
  100779. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  100780. * Screen rotation is taken into account.
  100781. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100782. */
  100783. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  100784. /**
  100785. * Instantiates a new input
  100786. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100787. */
  100788. function FreeCameraDeviceOrientationInput() {
  100789. var _this = this;
  100790. this._screenOrientationAngle = 0;
  100791. this._screenQuaternion = new BABYLON.Quaternion();
  100792. this._alpha = 0;
  100793. this._beta = 0;
  100794. this._gamma = 0;
  100795. this._orientationChanged = function () {
  100796. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  100797. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  100798. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  100799. };
  100800. this._deviceOrientation = function (evt) {
  100801. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  100802. _this._beta = evt.beta !== null ? evt.beta : 0;
  100803. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  100804. };
  100805. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  100806. this._orientationChanged();
  100807. }
  100808. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  100809. /**
  100810. * Define the camera controlled by the input.
  100811. */
  100812. get: function () {
  100813. return this._camera;
  100814. },
  100815. set: function (camera) {
  100816. this._camera = camera;
  100817. if (this._camera != null && !this._camera.rotationQuaternion) {
  100818. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  100819. }
  100820. },
  100821. enumerable: true,
  100822. configurable: true
  100823. });
  100824. /**
  100825. * Attach the input controls to a specific dom element to get the input from.
  100826. * @param element Defines the element the controls should be listened from
  100827. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100828. */
  100829. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100830. window.addEventListener("orientationchange", this._orientationChanged);
  100831. window.addEventListener("deviceorientation", this._deviceOrientation);
  100832. //In certain cases, the attach control is called AFTER orientation was changed,
  100833. //So this is needed.
  100834. this._orientationChanged();
  100835. };
  100836. /**
  100837. * Detach the current controls from the specified dom element.
  100838. * @param element Defines the element to stop listening the inputs from
  100839. */
  100840. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  100841. window.removeEventListener("orientationchange", this._orientationChanged);
  100842. window.removeEventListener("deviceorientation", this._deviceOrientation);
  100843. };
  100844. /**
  100845. * Update the current camera state depending on the inputs that have been used this frame.
  100846. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100847. */
  100848. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  100849. //if no device orientation provided, don't update the rotation.
  100850. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  100851. if (!this._alpha)
  100852. return;
  100853. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  100854. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  100855. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  100856. //Mirror on XY Plane
  100857. this._camera.rotationQuaternion.z *= -1;
  100858. this._camera.rotationQuaternion.w *= -1;
  100859. };
  100860. /**
  100861. * Gets the class name of the current intput.
  100862. * @returns the class name
  100863. */
  100864. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  100865. return "FreeCameraDeviceOrientationInput";
  100866. };
  100867. /**
  100868. * Get the friendly name associated with the input class.
  100869. * @returns the input friendly name
  100870. */
  100871. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  100872. return "deviceOrientation";
  100873. };
  100874. return FreeCameraDeviceOrientationInput;
  100875. }());
  100876. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  100877. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  100878. })(BABYLON || (BABYLON = {}));
  100879. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  100880. var BABYLON;
  100881. (function (BABYLON) {
  100882. /**
  100883. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  100884. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100885. */
  100886. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  100887. /**
  100888. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  100889. */
  100890. function ArcRotateCameraVRDeviceOrientationInput() {
  100891. /**
  100892. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  100893. */
  100894. this.alphaCorrection = 1;
  100895. /**
  100896. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  100897. */
  100898. this.betaCorrection = 1;
  100899. /**
  100900. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  100901. */
  100902. this.gammaCorrection = 1;
  100903. this._alpha = 0;
  100904. this._gamma = 0;
  100905. this._dirty = false;
  100906. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  100907. }
  100908. /**
  100909. * Attach the input controls to a specific dom element to get the input from.
  100910. * @param element Defines the element the controls should be listened from
  100911. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100912. */
  100913. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100914. this.camera.attachControl(element, noPreventDefault);
  100915. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  100916. };
  100917. /** @hidden */
  100918. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  100919. if (evt.alpha !== null) {
  100920. this._alpha = +evt.alpha | 0;
  100921. }
  100922. if (evt.gamma !== null) {
  100923. this._gamma = +evt.gamma | 0;
  100924. }
  100925. this._dirty = true;
  100926. };
  100927. /**
  100928. * Update the current camera state depending on the inputs that have been used this frame.
  100929. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100930. */
  100931. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  100932. if (this._dirty) {
  100933. this._dirty = false;
  100934. if (this._gamma < 0) {
  100935. this._gamma = 180 + this._gamma;
  100936. }
  100937. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  100938. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  100939. }
  100940. };
  100941. /**
  100942. * Detach the current controls from the specified dom element.
  100943. * @param element Defines the element to stop listening the inputs from
  100944. */
  100945. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  100946. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  100947. };
  100948. /**
  100949. * Gets the class name of the current intput.
  100950. * @returns the class name
  100951. */
  100952. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  100953. return "ArcRotateCameraVRDeviceOrientationInput";
  100954. };
  100955. /**
  100956. * Get the friendly name associated with the input class.
  100957. * @returns the input friendly name
  100958. */
  100959. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  100960. return "VRDeviceOrientation";
  100961. };
  100962. return ArcRotateCameraVRDeviceOrientationInput;
  100963. }());
  100964. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  100965. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  100966. })(BABYLON || (BABYLON = {}));
  100967. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  100968. var BABYLON;
  100969. (function (BABYLON) {
  100970. /**
  100971. * This represents all the required metrics to create a VR camera.
  100972. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  100973. */
  100974. var VRCameraMetrics = /** @class */ (function () {
  100975. function VRCameraMetrics() {
  100976. /**
  100977. * Define if the current vr camera should compensate the distortion of the lense or not.
  100978. */
  100979. this.compensateDistortion = true;
  100980. }
  100981. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  100982. /**
  100983. * Gets the rendering aspect ratio based on the provided resolutions.
  100984. */
  100985. get: function () {
  100986. return this.hResolution / (2 * this.vResolution);
  100987. },
  100988. enumerable: true,
  100989. configurable: true
  100990. });
  100991. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  100992. /**
  100993. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  100994. */
  100995. get: function () {
  100996. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  100997. },
  100998. enumerable: true,
  100999. configurable: true
  101000. });
  101001. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  101002. /**
  101003. * @hidden
  101004. */
  101005. get: function () {
  101006. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101007. var h = (4 * meters) / this.hScreenSize;
  101008. return BABYLON.Matrix.Translation(h, 0, 0);
  101009. },
  101010. enumerable: true,
  101011. configurable: true
  101012. });
  101013. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  101014. /**
  101015. * @hidden
  101016. */
  101017. get: function () {
  101018. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101019. var h = (4 * meters) / this.hScreenSize;
  101020. return BABYLON.Matrix.Translation(-h, 0, 0);
  101021. },
  101022. enumerable: true,
  101023. configurable: true
  101024. });
  101025. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  101026. /**
  101027. * @hidden
  101028. */
  101029. get: function () {
  101030. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101031. },
  101032. enumerable: true,
  101033. configurable: true
  101034. });
  101035. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101036. /**
  101037. * @hidden
  101038. */
  101039. get: function () {
  101040. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101041. },
  101042. enumerable: true,
  101043. configurable: true
  101044. });
  101045. /**
  101046. * Get the default VRMetrics based on the most generic setup.
  101047. * @returns the default vr metrics
  101048. */
  101049. VRCameraMetrics.GetDefault = function () {
  101050. var result = new VRCameraMetrics();
  101051. result.hResolution = 1280;
  101052. result.vResolution = 800;
  101053. result.hScreenSize = 0.149759993;
  101054. result.vScreenSize = 0.0935999975;
  101055. result.vScreenCenter = 0.0467999987;
  101056. result.eyeToScreenDistance = 0.0410000011;
  101057. result.lensSeparationDistance = 0.0635000020;
  101058. result.interpupillaryDistance = 0.0640000030;
  101059. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101060. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101061. result.postProcessScaleFactor = 1.714605507808412;
  101062. result.lensCenterOffset = 0.151976421;
  101063. return result;
  101064. };
  101065. return VRCameraMetrics;
  101066. }());
  101067. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101068. })(BABYLON || (BABYLON = {}));
  101069. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101070. var BABYLON;
  101071. (function (BABYLON) {
  101072. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101073. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101074. });
  101075. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101076. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101077. });
  101078. /**
  101079. * This represents a WebVR camera.
  101080. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101081. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101082. */
  101083. var WebVRFreeCamera = /** @class */ (function (_super) {
  101084. __extends(WebVRFreeCamera, _super);
  101085. /**
  101086. * Instantiates a WebVRFreeCamera.
  101087. * @param name The name of the WebVRFreeCamera
  101088. * @param position The starting anchor position for the camera
  101089. * @param scene The scene the camera belongs to
  101090. * @param webVROptions a set of customizable options for the webVRCamera
  101091. */
  101092. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101093. if (webVROptions === void 0) { webVROptions = {}; }
  101094. var _this = _super.call(this, name, position, scene) || this;
  101095. _this.webVROptions = webVROptions;
  101096. /**
  101097. * @hidden
  101098. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  101099. */
  101100. _this._vrDevice = null;
  101101. /**
  101102. * The rawPose of the vrDevice.
  101103. */
  101104. _this.rawPose = null;
  101105. _this._specsVersion = "1.1";
  101106. _this._attached = false;
  101107. _this._descendants = [];
  101108. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  101109. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  101110. /** @hidden */
  101111. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  101112. _this._standingMatrix = null;
  101113. /**
  101114. * Represents device position in babylon space.
  101115. */
  101116. _this.devicePosition = BABYLON.Vector3.Zero();
  101117. /**
  101118. * Represents device rotation in babylon space.
  101119. */
  101120. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  101121. /**
  101122. * The scale of the device to be used when translating from device space to babylon space.
  101123. */
  101124. _this.deviceScaleFactor = 1;
  101125. _this._deviceToWorld = BABYLON.Matrix.Identity();
  101126. _this._worldToDevice = BABYLON.Matrix.Identity();
  101127. /**
  101128. * References to the webVR controllers for the vrDevice.
  101129. */
  101130. _this.controllers = [];
  101131. /**
  101132. * Emits an event when a controller is attached.
  101133. */
  101134. _this.onControllersAttachedObservable = new BABYLON.Observable();
  101135. /**
  101136. * Emits an event when a controller's mesh has been loaded;
  101137. */
  101138. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101139. /**
  101140. * Emits an event when the HMD's pose has been updated.
  101141. */
  101142. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  101143. _this._poseSet = false;
  101144. /**
  101145. * If the rig cameras be used as parent instead of this camera.
  101146. */
  101147. _this.rigParenting = true;
  101148. _this._defaultHeight = undefined;
  101149. _this._htmlElementAttached = null;
  101150. _this._detachIfAttached = function () {
  101151. var vrDisplay = _this.getEngine().getVRDevice();
  101152. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  101153. _this.detachControl(_this._htmlElementAttached);
  101154. }
  101155. };
  101156. _this._workingVector = BABYLON.Vector3.Zero();
  101157. _this._oneVector = BABYLON.Vector3.One();
  101158. _this._workingMatrix = BABYLON.Matrix.Identity();
  101159. _this._tmpMatrix = new BABYLON.Matrix();
  101160. _this._cache.position = BABYLON.Vector3.Zero();
  101161. if (webVROptions.defaultHeight) {
  101162. _this._defaultHeight = webVROptions.defaultHeight;
  101163. _this.position.y = _this._defaultHeight;
  101164. }
  101165. _this.minZ = 0.1;
  101166. //legacy support - the compensation boolean was removed.
  101167. if (arguments.length === 5) {
  101168. _this.webVROptions = arguments[4];
  101169. }
  101170. // default webVR options
  101171. if (_this.webVROptions.trackPosition == undefined) {
  101172. _this.webVROptions.trackPosition = true;
  101173. }
  101174. if (_this.webVROptions.controllerMeshes == undefined) {
  101175. _this.webVROptions.controllerMeshes = true;
  101176. }
  101177. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  101178. _this.webVROptions.defaultLightingOnControllers = true;
  101179. }
  101180. _this.rotationQuaternion = new BABYLON.Quaternion();
  101181. if (_this.webVROptions && _this.webVROptions.positionScale) {
  101182. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  101183. }
  101184. //enable VR
  101185. var engine = _this.getEngine();
  101186. _this._onVREnabled = function (success) { if (success) {
  101187. _this.initControllers();
  101188. } };
  101189. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  101190. engine.initWebVR().add(function (event) {
  101191. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  101192. return;
  101193. }
  101194. _this._vrDevice = event.vrDisplay;
  101195. //reset the rig parameters.
  101196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  101197. if (_this._attached) {
  101198. _this.getEngine().enableVR();
  101199. }
  101200. });
  101201. if (typeof (VRFrameData) !== "undefined")
  101202. _this._frameData = new VRFrameData();
  101203. /**
  101204. * The idea behind the following lines:
  101205. * objects that have the camera as parent should actually have the rig cameras as a parent.
  101206. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  101207. * the second will not show it correctly.
  101208. *
  101209. * To solve this - each object that has the camera as parent will be added to a protected array.
  101210. * When the rig camera renders, it will take this array and set all of those to be its children.
  101211. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  101212. * Amazing!
  101213. */
  101214. scene.onBeforeCameraRenderObservable.add(function (camera) {
  101215. if (camera.parent === _this && _this.rigParenting) {
  101216. _this._descendants = _this.getDescendants(true, function (n) {
  101217. // don't take the cameras or the controllers!
  101218. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  101219. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  101220. return !isController && !isRigCamera;
  101221. });
  101222. _this._descendants.forEach(function (node) {
  101223. node.parent = camera;
  101224. });
  101225. }
  101226. });
  101227. scene.onAfterCameraRenderObservable.add(function (camera) {
  101228. if (camera.parent === _this && _this.rigParenting) {
  101229. _this._descendants.forEach(function (node) {
  101230. node.parent = _this;
  101231. });
  101232. }
  101233. });
  101234. return _this;
  101235. }
  101236. /**
  101237. * Gets the device distance from the ground in meters.
  101238. * @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.
  101239. */
  101240. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  101241. if (this._standingMatrix) {
  101242. // Add standing matrix offset to get real offset from ground in room
  101243. this._standingMatrix.getTranslationToRef(this._workingVector);
  101244. return this._deviceRoomPosition.y + this._workingVector.y;
  101245. }
  101246. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  101247. return this._defaultHeight || 0;
  101248. };
  101249. /**
  101250. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  101251. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  101252. */
  101253. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  101254. var _this = this;
  101255. if (callback === void 0) { callback = function (bool) { }; }
  101256. // Use standing matrix if available
  101257. this.getEngine().initWebVRAsync().then(function (result) {
  101258. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  101259. callback(false);
  101260. }
  101261. else {
  101262. _this._standingMatrix = new BABYLON.Matrix();
  101263. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  101264. if (!_this.getScene().useRightHandedSystem) {
  101265. [2, 6, 8, 9, 14].forEach(function (num) {
  101266. if (_this._standingMatrix) {
  101267. _this._standingMatrix.m[num] *= -1;
  101268. }
  101269. });
  101270. }
  101271. callback(true);
  101272. }
  101273. });
  101274. };
  101275. /**
  101276. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  101277. * @returns A promise with a boolean set to if the standing matrix is supported.
  101278. */
  101279. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  101280. var _this = this;
  101281. return new Promise(function (res, rej) {
  101282. _this.useStandingMatrix(function (supported) {
  101283. res(supported);
  101284. });
  101285. });
  101286. };
  101287. /**
  101288. * Disposes the camera
  101289. */
  101290. WebVRFreeCamera.prototype.dispose = function () {
  101291. this._detachIfAttached();
  101292. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  101293. if (this._updateCacheWhenTrackingDisabledObserver) {
  101294. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  101295. }
  101296. _super.prototype.dispose.call(this);
  101297. };
  101298. /**
  101299. * Gets a vrController by name.
  101300. * @param name The name of the controller to retreive
  101301. * @returns the controller matching the name specified or null if not found
  101302. */
  101303. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  101304. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  101305. var gp = _a[_i];
  101306. if (gp.hand === name) {
  101307. return gp;
  101308. }
  101309. }
  101310. return null;
  101311. };
  101312. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  101313. /**
  101314. * The controller corrisponding to the users left hand.
  101315. */
  101316. get: function () {
  101317. if (!this._leftController) {
  101318. this._leftController = this.getControllerByName("left");
  101319. }
  101320. return this._leftController;
  101321. },
  101322. enumerable: true,
  101323. configurable: true
  101324. });
  101325. ;
  101326. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  101327. /**
  101328. * The controller corrisponding to the users right hand.
  101329. */
  101330. get: function () {
  101331. if (!this._rightController) {
  101332. this._rightController = this.getControllerByName("right");
  101333. }
  101334. return this._rightController;
  101335. },
  101336. enumerable: true,
  101337. configurable: true
  101338. });
  101339. ;
  101340. /**
  101341. * Casts a ray forward from the vrCamera's gaze.
  101342. * @param length Length of the ray (default: 100)
  101343. * @returns the ray corrisponding to the gaze
  101344. */
  101345. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  101346. if (length === void 0) { length = 100; }
  101347. if (this.leftCamera) {
  101348. // Use left eye to avoid computation to compute center on every call
  101349. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  101350. }
  101351. else {
  101352. return _super.prototype.getForwardRay.call(this, length);
  101353. }
  101354. };
  101355. /**
  101356. * @hidden
  101357. * Updates the camera based on device's frame data
  101358. */
  101359. WebVRFreeCamera.prototype._checkInputs = function () {
  101360. if (this._vrDevice && this._vrDevice.isPresenting) {
  101361. this._vrDevice.getFrameData(this._frameData);
  101362. this.updateFromDevice(this._frameData.pose);
  101363. }
  101364. _super.prototype._checkInputs.call(this);
  101365. };
  101366. /**
  101367. * Updates the poseControlled values based on the input device pose.
  101368. * @param poseData Pose coming from the device
  101369. */
  101370. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  101371. if (poseData && poseData.orientation) {
  101372. this.rawPose = poseData;
  101373. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  101374. if (this.getScene().useRightHandedSystem) {
  101375. this._deviceRoomRotationQuaternion.z *= -1;
  101376. this._deviceRoomRotationQuaternion.w *= -1;
  101377. }
  101378. if (this.webVROptions.trackPosition && this.rawPose.position) {
  101379. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  101380. if (this.getScene().useRightHandedSystem) {
  101381. this._deviceRoomPosition.z *= -1;
  101382. }
  101383. }
  101384. this._poseSet = true;
  101385. }
  101386. };
  101387. /**
  101388. * WebVR's attach control will start broadcasting frames to the device.
  101389. * Note that in certain browsers (chrome for example) this function must be called
  101390. * within a user-interaction callback. Example:
  101391. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  101392. *
  101393. * @param element html element to attach the vrDevice to
  101394. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  101395. */
  101396. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  101397. _super.prototype.attachControl.call(this, element, noPreventDefault);
  101398. this._attached = true;
  101399. this._htmlElementAttached = element;
  101400. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  101401. if (this._vrDevice) {
  101402. this.getEngine().enableVR();
  101403. }
  101404. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  101405. };
  101406. /**
  101407. * Detaches the camera from the html element and disables VR
  101408. *
  101409. * @param element html element to detach from
  101410. */
  101411. WebVRFreeCamera.prototype.detachControl = function (element) {
  101412. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  101413. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  101414. _super.prototype.detachControl.call(this, element);
  101415. this._attached = false;
  101416. this.getEngine().disableVR();
  101417. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  101418. };
  101419. /**
  101420. * @returns the name of this class
  101421. */
  101422. WebVRFreeCamera.prototype.getClassName = function () {
  101423. return "WebVRFreeCamera";
  101424. };
  101425. /**
  101426. * Calls resetPose on the vrDisplay
  101427. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  101428. */
  101429. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  101430. //uses the vrDisplay's "resetPose()".
  101431. //pitch and roll won't be affected.
  101432. this._vrDevice.resetPose();
  101433. };
  101434. /**
  101435. * @hidden
  101436. * Updates the rig cameras (left and right eye)
  101437. */
  101438. WebVRFreeCamera.prototype._updateRigCameras = function () {
  101439. var camLeft = this._rigCameras[0];
  101440. var camRight = this._rigCameras[1];
  101441. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  101442. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  101443. camLeft.position.copyFrom(this._deviceRoomPosition);
  101444. camRight.position.copyFrom(this._deviceRoomPosition);
  101445. };
  101446. // Remove translation from 6dof headset if trackposition is set to false
  101447. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  101448. if (isViewMatrix === void 0) { isViewMatrix = false; }
  101449. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  101450. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  101451. if (!isViewMatrix) {
  101452. this._tmpMatrix.invert();
  101453. }
  101454. this._tmpMatrix.multiplyToRef(matrix, matrix);
  101455. }
  101456. };
  101457. /**
  101458. * @hidden
  101459. * Updates the cached values of the camera
  101460. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  101461. */
  101462. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  101463. var _this = this;
  101464. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  101465. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  101466. if (!this.updateCacheCalled) {
  101467. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  101468. this.updateCacheCalled = true;
  101469. this.update();
  101470. }
  101471. // Set working vector to the device position in room space rotated by the new rotation
  101472. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  101473. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  101474. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  101475. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  101476. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  101477. // Add translation from anchor position
  101478. this._deviceToWorld.getTranslationToRef(this._workingVector);
  101479. this._workingVector.addInPlace(this.position);
  101480. this._workingVector.subtractInPlace(this._cache.position);
  101481. this._deviceToWorld.setTranslation(this._workingVector);
  101482. // Set an inverted matrix to be used when updating the camera
  101483. this._deviceToWorld.invertToRef(this._worldToDevice);
  101484. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  101485. this.controllers.forEach(function (controller) {
  101486. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  101487. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  101488. controller.update();
  101489. });
  101490. }
  101491. if (!ignoreParentClass) {
  101492. _super.prototype._updateCache.call(this);
  101493. }
  101494. this.updateCacheCalled = false;
  101495. };
  101496. /**
  101497. * @hidden
  101498. * Get current device position in babylon world
  101499. */
  101500. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  101501. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  101502. };
  101503. /**
  101504. * Updates the current device position and rotation in the babylon world
  101505. */
  101506. WebVRFreeCamera.prototype.update = function () {
  101507. this._computeDevicePosition();
  101508. // Get current device rotation in babylon world
  101509. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  101510. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  101511. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  101512. if (this._poseSet) {
  101513. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  101514. }
  101515. _super.prototype.update.call(this);
  101516. };
  101517. /**
  101518. * @hidden
  101519. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  101520. * @returns an identity matrix
  101521. */
  101522. WebVRFreeCamera.prototype._getViewMatrix = function () {
  101523. return BABYLON.Matrix.Identity();
  101524. };
  101525. /**
  101526. * This function is called by the two RIG cameras.
  101527. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  101528. */
  101529. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  101530. var _this = this;
  101531. // Update the parent camera prior to using a child camera to avoid desynchronization
  101532. var parentCamera = this._cameraRigParams["parentCamera"];
  101533. parentCamera._updateCache();
  101534. //WebVR 1.1
  101535. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  101536. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  101537. if (!this.getScene().useRightHandedSystem) {
  101538. [2, 6, 8, 9, 14].forEach(function (num) {
  101539. _this._webvrViewMatrix.m[num] *= -1;
  101540. });
  101541. }
  101542. // update the camera rotation matrix
  101543. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  101544. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  101545. // Computing target and final matrix
  101546. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  101547. // should the view matrix be updated with scale and position offset?
  101548. if (parentCamera.deviceScaleFactor !== 1) {
  101549. this._webvrViewMatrix.invert();
  101550. // scale the position, if set
  101551. if (parentCamera.deviceScaleFactor) {
  101552. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  101553. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  101554. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  101555. }
  101556. this._webvrViewMatrix.invert();
  101557. }
  101558. // Remove translation from 6dof headset if trackposition is set to false
  101559. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  101560. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  101561. // Compute global position
  101562. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  101563. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  101564. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  101565. this._workingMatrix.getTranslationToRef(this._globalPosition);
  101566. this._markSyncedWithParent();
  101567. return this._webvrViewMatrix;
  101568. };
  101569. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  101570. var _this = this;
  101571. var parentCamera = this.parent;
  101572. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  101573. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  101574. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  101575. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  101576. //babylon compatible matrix
  101577. if (!this.getScene().useRightHandedSystem) {
  101578. [8, 9, 10, 11].forEach(function (num) {
  101579. _this._projectionMatrix.m[num] *= -1;
  101580. });
  101581. }
  101582. return this._projectionMatrix;
  101583. };
  101584. /**
  101585. * Initializes the controllers and their meshes
  101586. */
  101587. WebVRFreeCamera.prototype.initControllers = function () {
  101588. var _this = this;
  101589. this.controllers = [];
  101590. var manager = this.getScene().gamepadManager;
  101591. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  101592. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  101593. var webVrController = gamepad;
  101594. if (webVrController.defaultModel) {
  101595. webVrController.defaultModel.setEnabled(false);
  101596. }
  101597. if (webVrController.hand === "right") {
  101598. _this._rightController = null;
  101599. }
  101600. if (webVrController.hand === "left") {
  101601. _this._leftController = null;
  101602. }
  101603. var controllerIndex = _this.controllers.indexOf(webVrController);
  101604. if (controllerIndex !== -1) {
  101605. _this.controllers.splice(controllerIndex, 1);
  101606. }
  101607. }
  101608. });
  101609. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  101610. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  101611. var webVrController_1 = gamepad;
  101612. if (!_this.webVROptions.trackPosition) {
  101613. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  101614. // Cache must be updated before rendering controllers to avoid them being one frame behind
  101615. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  101616. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  101617. _this._updateCache();
  101618. });
  101619. }
  101620. }
  101621. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  101622. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  101623. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  101624. if (_this.webVROptions.controllerMeshes) {
  101625. if (webVrController_1.defaultModel) {
  101626. webVrController_1.defaultModel.setEnabled(true);
  101627. }
  101628. else {
  101629. // Load the meshes
  101630. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  101631. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  101632. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  101633. if (_this.webVROptions.defaultLightingOnControllers) {
  101634. if (!_this._lightOnControllers) {
  101635. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  101636. }
  101637. var activateLightOnSubMeshes_1 = function (mesh, light) {
  101638. var children = mesh.getChildren();
  101639. if (children && children.length !== 0) {
  101640. children.forEach(function (mesh) {
  101641. light.includedOnlyMeshes.push(mesh);
  101642. activateLightOnSubMeshes_1(mesh, light);
  101643. });
  101644. }
  101645. };
  101646. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  101647. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  101648. }
  101649. });
  101650. }
  101651. }
  101652. webVrController_1.attachToPoseControlledCamera(_this);
  101653. // since this is async - sanity check. Is the controller already stored?
  101654. if (_this.controllers.indexOf(webVrController_1) === -1) {
  101655. //add to the controllers array
  101656. _this.controllers.push(webVrController_1);
  101657. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  101658. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  101659. // So we're overriding setting left & right manually to be sure
  101660. var firstViveWandDetected = false;
  101661. for (var i = 0; i < _this.controllers.length; i++) {
  101662. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101663. if (!firstViveWandDetected) {
  101664. firstViveWandDetected = true;
  101665. _this.controllers[i].hand = "left";
  101666. }
  101667. else {
  101668. _this.controllers[i].hand = "right";
  101669. }
  101670. }
  101671. }
  101672. //did we find enough controllers? Great! let the developer know.
  101673. if (_this.controllers.length >= 2) {
  101674. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  101675. }
  101676. }
  101677. }
  101678. });
  101679. };
  101680. return WebVRFreeCamera;
  101681. }(BABYLON.FreeCamera));
  101682. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  101683. })(BABYLON || (BABYLON = {}));
  101684. //# sourceMappingURL=babylon.webVRCamera.js.map
  101685. var BABYLON;
  101686. (function (BABYLON) {
  101687. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  101688. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  101689. });
  101690. // We're mainly based on the logic defined into the FreeCamera code
  101691. /**
  101692. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  101693. * being tilted forward or back and left or right.
  101694. */
  101695. var DeviceOrientationCamera = /** @class */ (function (_super) {
  101696. __extends(DeviceOrientationCamera, _super);
  101697. /**
  101698. * Creates a new device orientation camera
  101699. * @param name The name of the camera
  101700. * @param position The start position camera
  101701. * @param scene The scene the camera belongs to
  101702. */
  101703. function DeviceOrientationCamera(name, position, scene) {
  101704. var _this = _super.call(this, name, position, scene) || this;
  101705. _this._quaternionCache = new BABYLON.Quaternion();
  101706. _this.inputs.addDeviceOrientation();
  101707. return _this;
  101708. }
  101709. /**
  101710. * Gets the current instance class name ("DeviceOrientationCamera").
  101711. * This helps avoiding instanceof at run time.
  101712. * @returns the class name
  101713. */
  101714. DeviceOrientationCamera.prototype.getClassName = function () {
  101715. return "DeviceOrientationCamera";
  101716. };
  101717. /**
  101718. * @hidden
  101719. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  101720. */
  101721. DeviceOrientationCamera.prototype._checkInputs = function () {
  101722. _super.prototype._checkInputs.call(this);
  101723. this._quaternionCache.copyFrom(this.rotationQuaternion);
  101724. if (this._initialQuaternion) {
  101725. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  101726. }
  101727. };
  101728. /**
  101729. * Reset the camera to its default orientation on the specified axis only.
  101730. * @param axis The axis to reset
  101731. */
  101732. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  101733. var _this = this;
  101734. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  101735. //can only work if this camera has a rotation quaternion already.
  101736. if (!this.rotationQuaternion)
  101737. return;
  101738. if (!this._initialQuaternion) {
  101739. this._initialQuaternion = new BABYLON.Quaternion();
  101740. }
  101741. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  101742. ['x', 'y', 'z'].forEach(function (axisName) {
  101743. if (!axis[axisName]) {
  101744. _this._initialQuaternion[axisName] = 0;
  101745. }
  101746. else {
  101747. _this._initialQuaternion[axisName] *= -1;
  101748. }
  101749. });
  101750. this._initialQuaternion.normalize();
  101751. //force rotation update
  101752. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  101753. };
  101754. return DeviceOrientationCamera;
  101755. }(BABYLON.FreeCamera));
  101756. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  101757. })(BABYLON || (BABYLON = {}));
  101758. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  101759. var BABYLON;
  101760. (function (BABYLON) {
  101761. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  101762. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101763. });
  101764. /**
  101765. * Camera used to simulate VR rendering (based on FreeCamera)
  101766. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101767. */
  101768. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  101769. __extends(VRDeviceOrientationFreeCamera, _super);
  101770. /**
  101771. * Creates a new VRDeviceOrientationFreeCamera
  101772. * @param name defines camera name
  101773. * @param position defines the start position of the camera
  101774. * @param scene defines the scene the camera belongs to
  101775. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101776. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101777. */
  101778. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101779. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101780. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101781. var _this = _super.call(this, name, position, scene) || this;
  101782. vrCameraMetrics.compensateDistortion = compensateDistortion;
  101783. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101784. return _this;
  101785. }
  101786. /**
  101787. * Gets camera class name
  101788. * @returns VRDeviceOrientationFreeCamera
  101789. */
  101790. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  101791. return "VRDeviceOrientationFreeCamera";
  101792. };
  101793. return VRDeviceOrientationFreeCamera;
  101794. }(BABYLON.DeviceOrientationCamera));
  101795. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  101796. })(BABYLON || (BABYLON = {}));
  101797. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  101798. var BABYLON;
  101799. (function (BABYLON) {
  101800. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  101801. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  101802. });
  101803. /**
  101804. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  101805. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101806. */
  101807. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  101808. __extends(VRDeviceOrientationArcRotateCamera, _super);
  101809. /**
  101810. * Creates a new VRDeviceOrientationArcRotateCamera
  101811. * @param name defines camera name
  101812. * @param alpha defines the camera rotation along the logitudinal axis
  101813. * @param beta defines the camera rotation along the latitudinal axis
  101814. * @param radius defines the camera distance from its target
  101815. * @param target defines the camera target
  101816. * @param scene defines the scene the camera belongs to
  101817. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101818. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101819. */
  101820. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  101821. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101822. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101823. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101824. vrCameraMetrics.compensateDistortion = compensateDistortion;
  101825. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101826. _this.inputs.addVRDeviceOrientation();
  101827. return _this;
  101828. }
  101829. /**
  101830. * Gets camera class name
  101831. * @returns VRDeviceOrientationArcRotateCamera
  101832. */
  101833. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  101834. return "VRDeviceOrientationArcRotateCamera";
  101835. };
  101836. return VRDeviceOrientationArcRotateCamera;
  101837. }(BABYLON.ArcRotateCamera));
  101838. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  101839. })(BABYLON || (BABYLON = {}));
  101840. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  101841. var BABYLON;
  101842. (function (BABYLON) {
  101843. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  101844. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  101845. });
  101846. /**
  101847. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  101848. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101849. */
  101850. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  101851. __extends(VRDeviceOrientationGamepadCamera, _super);
  101852. /**
  101853. * Creates a new VRDeviceOrientationGamepadCamera
  101854. * @param name defines camera name
  101855. * @param position defines the start position of the camera
  101856. * @param scene defines the scene the camera belongs to
  101857. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101858. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101859. */
  101860. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101861. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101862. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101863. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  101864. _this.inputs.addGamepad();
  101865. return _this;
  101866. }
  101867. /**
  101868. * Gets camera class name
  101869. * @returns VRDeviceOrientationGamepadCamera
  101870. */
  101871. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  101872. return "VRDeviceOrientationGamepadCamera";
  101873. };
  101874. return VRDeviceOrientationGamepadCamera;
  101875. }(BABYLON.VRDeviceOrientationFreeCamera));
  101876. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  101877. })(BABYLON || (BABYLON = {}));
  101878. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  101879. var BABYLON;
  101880. (function (BABYLON) {
  101881. var VRExperienceHelperGazer = /** @class */ (function () {
  101882. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  101883. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  101884. this.scene = scene;
  101885. /** @hidden */
  101886. this._pointerDownOnMeshAsked = false;
  101887. /** @hidden */
  101888. this._isActionableMesh = false;
  101889. /** @hidden */
  101890. this._teleportationRequestInitiated = false;
  101891. /** @hidden */
  101892. this._teleportationBackRequestInitiated = false;
  101893. /** @hidden */
  101894. this._rotationRightAsked = false;
  101895. /** @hidden */
  101896. this._rotationLeftAsked = false;
  101897. /** @hidden */
  101898. this._dpadPressed = true;
  101899. /** @hidden */
  101900. this._activePointer = false;
  101901. this._id = VRExperienceHelperGazer._idCounter++;
  101902. // Gaze tracker
  101903. if (!gazeTrackerToClone) {
  101904. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  101905. this._gazeTracker.bakeCurrentTransformIntoVertices();
  101906. this._gazeTracker.isPickable = false;
  101907. this._gazeTracker.isVisible = false;
  101908. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  101909. targetMat.specularColor = BABYLON.Color3.Black();
  101910. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101911. targetMat.backFaceCulling = false;
  101912. this._gazeTracker.material = targetMat;
  101913. }
  101914. else {
  101915. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  101916. }
  101917. }
  101918. /** @hidden */
  101919. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  101920. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  101921. };
  101922. /** @hidden */
  101923. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  101924. this._pointerDownOnMeshAsked = true;
  101925. if (this._currentHit) {
  101926. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  101927. }
  101928. };
  101929. /** @hidden */
  101930. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  101931. if (this._currentHit) {
  101932. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  101933. }
  101934. this._pointerDownOnMeshAsked = false;
  101935. };
  101936. /** @hidden */
  101937. VRExperienceHelperGazer.prototype._activatePointer = function () {
  101938. this._activePointer = true;
  101939. };
  101940. /** @hidden */
  101941. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  101942. this._activePointer = false;
  101943. };
  101944. /** @hidden */
  101945. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  101946. if (distance === void 0) { distance = 100; }
  101947. };
  101948. VRExperienceHelperGazer.prototype.dispose = function () {
  101949. this._interactionsEnabled = false;
  101950. this._teleportationEnabled = false;
  101951. if (this._gazeTracker) {
  101952. this._gazeTracker.dispose();
  101953. }
  101954. };
  101955. VRExperienceHelperGazer._idCounter = 0;
  101956. return VRExperienceHelperGazer;
  101957. }());
  101958. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  101959. __extends(VRExperienceHelperControllerGazer, _super);
  101960. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  101961. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  101962. _this.webVRController = webVRController;
  101963. // Laser pointer
  101964. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  101965. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  101966. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101967. laserPointerMaterial.alpha = 0.6;
  101968. _this._laserPointer.material = laserPointerMaterial;
  101969. _this._laserPointer.rotation.x = Math.PI / 2;
  101970. _this._laserPointer.position.z = -0.5;
  101971. _this._laserPointer.isVisible = false;
  101972. _this._laserPointer.isPickable = false;
  101973. if (!webVRController.mesh) {
  101974. // Create an empty mesh that is used prior to loading the high quality model
  101975. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  101976. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  101977. preloadPointerPose.rotation.x = -0.7;
  101978. preloadMesh.addChild(preloadPointerPose);
  101979. webVRController.attachToMesh(preloadMesh);
  101980. }
  101981. _this._setLaserPointerParent(webVRController.mesh);
  101982. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  101983. _this._setLaserPointerParent(mesh);
  101984. });
  101985. return _this;
  101986. }
  101987. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  101988. return this.webVRController.getForwardRay(length);
  101989. };
  101990. /** @hidden */
  101991. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  101992. _super.prototype._activatePointer.call(this);
  101993. this._laserPointer.isVisible = true;
  101994. };
  101995. /** @hidden */
  101996. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  101997. _super.prototype._deactivatePointer.call(this);
  101998. this._laserPointer.isVisible = false;
  101999. };
  102000. /** @hidden */
  102001. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  102002. this._laserPointer.material.emissiveColor = color;
  102003. };
  102004. /** @hidden */
  102005. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  102006. var makeNotPick = function (root) {
  102007. root.isPickable = false;
  102008. root.getChildMeshes().forEach(function (c) {
  102009. makeNotPick(c);
  102010. });
  102011. };
  102012. makeNotPick(mesh);
  102013. var childMeshes = mesh.getChildMeshes();
  102014. this.webVRController._pointingPoseNode = null;
  102015. for (var i = 0; i < childMeshes.length; i++) {
  102016. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  102017. mesh = childMeshes[i];
  102018. this.webVRController._pointingPoseNode = mesh;
  102019. break;
  102020. }
  102021. }
  102022. this._laserPointer.parent = mesh;
  102023. };
  102024. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  102025. if (distance === void 0) { distance = 100; }
  102026. this._laserPointer.scaling.y = distance;
  102027. this._laserPointer.position.z = -distance / 2;
  102028. };
  102029. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102030. _super.prototype.dispose.call(this);
  102031. this._laserPointer.dispose();
  102032. if (this._meshAttachedObserver) {
  102033. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102034. }
  102035. };
  102036. return VRExperienceHelperControllerGazer;
  102037. }(VRExperienceHelperGazer));
  102038. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102039. __extends(VRExperienceHelperCameraGazer, _super);
  102040. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102041. var _this = _super.call(this, scene) || this;
  102042. _this.getCamera = getCamera;
  102043. return _this;
  102044. }
  102045. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102046. var camera = this.getCamera();
  102047. if (camera) {
  102048. return camera.getForwardRay(length);
  102049. }
  102050. else {
  102051. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102052. }
  102053. };
  102054. return VRExperienceHelperCameraGazer;
  102055. }(VRExperienceHelperGazer));
  102056. /**
  102057. * Helps to quickly add VR support to an existing scene.
  102058. * See http://doc.babylonjs.com/how_to/webvr_helper
  102059. */
  102060. var VRExperienceHelper = /** @class */ (function () {
  102061. /**
  102062. * Instantiates a VRExperienceHelper.
  102063. * Helps to quickly add VR support to an existing scene.
  102064. * @param scene The scene the VRExperienceHelper belongs to.
  102065. * @param webVROptions Options to modify the vr experience helper's behavior.
  102066. */
  102067. function VRExperienceHelper(scene,
  102068. /** Options to modify the vr experience helper's behavior. */
  102069. webVROptions) {
  102070. if (webVROptions === void 0) { webVROptions = {}; }
  102071. var _this = this;
  102072. this.webVROptions = webVROptions;
  102073. // Can the system support WebVR, even if a headset isn't plugged in?
  102074. this._webVRsupported = false;
  102075. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102076. this._webVRready = false;
  102077. // Are we waiting for the requestPresent callback to complete?
  102078. this._webVRrequesting = false;
  102079. // Are we presenting to the headset right now? (this is the vrDevice state)
  102080. this._webVRpresenting = false;
  102081. // Are we presenting in the fullscreen fallback?
  102082. this._fullscreenVRpresenting = false;
  102083. /**
  102084. * Observable raised when entering VR.
  102085. */
  102086. this.onEnteringVRObservable = new BABYLON.Observable();
  102087. /**
  102088. * Observable raised when exiting VR.
  102089. */
  102090. this.onExitingVRObservable = new BABYLON.Observable();
  102091. /**
  102092. * Observable raised when controller mesh is loaded.
  102093. */
  102094. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102095. this._useCustomVRButton = false;
  102096. this._teleportationRequested = false;
  102097. this._teleportActive = false;
  102098. this._floorMeshesCollection = [];
  102099. this._rotationAllowed = true;
  102100. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  102101. this._isDefaultTeleportationTarget = true;
  102102. this._teleportationFillColor = "#444444";
  102103. this._teleportationBorderColor = "#FFFFFF";
  102104. this._rotationAngle = 0;
  102105. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  102106. this._padSensibilityUp = 0.65;
  102107. this._padSensibilityDown = 0.35;
  102108. this._leftController = null;
  102109. this._rightController = null;
  102110. /**
  102111. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  102112. */
  102113. this.onNewMeshSelected = new BABYLON.Observable();
  102114. /**
  102115. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  102116. */
  102117. this.onNewMeshPicked = new BABYLON.Observable();
  102118. /**
  102119. * Observable raised before camera teleportation
  102120. */
  102121. this.onBeforeCameraTeleport = new BABYLON.Observable();
  102122. /**
  102123. * Observable raised after camera teleportation
  102124. */
  102125. this.onAfterCameraTeleport = new BABYLON.Observable();
  102126. /**
  102127. * Observable raised when current selected mesh gets unselected
  102128. */
  102129. this.onSelectedMeshUnselected = new BABYLON.Observable();
  102130. /**
  102131. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  102132. */
  102133. this.teleportationEnabled = true;
  102134. this._teleportationInitialized = false;
  102135. this._interactionsEnabled = false;
  102136. this._interactionsRequested = false;
  102137. this._displayGaze = true;
  102138. this._displayLaserPointer = true;
  102139. /**
  102140. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  102141. */
  102142. this.updateGazeTrackerScale = true;
  102143. this._onResize = function () {
  102144. _this.moveButtonToBottomRight();
  102145. if (_this._fullscreenVRpresenting && _this._webVRready) {
  102146. _this.exitVR();
  102147. }
  102148. };
  102149. this._onFullscreenChange = function () {
  102150. if (document.fullscreen !== undefined) {
  102151. _this._fullscreenVRpresenting = document.fullscreen;
  102152. }
  102153. else if (document.mozFullScreen !== undefined) {
  102154. _this._fullscreenVRpresenting = document.mozFullScreen;
  102155. }
  102156. else if (document.webkitIsFullScreen !== undefined) {
  102157. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  102158. }
  102159. else if (document.msIsFullScreen !== undefined) {
  102160. _this._fullscreenVRpresenting = document.msIsFullScreen;
  102161. }
  102162. else if (document.msFullscreenElement !== undefined) {
  102163. _this._fullscreenVRpresenting = document.msFullscreenElement;
  102164. }
  102165. if (!_this._fullscreenVRpresenting && _this._canvas) {
  102166. _this.exitVR();
  102167. if (!_this._useCustomVRButton) {
  102168. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  102169. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  102170. }
  102171. }
  102172. };
  102173. this.beforeRender = function () {
  102174. if (_this._leftController && _this._leftController._activePointer) {
  102175. _this._castRayAndSelectObject(_this._leftController);
  102176. }
  102177. if (_this._rightController && _this._rightController._activePointer) {
  102178. _this._castRayAndSelectObject(_this._rightController);
  102179. }
  102180. if (_this._noControllerIsActive) {
  102181. _this._castRayAndSelectObject(_this._cameraGazer);
  102182. }
  102183. else {
  102184. _this._cameraGazer._gazeTracker.isVisible = false;
  102185. }
  102186. };
  102187. this._onNewGamepadConnected = function (gamepad) {
  102188. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  102189. if (gamepad.leftStick) {
  102190. gamepad.onleftstickchanged(function (stickValues) {
  102191. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  102192. // Listening to classic/xbox gamepad only if no VR controller is active
  102193. if ((!_this._leftController && !_this._rightController) ||
  102194. ((_this._leftController && !_this._leftController._activePointer) &&
  102195. (_this._rightController && !_this._rightController._activePointer))) {
  102196. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  102197. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  102198. }
  102199. }
  102200. });
  102201. }
  102202. if (gamepad.rightStick) {
  102203. gamepad.onrightstickchanged(function (stickValues) {
  102204. if (_this._teleportationInitialized) {
  102205. _this._checkRotate(stickValues, _this._cameraGazer);
  102206. }
  102207. });
  102208. }
  102209. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  102210. gamepad.onbuttondown(function (buttonPressed) {
  102211. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  102212. _this._cameraGazer._selectionPointerDown();
  102213. }
  102214. });
  102215. gamepad.onbuttonup(function (buttonPressed) {
  102216. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  102217. _this._cameraGazer._selectionPointerUp();
  102218. }
  102219. });
  102220. }
  102221. }
  102222. else {
  102223. var webVRController = gamepad;
  102224. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  102225. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  102226. _this._rightController = controller;
  102227. }
  102228. else {
  102229. _this._leftController = controller;
  102230. }
  102231. _this._tryEnableInteractionOnController(controller);
  102232. }
  102233. };
  102234. // 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
  102235. this._tryEnableInteractionOnController = function (controller) {
  102236. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  102237. _this._enableInteractionOnController(controller);
  102238. }
  102239. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  102240. _this._enableTeleportationOnController(controller);
  102241. }
  102242. };
  102243. this._onNewGamepadDisconnected = function (gamepad) {
  102244. if (gamepad instanceof BABYLON.WebVRController) {
  102245. if (gamepad.hand === "left" && _this._leftController != null) {
  102246. _this._leftController.dispose();
  102247. _this._leftController = null;
  102248. }
  102249. if (gamepad.hand === "right" && _this._rightController != null) {
  102250. _this._rightController.dispose();
  102251. _this._rightController = null;
  102252. }
  102253. }
  102254. };
  102255. this._workingVector = BABYLON.Vector3.Zero();
  102256. this._workingQuaternion = BABYLON.Quaternion.Identity();
  102257. this._workingMatrix = BABYLON.Matrix.Identity();
  102258. this._scene = scene;
  102259. this._canvas = scene.getEngine().getRenderingCanvas();
  102260. // Parse options
  102261. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  102262. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  102263. }
  102264. if (webVROptions.createDeviceOrientationCamera === undefined) {
  102265. webVROptions.createDeviceOrientationCamera = true;
  102266. }
  102267. if (webVROptions.laserToggle === undefined) {
  102268. webVROptions.laserToggle = true;
  102269. }
  102270. if (webVROptions.defaultHeight === undefined) {
  102271. webVROptions.defaultHeight = 1.7;
  102272. }
  102273. if (webVROptions.useCustomVRButton) {
  102274. this._useCustomVRButton = true;
  102275. if (webVROptions.customVRButton) {
  102276. this._btnVR = webVROptions.customVRButton;
  102277. }
  102278. }
  102279. if (webVROptions.rayLength) {
  102280. this._rayLength = webVROptions.rayLength;
  102281. }
  102282. this._defaultHeight = webVROptions.defaultHeight;
  102283. if (webVROptions.positionScale) {
  102284. this._rayLength *= webVROptions.positionScale;
  102285. this._defaultHeight *= webVROptions.positionScale;
  102286. }
  102287. this._hasEnteredVR = false;
  102288. // Set position
  102289. if (this._scene.activeCamera) {
  102290. this._position = this._scene.activeCamera.position.clone();
  102291. }
  102292. else {
  102293. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  102294. }
  102295. // Set non-vr camera
  102296. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  102297. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  102298. // Copy data from existing camera
  102299. if (this._scene.activeCamera) {
  102300. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  102301. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  102302. // Set rotation from previous camera
  102303. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  102304. var targetCamera = this._scene.activeCamera;
  102305. if (targetCamera.rotationQuaternion) {
  102306. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  102307. }
  102308. else {
  102309. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  102310. }
  102311. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  102312. }
  102313. }
  102314. this._scene.activeCamera = this._deviceOrientationCamera;
  102315. if (this._canvas) {
  102316. this._scene.activeCamera.attachControl(this._canvas);
  102317. }
  102318. }
  102319. else {
  102320. this._existingCamera = this._scene.activeCamera;
  102321. }
  102322. // Create VR cameras
  102323. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  102324. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  102325. }
  102326. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  102327. this._webVRCamera.useStandingMatrix();
  102328. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  102329. // Create default button
  102330. if (!this._useCustomVRButton) {
  102331. this._btnVR = document.createElement("BUTTON");
  102332. this._btnVR.className = "babylonVRicon";
  102333. this._btnVR.id = "babylonVRiconbtn";
  102334. this._btnVR.title = "Click to switch to VR";
  102335. 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) }";
  102336. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  102337. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  102338. // css += ".babylonVRicon.vrdisplaysupported { }";
  102339. // css += ".babylonVRicon.vrdisplayready { }";
  102340. // css += ".babylonVRicon.vrdisplayrequesting { }";
  102341. var style = document.createElement('style');
  102342. style.appendChild(document.createTextNode(css));
  102343. document.getElementsByTagName('head')[0].appendChild(style);
  102344. this.moveButtonToBottomRight();
  102345. }
  102346. // VR button click event
  102347. if (this._btnVR) {
  102348. this._btnVR.addEventListener("click", function () {
  102349. if (!_this.isInVRMode) {
  102350. _this.enterVR();
  102351. }
  102352. else {
  102353. _this.exitVR();
  102354. }
  102355. });
  102356. }
  102357. // Window events
  102358. window.addEventListener("resize", this._onResize);
  102359. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  102360. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  102361. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  102362. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  102363. document.onmsfullscreenchange = this._onFullscreenChange;
  102364. // Display vr button when headset is connected
  102365. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  102366. this.displayVRButton();
  102367. }
  102368. else {
  102369. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  102370. if (e.vrDisplay) {
  102371. _this.displayVRButton();
  102372. }
  102373. });
  102374. }
  102375. // Exiting VR mode using 'ESC' key on desktop
  102376. this._onKeyDown = function (event) {
  102377. if (event.keyCode === 27 && _this.isInVRMode) {
  102378. _this.exitVR();
  102379. }
  102380. };
  102381. document.addEventListener("keydown", this._onKeyDown);
  102382. // Exiting VR mode double tapping the touch screen
  102383. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  102384. if (_this.isInVRMode) {
  102385. _this.exitVR();
  102386. if (_this._fullscreenVRpresenting) {
  102387. _this._scene.getEngine().switchFullscreen(true);
  102388. }
  102389. }
  102390. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  102391. // Listen for WebVR display changes
  102392. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  102393. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  102394. this._onVRRequestPresentStart = function () {
  102395. _this._webVRrequesting = true;
  102396. _this.updateButtonVisibility();
  102397. };
  102398. this._onVRRequestPresentComplete = function (success) {
  102399. _this._webVRrequesting = false;
  102400. _this.updateButtonVisibility();
  102401. };
  102402. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  102403. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  102404. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  102405. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102406. scene.onDisposeObservable.add(function () {
  102407. _this.dispose();
  102408. });
  102409. // Gamepad connection events
  102410. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  102411. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  102412. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  102413. this.updateButtonVisibility();
  102414. //create easing functions
  102415. this._circleEase = new BABYLON.CircleEase();
  102416. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  102417. if (this.webVROptions.floorMeshes) {
  102418. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  102419. }
  102420. }
  102421. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  102422. /** Return this.onEnteringVRObservable
  102423. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  102424. */
  102425. get: function () {
  102426. return this.onEnteringVRObservable;
  102427. },
  102428. enumerable: true,
  102429. configurable: true
  102430. });
  102431. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  102432. /** Return this.onExitingVRObservable
  102433. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  102434. */
  102435. get: function () {
  102436. return this.onExitingVRObservable;
  102437. },
  102438. enumerable: true,
  102439. configurable: true
  102440. });
  102441. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  102442. /** Return this.onControllerMeshLoadedObservable
  102443. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  102444. */
  102445. get: function () {
  102446. return this.onControllerMeshLoadedObservable;
  102447. },
  102448. enumerable: true,
  102449. configurable: true
  102450. });
  102451. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  102452. /**
  102453. * The mesh used to display where the user is going to teleport.
  102454. */
  102455. get: function () {
  102456. return this._teleportationTarget;
  102457. },
  102458. /**
  102459. * Sets the mesh to be used to display where the user is going to teleport.
  102460. */
  102461. set: function (value) {
  102462. if (value) {
  102463. value.name = "teleportationTarget";
  102464. this._isDefaultTeleportationTarget = false;
  102465. this._teleportationTarget = value;
  102466. }
  102467. },
  102468. enumerable: true,
  102469. configurable: true
  102470. });
  102471. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  102472. /**
  102473. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  102474. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  102475. * See http://doc.babylonjs.com/resources/baking_transformations
  102476. */
  102477. get: function () {
  102478. return this._cameraGazer._gazeTracker;
  102479. },
  102480. set: function (value) {
  102481. if (value) {
  102482. // Dispose of existing meshes
  102483. if (this._cameraGazer._gazeTracker) {
  102484. this._cameraGazer._gazeTracker.dispose();
  102485. }
  102486. if (this._leftController && this._leftController._gazeTracker) {
  102487. this._leftController._gazeTracker.dispose();
  102488. }
  102489. if (this._rightController && this._rightController._gazeTracker) {
  102490. this._rightController._gazeTracker.dispose();
  102491. }
  102492. // Set and create gaze trackers on head and controllers
  102493. this._cameraGazer._gazeTracker = value;
  102494. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  102495. this._cameraGazer._gazeTracker.isPickable = false;
  102496. this._cameraGazer._gazeTracker.isVisible = false;
  102497. this._cameraGazer._gazeTracker.name = "gazeTracker";
  102498. if (this._leftController) {
  102499. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  102500. }
  102501. if (this._rightController) {
  102502. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  102503. }
  102504. }
  102505. },
  102506. enumerable: true,
  102507. configurable: true
  102508. });
  102509. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  102510. /**
  102511. * The gaze tracking mesh corresponding to the left controller
  102512. */
  102513. get: function () {
  102514. if (this._leftController) {
  102515. return this._leftController._gazeTracker;
  102516. }
  102517. return null;
  102518. },
  102519. enumerable: true,
  102520. configurable: true
  102521. });
  102522. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  102523. /**
  102524. * The gaze tracking mesh corresponding to the right controller
  102525. */
  102526. get: function () {
  102527. if (this._rightController) {
  102528. return this._rightController._gazeTracker;
  102529. }
  102530. return null;
  102531. },
  102532. enumerable: true,
  102533. configurable: true
  102534. });
  102535. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  102536. /**
  102537. * If the ray of the gaze should be displayed.
  102538. */
  102539. get: function () {
  102540. return this._displayGaze;
  102541. },
  102542. /**
  102543. * Sets if the ray of the gaze should be displayed.
  102544. */
  102545. set: function (value) {
  102546. this._displayGaze = value;
  102547. if (!value) {
  102548. this._cameraGazer._gazeTracker.isVisible = false;
  102549. if (this._leftController) {
  102550. this._leftController._gazeTracker.isVisible = false;
  102551. }
  102552. if (this._rightController) {
  102553. this._rightController._gazeTracker.isVisible = false;
  102554. }
  102555. }
  102556. },
  102557. enumerable: true,
  102558. configurable: true
  102559. });
  102560. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  102561. /**
  102562. * If the ray of the LaserPointer should be displayed.
  102563. */
  102564. get: function () {
  102565. return this._displayLaserPointer;
  102566. },
  102567. /**
  102568. * Sets if the ray of the LaserPointer should be displayed.
  102569. */
  102570. set: function (value) {
  102571. this._displayLaserPointer = value;
  102572. if (!value) {
  102573. if (this._rightController) {
  102574. this._rightController._deactivatePointer();
  102575. this._rightController._gazeTracker.isVisible = false;
  102576. }
  102577. if (this._leftController) {
  102578. this._leftController._deactivatePointer();
  102579. this._leftController._gazeTracker.isVisible = false;
  102580. }
  102581. }
  102582. else {
  102583. if (this._rightController) {
  102584. this._rightController._activatePointer();
  102585. }
  102586. if (this._leftController) {
  102587. this._leftController._activatePointer();
  102588. }
  102589. }
  102590. },
  102591. enumerable: true,
  102592. configurable: true
  102593. });
  102594. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  102595. /**
  102596. * The deviceOrientationCamera used as the camera when not in VR.
  102597. */
  102598. get: function () {
  102599. return this._deviceOrientationCamera;
  102600. },
  102601. enumerable: true,
  102602. configurable: true
  102603. });
  102604. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  102605. /**
  102606. * Based on the current WebVR support, returns the current VR camera used.
  102607. */
  102608. get: function () {
  102609. if (this._webVRready) {
  102610. return this._webVRCamera;
  102611. }
  102612. else {
  102613. return this._scene.activeCamera;
  102614. }
  102615. },
  102616. enumerable: true,
  102617. configurable: true
  102618. });
  102619. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  102620. /**
  102621. * The webVRCamera which is used when in VR.
  102622. */
  102623. get: function () {
  102624. return this._webVRCamera;
  102625. },
  102626. enumerable: true,
  102627. configurable: true
  102628. });
  102629. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  102630. /**
  102631. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  102632. */
  102633. get: function () {
  102634. return this._vrDeviceOrientationCamera;
  102635. },
  102636. enumerable: true,
  102637. configurable: true
  102638. });
  102639. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  102640. get: function () {
  102641. var result = this._cameraGazer._teleportationRequestInitiated
  102642. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  102643. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  102644. return result;
  102645. },
  102646. enumerable: true,
  102647. configurable: true
  102648. });
  102649. // Raised when one of the controller has loaded successfully its associated default mesh
  102650. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  102651. if (this._leftController && this._leftController.webVRController == webVRController) {
  102652. if (webVRController.mesh) {
  102653. this._leftController._setLaserPointerParent(webVRController.mesh);
  102654. }
  102655. }
  102656. if (this._rightController && this._rightController.webVRController == webVRController) {
  102657. if (webVRController.mesh) {
  102658. this._rightController._setLaserPointerParent(webVRController.mesh);
  102659. }
  102660. }
  102661. try {
  102662. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  102663. }
  102664. catch (err) {
  102665. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  102666. }
  102667. };
  102668. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  102669. /**
  102670. * Gets a value indicating if we are currently in VR mode.
  102671. */
  102672. get: function () {
  102673. return this._webVRpresenting || this._fullscreenVRpresenting;
  102674. },
  102675. enumerable: true,
  102676. configurable: true
  102677. });
  102678. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  102679. var vrDisplay = this._scene.getEngine().getVRDevice();
  102680. if (vrDisplay) {
  102681. var wasPresenting = this._webVRpresenting;
  102682. this._webVRpresenting = vrDisplay.isPresenting;
  102683. if (wasPresenting && !this._webVRpresenting)
  102684. this.exitVR();
  102685. }
  102686. else {
  102687. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  102688. }
  102689. this.updateButtonVisibility();
  102690. };
  102691. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  102692. this._webVRsupported = eventArgs.vrSupported;
  102693. this._webVRready = !!eventArgs.vrDisplay;
  102694. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  102695. this.updateButtonVisibility();
  102696. };
  102697. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  102698. if (this._canvas && !this._useCustomVRButton) {
  102699. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  102700. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  102701. }
  102702. };
  102703. VRExperienceHelper.prototype.displayVRButton = function () {
  102704. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  102705. document.body.appendChild(this._btnVR);
  102706. this._btnVRDisplayed = true;
  102707. }
  102708. };
  102709. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  102710. if (!this._btnVR || this._useCustomVRButton) {
  102711. return;
  102712. }
  102713. this._btnVR.className = "babylonVRicon";
  102714. if (this.isInVRMode) {
  102715. this._btnVR.className += " vrdisplaypresenting";
  102716. }
  102717. else {
  102718. if (this._webVRready)
  102719. this._btnVR.className += " vrdisplayready";
  102720. if (this._webVRsupported)
  102721. this._btnVR.className += " vrdisplaysupported";
  102722. if (this._webVRrequesting)
  102723. this._btnVR.className += " vrdisplayrequesting";
  102724. }
  102725. };
  102726. /**
  102727. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  102728. * Otherwise, will use the fullscreen API.
  102729. */
  102730. VRExperienceHelper.prototype.enterVR = function () {
  102731. if (this.onEnteringVRObservable) {
  102732. try {
  102733. this.onEnteringVRObservable.notifyObservers(this);
  102734. }
  102735. catch (err) {
  102736. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  102737. }
  102738. }
  102739. if (this._scene.activeCamera) {
  102740. this._position = this._scene.activeCamera.position.clone();
  102741. // make sure that we return to the last active camera
  102742. this._existingCamera = this._scene.activeCamera;
  102743. }
  102744. if (this._webVRrequesting)
  102745. return;
  102746. // If WebVR is supported and a headset is connected
  102747. if (this._webVRready) {
  102748. if (!this._webVRpresenting) {
  102749. this._webVRCamera.position = this._position;
  102750. this._scene.activeCamera = this._webVRCamera;
  102751. }
  102752. }
  102753. else if (this._vrDeviceOrientationCamera) {
  102754. this._vrDeviceOrientationCamera.position = this._position;
  102755. if (this._scene.activeCamera) {
  102756. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  102757. }
  102758. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  102759. this._scene.getEngine().switchFullscreen(true);
  102760. this.updateButtonVisibility();
  102761. }
  102762. if (this._scene.activeCamera && this._canvas) {
  102763. this._scene.activeCamera.attachControl(this._canvas);
  102764. }
  102765. if (this._interactionsEnabled) {
  102766. this._scene.registerBeforeRender(this.beforeRender);
  102767. }
  102768. this._hasEnteredVR = true;
  102769. };
  102770. /**
  102771. * Attempt to exit VR, or fullscreen.
  102772. */
  102773. VRExperienceHelper.prototype.exitVR = function () {
  102774. if (this._hasEnteredVR) {
  102775. if (this.onExitingVRObservable) {
  102776. try {
  102777. this.onExitingVRObservable.notifyObservers(this);
  102778. }
  102779. catch (err) {
  102780. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  102781. }
  102782. }
  102783. if (this._webVRpresenting) {
  102784. this._scene.getEngine().disableVR();
  102785. }
  102786. if (this._scene.activeCamera) {
  102787. this._position = this._scene.activeCamera.position.clone();
  102788. }
  102789. if (this._deviceOrientationCamera) {
  102790. this._deviceOrientationCamera.position = this._position;
  102791. this._scene.activeCamera = this._deviceOrientationCamera;
  102792. if (this._canvas) {
  102793. this._scene.activeCamera.attachControl(this._canvas);
  102794. }
  102795. }
  102796. else if (this._existingCamera) {
  102797. this._existingCamera.position = this._position;
  102798. this._scene.activeCamera = this._existingCamera;
  102799. }
  102800. this.updateButtonVisibility();
  102801. if (this._interactionsEnabled) {
  102802. this._scene.unregisterBeforeRender(this.beforeRender);
  102803. this._cameraGazer._gazeTracker.isVisible = false;
  102804. if (this._leftController) {
  102805. this._leftController._gazeTracker.isVisible = false;
  102806. }
  102807. if (this._rightController) {
  102808. this._rightController._gazeTracker.isVisible = false;
  102809. }
  102810. }
  102811. // resize to update width and height when exiting vr exits fullscreen
  102812. this._scene.getEngine().resize();
  102813. this._hasEnteredVR = false;
  102814. }
  102815. };
  102816. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  102817. /**
  102818. * The position of the vr experience helper.
  102819. */
  102820. get: function () {
  102821. return this._position;
  102822. },
  102823. /**
  102824. * Sets the position of the vr experience helper.
  102825. */
  102826. set: function (value) {
  102827. this._position = value;
  102828. if (this._scene.activeCamera) {
  102829. this._scene.activeCamera.position = value;
  102830. }
  102831. },
  102832. enumerable: true,
  102833. configurable: true
  102834. });
  102835. /**
  102836. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  102837. */
  102838. VRExperienceHelper.prototype.enableInteractions = function () {
  102839. var _this = this;
  102840. if (!this._interactionsEnabled) {
  102841. this._interactionsRequested = true;
  102842. if (this._leftController) {
  102843. this._enableInteractionOnController(this._leftController);
  102844. }
  102845. if (this._rightController) {
  102846. this._enableInteractionOnController(this._rightController);
  102847. }
  102848. this.raySelectionPredicate = function (mesh) {
  102849. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  102850. };
  102851. this.meshSelectionPredicate = function (mesh) {
  102852. return true;
  102853. };
  102854. this._raySelectionPredicate = function (mesh) {
  102855. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  102856. && mesh.name.indexOf("teleportationTarget") === -1
  102857. && mesh.name.indexOf("torusTeleportation") === -1)) {
  102858. return _this.raySelectionPredicate(mesh);
  102859. }
  102860. return false;
  102861. };
  102862. this._interactionsEnabled = true;
  102863. }
  102864. };
  102865. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  102866. get: function () {
  102867. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  102868. },
  102869. enumerable: true,
  102870. configurable: true
  102871. });
  102872. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  102873. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  102874. if (this._floorMeshesCollection[i].id === mesh.id) {
  102875. return true;
  102876. }
  102877. }
  102878. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  102879. return true;
  102880. }
  102881. return false;
  102882. };
  102883. /**
  102884. * Adds a floor mesh to be used for teleportation.
  102885. * @param floorMesh the mesh to be used for teleportation.
  102886. */
  102887. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  102888. if (!this._floorMeshesCollection) {
  102889. return;
  102890. }
  102891. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  102892. return;
  102893. }
  102894. this._floorMeshesCollection.push(floorMesh);
  102895. };
  102896. /**
  102897. * Removes a floor mesh from being used for teleportation.
  102898. * @param floorMesh the mesh to be removed.
  102899. */
  102900. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  102901. if (!this._floorMeshesCollection) {
  102902. return;
  102903. }
  102904. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  102905. if (meshIndex !== -1) {
  102906. this._floorMeshesCollection.splice(meshIndex, 1);
  102907. }
  102908. };
  102909. /**
  102910. * Enables interactions and teleportation using the VR controllers and gaze.
  102911. * @param vrTeleportationOptions options to modify teleportation behavior.
  102912. */
  102913. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  102914. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  102915. if (!this._teleportationInitialized) {
  102916. this._teleportationRequested = true;
  102917. this.enableInteractions();
  102918. if (vrTeleportationOptions.floorMeshName) {
  102919. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  102920. }
  102921. if (vrTeleportationOptions.floorMeshes) {
  102922. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  102923. }
  102924. if (this._leftController != null) {
  102925. this._enableTeleportationOnController(this._leftController);
  102926. }
  102927. if (this._rightController != null) {
  102928. this._enableTeleportationOnController(this._rightController);
  102929. }
  102930. // Creates an image processing post process for the vignette not relying
  102931. // on the main scene configuration for image processing to reduce setup and spaces
  102932. // (gamma/linear) conflicts.
  102933. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  102934. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  102935. imageProcessingConfiguration.vignetteEnabled = true;
  102936. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  102937. this._webVRCamera.detachPostProcess(this._postProcessMove);
  102938. this._teleportationInitialized = true;
  102939. if (this._isDefaultTeleportationTarget) {
  102940. this._createTeleportationCircles();
  102941. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  102942. }
  102943. }
  102944. };
  102945. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  102946. var _this = this;
  102947. var controllerMesh = controller.webVRController.mesh;
  102948. if (controllerMesh) {
  102949. controller._interactionsEnabled = true;
  102950. controller._activatePointer();
  102951. if (this.webVROptions.laserToggle) {
  102952. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  102953. // Enabling / disabling laserPointer
  102954. if (_this._displayLaserPointer && stateObject.value === 1) {
  102955. if (controller._activePointer) {
  102956. controller._deactivatePointer();
  102957. }
  102958. else {
  102959. controller._activatePointer();
  102960. }
  102961. if (_this.displayGaze) {
  102962. controller._gazeTracker.isVisible = controller._activePointer;
  102963. }
  102964. }
  102965. });
  102966. }
  102967. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  102968. var gazer = controller;
  102969. if (_this._noControllerIsActive) {
  102970. gazer = _this._cameraGazer;
  102971. }
  102972. if (!gazer._pointerDownOnMeshAsked) {
  102973. if (stateObject.value > _this._padSensibilityUp) {
  102974. gazer._selectionPointerDown();
  102975. }
  102976. }
  102977. else if (stateObject.value < _this._padSensibilityDown) {
  102978. gazer._selectionPointerUp();
  102979. }
  102980. });
  102981. }
  102982. };
  102983. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  102984. // Dont teleport if another gaze already requested teleportation
  102985. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  102986. return;
  102987. }
  102988. if (!gazer._teleportationRequestInitiated) {
  102989. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  102990. gazer._activatePointer();
  102991. gazer._teleportationRequestInitiated = true;
  102992. }
  102993. }
  102994. else {
  102995. // Listening to the proper controller values changes to confirm teleportation
  102996. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  102997. if (this._teleportActive) {
  102998. this.teleportCamera(this._haloCenter);
  102999. }
  103000. gazer._teleportationRequestInitiated = false;
  103001. }
  103002. }
  103003. };
  103004. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  103005. // Only rotate when user is not currently selecting a teleportation location
  103006. if (gazer._teleportationRequestInitiated) {
  103007. return;
  103008. }
  103009. if (!gazer._rotationLeftAsked) {
  103010. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  103011. gazer._rotationLeftAsked = true;
  103012. if (this._rotationAllowed) {
  103013. this._rotateCamera(false);
  103014. }
  103015. }
  103016. }
  103017. else {
  103018. if (stateObject.x > -this._padSensibilityDown) {
  103019. gazer._rotationLeftAsked = false;
  103020. }
  103021. }
  103022. if (!gazer._rotationRightAsked) {
  103023. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  103024. gazer._rotationRightAsked = true;
  103025. if (this._rotationAllowed) {
  103026. this._rotateCamera(true);
  103027. }
  103028. }
  103029. }
  103030. else {
  103031. if (stateObject.x < this._padSensibilityDown) {
  103032. gazer._rotationRightAsked = false;
  103033. }
  103034. }
  103035. };
  103036. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103037. // Only teleport backwards when user is not currently selecting a teleportation location
  103038. if (gazer._teleportationRequestInitiated) {
  103039. return;
  103040. }
  103041. // Teleport backwards
  103042. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103043. if (!gazer._teleportationBackRequestInitiated) {
  103044. if (!this.currentVRCamera) {
  103045. return;
  103046. }
  103047. // Get rotation and position of the current camera
  103048. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103049. var position = this.currentVRCamera.position;
  103050. // If the camera has device position, use that instead
  103051. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103052. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103053. position = this.currentVRCamera.devicePosition;
  103054. }
  103055. // Get matrix with only the y rotation of the device rotation
  103056. rotation.toEulerAnglesToRef(this._workingVector);
  103057. this._workingVector.z = 0;
  103058. this._workingVector.x = 0;
  103059. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103060. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103061. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103062. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103063. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103064. var ray = new BABYLON.Ray(position, this._workingVector);
  103065. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103066. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103067. this.teleportCamera(hit.pickedPoint);
  103068. }
  103069. gazer._teleportationBackRequestInitiated = true;
  103070. }
  103071. }
  103072. else {
  103073. gazer._teleportationBackRequestInitiated = false;
  103074. }
  103075. };
  103076. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103077. var _this = this;
  103078. var controllerMesh = controller.webVRController.mesh;
  103079. if (controllerMesh) {
  103080. if (!controller._interactionsEnabled) {
  103081. this._enableInteractionOnController(controller);
  103082. }
  103083. controller._interactionsEnabled = true;
  103084. controller._teleportationEnabled = true;
  103085. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103086. controller._dpadPressed = false;
  103087. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103088. controller._dpadPressed = stateObject.pressed;
  103089. if (!controller._dpadPressed) {
  103090. controller._rotationLeftAsked = false;
  103091. controller._rotationRightAsked = false;
  103092. controller._teleportationBackRequestInitiated = false;
  103093. }
  103094. });
  103095. }
  103096. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  103097. if (_this.teleportationEnabled) {
  103098. _this._checkTeleportBackwards(stateObject, controller);
  103099. _this._checkTeleportWithRay(stateObject, controller);
  103100. }
  103101. _this._checkRotate(stateObject, controller);
  103102. });
  103103. }
  103104. };
  103105. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  103106. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  103107. this._teleportationTarget.isPickable = false;
  103108. var length = 512;
  103109. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  103110. dynamicTexture.hasAlpha = true;
  103111. var context = dynamicTexture.getContext();
  103112. var centerX = length / 2;
  103113. var centerY = length / 2;
  103114. var radius = 200;
  103115. context.beginPath();
  103116. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  103117. context.fillStyle = this._teleportationFillColor;
  103118. context.fill();
  103119. context.lineWidth = 10;
  103120. context.strokeStyle = this._teleportationBorderColor;
  103121. context.stroke();
  103122. context.closePath();
  103123. dynamicTexture.update();
  103124. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  103125. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  103126. this._teleportationTarget.material = teleportationCircleMaterial;
  103127. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  103128. torus.isPickable = false;
  103129. torus.parent = this._teleportationTarget;
  103130. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103131. var keys = [];
  103132. keys.push({
  103133. frame: 0,
  103134. value: 0
  103135. });
  103136. keys.push({
  103137. frame: 30,
  103138. value: 0.4
  103139. });
  103140. keys.push({
  103141. frame: 60,
  103142. value: 0
  103143. });
  103144. animationInnerCircle.setKeys(keys);
  103145. var easingFunction = new BABYLON.SineEase();
  103146. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103147. animationInnerCircle.setEasingFunction(easingFunction);
  103148. torus.animations = [];
  103149. torus.animations.push(animationInnerCircle);
  103150. this._scene.beginAnimation(torus, 0, 60, true);
  103151. this._hideTeleportationTarget();
  103152. };
  103153. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  103154. this._teleportActive = true;
  103155. if (this._teleportationInitialized) {
  103156. this._teleportationTarget.isVisible = true;
  103157. if (this._isDefaultTeleportationTarget) {
  103158. this._teleportationTarget.getChildren()[0].isVisible = true;
  103159. }
  103160. }
  103161. };
  103162. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  103163. this._teleportActive = false;
  103164. if (this._teleportationInitialized) {
  103165. this._teleportationTarget.isVisible = false;
  103166. if (this._isDefaultTeleportationTarget) {
  103167. this._teleportationTarget.getChildren()[0].isVisible = false;
  103168. }
  103169. }
  103170. };
  103171. VRExperienceHelper.prototype._rotateCamera = function (right) {
  103172. var _this = this;
  103173. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103174. return;
  103175. }
  103176. if (right) {
  103177. this._rotationAngle++;
  103178. }
  103179. else {
  103180. this._rotationAngle--;
  103181. }
  103182. this.currentVRCamera.animations = [];
  103183. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  103184. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103185. var animationRotationKeys = [];
  103186. animationRotationKeys.push({
  103187. frame: 0,
  103188. value: this.currentVRCamera.rotationQuaternion
  103189. });
  103190. animationRotationKeys.push({
  103191. frame: 6,
  103192. value: target
  103193. });
  103194. animationRotation.setKeys(animationRotationKeys);
  103195. animationRotation.setEasingFunction(this._circleEase);
  103196. this.currentVRCamera.animations.push(animationRotation);
  103197. this._postProcessMove.animations = [];
  103198. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103199. var vignetteWeightKeys = [];
  103200. vignetteWeightKeys.push({
  103201. frame: 0,
  103202. value: 0
  103203. });
  103204. vignetteWeightKeys.push({
  103205. frame: 3,
  103206. value: 4
  103207. });
  103208. vignetteWeightKeys.push({
  103209. frame: 6,
  103210. value: 0
  103211. });
  103212. animationPP.setKeys(vignetteWeightKeys);
  103213. animationPP.setEasingFunction(this._circleEase);
  103214. this._postProcessMove.animations.push(animationPP);
  103215. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103216. var vignetteStretchKeys = [];
  103217. vignetteStretchKeys.push({
  103218. frame: 0,
  103219. value: 0
  103220. });
  103221. vignetteStretchKeys.push({
  103222. frame: 3,
  103223. value: 10
  103224. });
  103225. vignetteStretchKeys.push({
  103226. frame: 6,
  103227. value: 0
  103228. });
  103229. animationPP2.setKeys(vignetteStretchKeys);
  103230. animationPP2.setEasingFunction(this._circleEase);
  103231. this._postProcessMove.animations.push(animationPP2);
  103232. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  103233. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  103234. this._postProcessMove.samples = 4;
  103235. this._webVRCamera.attachPostProcess(this._postProcessMove);
  103236. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  103237. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  103238. });
  103239. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  103240. };
  103241. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  103242. if (hit.pickedPoint) {
  103243. if (gazer._teleportationRequestInitiated) {
  103244. this._displayTeleportationTarget();
  103245. this._haloCenter.copyFrom(hit.pickedPoint);
  103246. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  103247. }
  103248. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  103249. if (pickNormal) {
  103250. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  103251. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  103252. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  103253. }
  103254. this._teleportationTarget.position.y += 0.1;
  103255. }
  103256. };
  103257. /**
  103258. * Teleports the users feet to the desired location
  103259. * @param location The location where the user's feet should be placed
  103260. */
  103261. VRExperienceHelper.prototype.teleportCamera = function (location) {
  103262. var _this = this;
  103263. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103264. return;
  103265. }
  103266. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  103267. // offset of the headset from the anchor.
  103268. if (this.webVRCamera.leftCamera) {
  103269. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  103270. this._workingVector.subtractInPlace(this.webVRCamera.position);
  103271. location.subtractToRef(this._workingVector, this._workingVector);
  103272. }
  103273. else {
  103274. this._workingVector.copyFrom(location);
  103275. }
  103276. // Add height to account for user's height offset
  103277. if (this.isInVRMode) {
  103278. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  103279. }
  103280. else {
  103281. this._workingVector.y += this._defaultHeight;
  103282. }
  103283. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  103284. // Create animation from the camera's position to the new location
  103285. this.currentVRCamera.animations = [];
  103286. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103287. var animationCameraTeleportationKeys = [{
  103288. frame: 0,
  103289. value: this.currentVRCamera.position
  103290. },
  103291. {
  103292. frame: 11,
  103293. value: this._workingVector
  103294. }
  103295. ];
  103296. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  103297. animationCameraTeleportation.setEasingFunction(this._circleEase);
  103298. this.currentVRCamera.animations.push(animationCameraTeleportation);
  103299. this._postProcessMove.animations = [];
  103300. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103301. var vignetteWeightKeys = [];
  103302. vignetteWeightKeys.push({
  103303. frame: 0,
  103304. value: 0
  103305. });
  103306. vignetteWeightKeys.push({
  103307. frame: 5,
  103308. value: 8
  103309. });
  103310. vignetteWeightKeys.push({
  103311. frame: 11,
  103312. value: 0
  103313. });
  103314. animationPP.setKeys(vignetteWeightKeys);
  103315. this._postProcessMove.animations.push(animationPP);
  103316. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103317. var vignetteStretchKeys = [];
  103318. vignetteStretchKeys.push({
  103319. frame: 0,
  103320. value: 0
  103321. });
  103322. vignetteStretchKeys.push({
  103323. frame: 5,
  103324. value: 10
  103325. });
  103326. vignetteStretchKeys.push({
  103327. frame: 11,
  103328. value: 0
  103329. });
  103330. animationPP2.setKeys(vignetteStretchKeys);
  103331. this._postProcessMove.animations.push(animationPP2);
  103332. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  103333. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  103334. this._webVRCamera.attachPostProcess(this._postProcessMove);
  103335. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  103336. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  103337. });
  103338. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  103339. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  103340. });
  103341. this._hideTeleportationTarget();
  103342. };
  103343. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  103344. if (normal) {
  103345. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  103346. if (angle < Math.PI / 2) {
  103347. normal.scaleInPlace(-1);
  103348. }
  103349. }
  103350. return normal;
  103351. };
  103352. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  103353. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  103354. return;
  103355. }
  103356. var ray = gazer._getForwardRay(this._rayLength);
  103357. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103358. if (hit) {
  103359. // Populate the contrllers mesh that can be used for drag/drop
  103360. if (gazer._laserPointer) {
  103361. hit.originMesh = gazer._laserPointer.parent;
  103362. }
  103363. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  103364. }
  103365. gazer._currentHit = hit;
  103366. // Moving the gazeTracker on the mesh face targetted
  103367. if (hit && hit.pickedPoint) {
  103368. if (this._displayGaze) {
  103369. var multiplier = 1;
  103370. gazer._gazeTracker.isVisible = true;
  103371. if (gazer._isActionableMesh) {
  103372. multiplier = 3;
  103373. }
  103374. if (this.updateGazeTrackerScale) {
  103375. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  103376. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  103377. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  103378. }
  103379. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  103380. // To avoid z-fighting
  103381. var deltaFighting = 0.002;
  103382. if (pickNormal) {
  103383. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  103384. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  103385. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  103386. }
  103387. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  103388. if (gazer._gazeTracker.position.x < 0) {
  103389. gazer._gazeTracker.position.x += deltaFighting;
  103390. }
  103391. else {
  103392. gazer._gazeTracker.position.x -= deltaFighting;
  103393. }
  103394. if (gazer._gazeTracker.position.y < 0) {
  103395. gazer._gazeTracker.position.y += deltaFighting;
  103396. }
  103397. else {
  103398. gazer._gazeTracker.position.y -= deltaFighting;
  103399. }
  103400. if (gazer._gazeTracker.position.z < 0) {
  103401. gazer._gazeTracker.position.z += deltaFighting;
  103402. }
  103403. else {
  103404. gazer._gazeTracker.position.z -= deltaFighting;
  103405. }
  103406. }
  103407. // Changing the size of the laser pointer based on the distance from the targetted point
  103408. gazer._updatePointerDistance(hit.distance);
  103409. }
  103410. else {
  103411. gazer._updatePointerDistance();
  103412. gazer._gazeTracker.isVisible = false;
  103413. }
  103414. if (hit && hit.pickedMesh) {
  103415. // The object selected is the floor, we're in a teleportation scenario
  103416. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  103417. // Moving the teleportation area to this targetted point
  103418. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  103419. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  103420. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103421. }
  103422. gazer._currentMeshSelected = null;
  103423. if (gazer._teleportationRequestInitiated) {
  103424. this._moveTeleportationSelectorTo(hit, gazer, ray);
  103425. }
  103426. return;
  103427. }
  103428. // If not, we're in a selection scenario
  103429. //this._teleportationAllowed = false;
  103430. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  103431. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  103432. this.onNewMeshPicked.notifyObservers(hit);
  103433. gazer._currentMeshSelected = hit.pickedMesh;
  103434. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  103435. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  103436. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  103437. gazer._isActionableMesh = true;
  103438. }
  103439. else {
  103440. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103441. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103442. gazer._isActionableMesh = false;
  103443. }
  103444. try {
  103445. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  103446. }
  103447. catch (err) {
  103448. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  103449. }
  103450. }
  103451. else {
  103452. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103453. gazer._currentMeshSelected = null;
  103454. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103455. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103456. }
  103457. }
  103458. }
  103459. else {
  103460. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  103461. gazer._currentMeshSelected = null;
  103462. //this._teleportationAllowed = false;
  103463. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103464. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  103465. }
  103466. };
  103467. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  103468. if (mesh) {
  103469. this.onSelectedMeshUnselected.notifyObservers(mesh);
  103470. }
  103471. };
  103472. /**
  103473. * Sets the color of the laser ray from the vr controllers.
  103474. * @param color new color for the ray.
  103475. */
  103476. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  103477. if (this._leftController) {
  103478. this._leftController._setLaserPointerColor(color);
  103479. }
  103480. if (this._rightController) {
  103481. this._rightController._setLaserPointerColor(color);
  103482. }
  103483. };
  103484. /**
  103485. * Sets the color of the ray from the vr headsets gaze.
  103486. * @param color new color for the ray.
  103487. */
  103488. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  103489. if (!this._cameraGazer._gazeTracker.material) {
  103490. return;
  103491. }
  103492. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  103493. if (this._leftController) {
  103494. this._leftController._gazeTracker.material.emissiveColor = color;
  103495. }
  103496. if (this._rightController) {
  103497. this._rightController._gazeTracker.material.emissiveColor = color;
  103498. }
  103499. };
  103500. /**
  103501. * Exits VR and disposes of the vr experience helper
  103502. */
  103503. VRExperienceHelper.prototype.dispose = function () {
  103504. if (this.isInVRMode) {
  103505. this.exitVR();
  103506. }
  103507. if (this._postProcessMove) {
  103508. this._postProcessMove.dispose();
  103509. }
  103510. if (this._webVRCamera) {
  103511. this._webVRCamera.dispose();
  103512. }
  103513. if (this._vrDeviceOrientationCamera) {
  103514. this._vrDeviceOrientationCamera.dispose();
  103515. }
  103516. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  103517. document.body.removeChild(this._btnVR);
  103518. }
  103519. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  103520. this._deviceOrientationCamera.dispose();
  103521. }
  103522. if (this._cameraGazer) {
  103523. this._cameraGazer.dispose();
  103524. }
  103525. if (this._leftController) {
  103526. this._leftController.dispose();
  103527. }
  103528. if (this._rightController) {
  103529. this._rightController.dispose();
  103530. }
  103531. if (this._teleportationTarget) {
  103532. this._teleportationTarget.dispose();
  103533. }
  103534. this._floorMeshesCollection = [];
  103535. document.removeEventListener("keydown", this._onKeyDown);
  103536. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103537. window.removeEventListener("resize", this._onResize);
  103538. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  103539. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  103540. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  103541. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  103542. document.onmsfullscreenchange = null;
  103543. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  103544. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  103545. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  103546. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103547. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  103548. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  103549. this._scene.unregisterBeforeRender(this.beforeRender);
  103550. };
  103551. /**
  103552. * Gets the name of the VRExperienceHelper class
  103553. * @returns "VRExperienceHelper"
  103554. */
  103555. VRExperienceHelper.prototype.getClassName = function () {
  103556. return "VRExperienceHelper";
  103557. };
  103558. return VRExperienceHelper;
  103559. }());
  103560. BABYLON.VRExperienceHelper = VRExperienceHelper;
  103561. })(BABYLON || (BABYLON = {}));
  103562. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  103563. // Mainly based on these 2 articles :
  103564. // 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
  103565. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  103566. var BABYLON;
  103567. (function (BABYLON) {
  103568. /**
  103569. * Defines the potential axis of a Joystick
  103570. */
  103571. var JoystickAxis;
  103572. (function (JoystickAxis) {
  103573. /** X axis */
  103574. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  103575. /** Y axis */
  103576. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  103577. /** Z axis */
  103578. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  103579. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  103580. /**
  103581. * Class used to define virtual joystick (used in touch mode)
  103582. */
  103583. var VirtualJoystick = /** @class */ (function () {
  103584. /**
  103585. * Creates a new virtual joystick
  103586. * @param leftJoystick defines that the joystick is for left hand (false by default)
  103587. */
  103588. function VirtualJoystick(leftJoystick) {
  103589. var _this = this;
  103590. if (leftJoystick) {
  103591. this._leftJoystick = true;
  103592. }
  103593. else {
  103594. this._leftJoystick = false;
  103595. }
  103596. VirtualJoystick._globalJoystickIndex++;
  103597. // By default left & right arrow keys are moving the X
  103598. // and up & down keys are moving the Y
  103599. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  103600. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  103601. this.reverseLeftRight = false;
  103602. this.reverseUpDown = false;
  103603. // collections of pointers
  103604. this._touches = new BABYLON.StringDictionary();
  103605. this.deltaPosition = BABYLON.Vector3.Zero();
  103606. this._joystickSensibility = 25;
  103607. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  103608. this._onResize = function (evt) {
  103609. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  103610. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  103611. if (VirtualJoystick.vjCanvas) {
  103612. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  103613. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  103614. }
  103615. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  103616. };
  103617. // injecting a canvas element on top of the canvas 3D game
  103618. if (!VirtualJoystick.vjCanvas) {
  103619. window.addEventListener("resize", this._onResize, false);
  103620. VirtualJoystick.vjCanvas = document.createElement("canvas");
  103621. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  103622. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  103623. VirtualJoystick.vjCanvas.width = window.innerWidth;
  103624. VirtualJoystick.vjCanvas.height = window.innerHeight;
  103625. VirtualJoystick.vjCanvas.style.width = "100%";
  103626. VirtualJoystick.vjCanvas.style.height = "100%";
  103627. VirtualJoystick.vjCanvas.style.position = "absolute";
  103628. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  103629. VirtualJoystick.vjCanvas.style.top = "0px";
  103630. VirtualJoystick.vjCanvas.style.left = "0px";
  103631. VirtualJoystick.vjCanvas.style.zIndex = "5";
  103632. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  103633. // Support for jQuery PEP polyfill
  103634. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  103635. var context = VirtualJoystick.vjCanvas.getContext('2d');
  103636. if (!context) {
  103637. throw new Error("Unable to create canvas for virtual joystick");
  103638. }
  103639. VirtualJoystick.vjCanvasContext = context;
  103640. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  103641. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103642. document.body.appendChild(VirtualJoystick.vjCanvas);
  103643. }
  103644. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  103645. this.pressed = false;
  103646. // default joystick color
  103647. this._joystickColor = "cyan";
  103648. this._joystickPointerID = -1;
  103649. // current joystick position
  103650. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  103651. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  103652. // origin joystick position
  103653. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  103654. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  103655. this._onPointerDownHandlerRef = function (evt) {
  103656. _this._onPointerDown(evt);
  103657. };
  103658. this._onPointerMoveHandlerRef = function (evt) {
  103659. _this._onPointerMove(evt);
  103660. };
  103661. this._onPointerUpHandlerRef = function (evt) {
  103662. _this._onPointerUp(evt);
  103663. };
  103664. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  103665. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  103666. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  103667. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  103668. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  103669. evt.preventDefault(); // Disables system menu
  103670. }, false);
  103671. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103672. }
  103673. /**
  103674. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  103675. * @param newJoystickSensibility defines the new sensibility
  103676. */
  103677. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  103678. this._joystickSensibility = newJoystickSensibility;
  103679. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  103680. };
  103681. VirtualJoystick.prototype._onPointerDown = function (e) {
  103682. var positionOnScreenCondition;
  103683. e.preventDefault();
  103684. if (this._leftJoystick === true) {
  103685. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  103686. }
  103687. else {
  103688. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  103689. }
  103690. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  103691. // First contact will be dedicated to the virtual joystick
  103692. this._joystickPointerID = e.pointerId;
  103693. this._joystickPointerStartPos.x = e.clientX;
  103694. this._joystickPointerStartPos.y = e.clientY;
  103695. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  103696. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  103697. this._deltaJoystickVector.x = 0;
  103698. this._deltaJoystickVector.y = 0;
  103699. this.pressed = true;
  103700. this._touches.add(e.pointerId.toString(), e);
  103701. }
  103702. else {
  103703. // You can only trigger the action buttons with a joystick declared
  103704. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  103705. this._action();
  103706. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  103707. }
  103708. }
  103709. };
  103710. VirtualJoystick.prototype._onPointerMove = function (e) {
  103711. // If the current pointer is the one associated to the joystick (first touch contact)
  103712. if (this._joystickPointerID == e.pointerId) {
  103713. this._joystickPointerPos.x = e.clientX;
  103714. this._joystickPointerPos.y = e.clientY;
  103715. this._deltaJoystickVector = this._joystickPointerPos.clone();
  103716. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  103717. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  103718. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  103719. switch (this._axisTargetedByLeftAndRight) {
  103720. case JoystickAxis.X:
  103721. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  103722. break;
  103723. case JoystickAxis.Y:
  103724. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  103725. break;
  103726. case JoystickAxis.Z:
  103727. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  103728. break;
  103729. }
  103730. var directionUpDown = this.reverseUpDown ? 1 : -1;
  103731. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  103732. switch (this._axisTargetedByUpAndDown) {
  103733. case JoystickAxis.X:
  103734. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  103735. break;
  103736. case JoystickAxis.Y:
  103737. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  103738. break;
  103739. case JoystickAxis.Z:
  103740. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  103741. break;
  103742. }
  103743. }
  103744. else {
  103745. var data = this._touches.get(e.pointerId.toString());
  103746. if (data) {
  103747. data.x = e.clientX;
  103748. data.y = e.clientY;
  103749. }
  103750. }
  103751. };
  103752. VirtualJoystick.prototype._onPointerUp = function (e) {
  103753. if (this._joystickPointerID == e.pointerId) {
  103754. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  103755. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  103756. this._joystickPointerID = -1;
  103757. this.pressed = false;
  103758. }
  103759. else {
  103760. var touch = this._touches.get(e.pointerId.toString());
  103761. if (touch) {
  103762. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103763. }
  103764. }
  103765. this._deltaJoystickVector.x = 0;
  103766. this._deltaJoystickVector.y = 0;
  103767. this._touches.remove(e.pointerId.toString());
  103768. };
  103769. /**
  103770. * Change the color of the virtual joystick
  103771. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  103772. */
  103773. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  103774. this._joystickColor = newColor;
  103775. };
  103776. /**
  103777. * Defines a callback to call when the joystick is touched
  103778. * @param action defines the callback
  103779. */
  103780. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  103781. this._action = action;
  103782. };
  103783. /**
  103784. * Defines which axis you'd like to control for left & right
  103785. * @param axis defines the axis to use
  103786. */
  103787. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  103788. switch (axis) {
  103789. case JoystickAxis.X:
  103790. case JoystickAxis.Y:
  103791. case JoystickAxis.Z:
  103792. this._axisTargetedByLeftAndRight = axis;
  103793. break;
  103794. default:
  103795. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  103796. break;
  103797. }
  103798. };
  103799. /**
  103800. * Defines which axis you'd like to control for up & down
  103801. * @param axis defines the axis to use
  103802. */
  103803. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  103804. switch (axis) {
  103805. case JoystickAxis.X:
  103806. case JoystickAxis.Y:
  103807. case JoystickAxis.Z:
  103808. this._axisTargetedByUpAndDown = axis;
  103809. break;
  103810. default:
  103811. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  103812. break;
  103813. }
  103814. };
  103815. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  103816. var _this = this;
  103817. if (this.pressed) {
  103818. this._touches.forEach(function (key, touch) {
  103819. if (touch.pointerId === _this._joystickPointerID) {
  103820. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  103821. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  103822. VirtualJoystick.vjCanvasContext.beginPath();
  103823. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103824. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103825. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  103826. VirtualJoystick.vjCanvasContext.stroke();
  103827. VirtualJoystick.vjCanvasContext.closePath();
  103828. VirtualJoystick.vjCanvasContext.beginPath();
  103829. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103830. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103831. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  103832. VirtualJoystick.vjCanvasContext.stroke();
  103833. VirtualJoystick.vjCanvasContext.closePath();
  103834. VirtualJoystick.vjCanvasContext.beginPath();
  103835. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103836. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  103837. VirtualJoystick.vjCanvasContext.stroke();
  103838. VirtualJoystick.vjCanvasContext.closePath();
  103839. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  103840. }
  103841. else {
  103842. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103843. VirtualJoystick.vjCanvasContext.beginPath();
  103844. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  103845. VirtualJoystick.vjCanvasContext.beginPath();
  103846. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  103847. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103848. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  103849. VirtualJoystick.vjCanvasContext.stroke();
  103850. VirtualJoystick.vjCanvasContext.closePath();
  103851. touch.prevX = touch.x;
  103852. touch.prevY = touch.y;
  103853. }
  103854. ;
  103855. });
  103856. }
  103857. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103858. };
  103859. /**
  103860. * Release internal HTML canvas
  103861. */
  103862. VirtualJoystick.prototype.releaseCanvas = function () {
  103863. if (VirtualJoystick.vjCanvas) {
  103864. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  103865. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  103866. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  103867. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  103868. window.removeEventListener("resize", this._onResize);
  103869. document.body.removeChild(VirtualJoystick.vjCanvas);
  103870. VirtualJoystick.vjCanvas = null;
  103871. }
  103872. };
  103873. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  103874. VirtualJoystick._globalJoystickIndex = 0;
  103875. return VirtualJoystick;
  103876. }());
  103877. BABYLON.VirtualJoystick = VirtualJoystick;
  103878. })(BABYLON || (BABYLON = {}));
  103879. //# sourceMappingURL=babylon.virtualJoystick.js.map
  103880. var BABYLON;
  103881. (function (BABYLON) {
  103882. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  103883. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  103884. });
  103885. /**
  103886. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  103887. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103888. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103889. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103890. */
  103891. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  103892. __extends(VirtualJoysticksCamera, _super);
  103893. /**
  103894. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  103895. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103896. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103897. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103898. * @param name Define the name of the camera in the scene
  103899. * @param position Define the start position of the camera in the scene
  103900. * @param scene Define the scene the camera belongs to
  103901. */
  103902. function VirtualJoysticksCamera(name, position, scene) {
  103903. var _this = _super.call(this, name, position, scene) || this;
  103904. _this.inputs.addVirtualJoystick();
  103905. return _this;
  103906. }
  103907. /**
  103908. * Gets the current object class name.
  103909. * @return the class name
  103910. */
  103911. VirtualJoysticksCamera.prototype.getClassName = function () {
  103912. return "VirtualJoysticksCamera";
  103913. };
  103914. return VirtualJoysticksCamera;
  103915. }(BABYLON.FreeCamera));
  103916. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  103917. })(BABYLON || (BABYLON = {}));
  103918. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  103919. var BABYLON;
  103920. (function (BABYLON) {
  103921. /**
  103922. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  103923. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103924. */
  103925. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  103926. function FreeCameraVirtualJoystickInput() {
  103927. }
  103928. /**
  103929. * Gets the left stick of the virtual joystick.
  103930. * @returns The virtual Joystick
  103931. */
  103932. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  103933. return this._leftjoystick;
  103934. };
  103935. /**
  103936. * Gets the right stick of the virtual joystick.
  103937. * @returns The virtual Joystick
  103938. */
  103939. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  103940. return this._rightjoystick;
  103941. };
  103942. /**
  103943. * Update the current camera state depending on the inputs that have been used this frame.
  103944. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103945. */
  103946. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  103947. if (this._leftjoystick) {
  103948. var camera = this.camera;
  103949. var speed = camera._computeLocalCameraSpeed() * 50;
  103950. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  103951. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  103952. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  103953. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  103954. if (!this._leftjoystick.pressed) {
  103955. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  103956. }
  103957. if (!this._rightjoystick.pressed) {
  103958. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  103959. }
  103960. }
  103961. };
  103962. /**
  103963. * Attach the input controls to a specific dom element to get the input from.
  103964. * @param element Defines the element the controls should be listened from
  103965. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103966. */
  103967. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  103968. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  103969. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  103970. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  103971. this._leftjoystick.setJoystickSensibility(0.15);
  103972. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  103973. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  103974. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  103975. this._rightjoystick.reverseUpDown = true;
  103976. this._rightjoystick.setJoystickSensibility(0.05);
  103977. this._rightjoystick.setJoystickColor("yellow");
  103978. };
  103979. /**
  103980. * Detach the current controls from the specified dom element.
  103981. * @param element Defines the element to stop listening the inputs from
  103982. */
  103983. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  103984. this._leftjoystick.releaseCanvas();
  103985. this._rightjoystick.releaseCanvas();
  103986. };
  103987. /**
  103988. * Gets the class name of the current intput.
  103989. * @returns the class name
  103990. */
  103991. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  103992. return "FreeCameraVirtualJoystickInput";
  103993. };
  103994. /**
  103995. * Get the friendly name associated with the input class.
  103996. * @returns the input friendly name
  103997. */
  103998. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  103999. return "virtualJoystick";
  104000. };
  104001. return FreeCameraVirtualJoystickInput;
  104002. }());
  104003. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  104004. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  104005. })(BABYLON || (BABYLON = {}));
  104006. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  104007. var BABYLON;
  104008. (function (BABYLON) {
  104009. /**
  104010. * Class used to specify simplification options
  104011. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104012. */
  104013. var SimplificationSettings = /** @class */ (function () {
  104014. /**
  104015. * Creates a SimplificationSettings
  104016. * @param quality expected quality
  104017. * @param distance distance when this optimized version should be used
  104018. * @param optimizeMesh already optimized mesh
  104019. */
  104020. function SimplificationSettings(
  104021. /** expected quality */
  104022. quality,
  104023. /** distance when this optimized version should be used */
  104024. distance,
  104025. /** already optimized mesh */
  104026. optimizeMesh) {
  104027. this.quality = quality;
  104028. this.distance = distance;
  104029. this.optimizeMesh = optimizeMesh;
  104030. }
  104031. return SimplificationSettings;
  104032. }());
  104033. BABYLON.SimplificationSettings = SimplificationSettings;
  104034. /**
  104035. * Queue used to order the simplification tasks
  104036. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104037. */
  104038. var SimplificationQueue = /** @class */ (function () {
  104039. /**
  104040. * Creates a new queue
  104041. */
  104042. function SimplificationQueue() {
  104043. this.running = false;
  104044. this._simplificationArray = [];
  104045. }
  104046. /**
  104047. * Adds a new simplification task
  104048. * @param task defines a task to add
  104049. */
  104050. SimplificationQueue.prototype.addTask = function (task) {
  104051. this._simplificationArray.push(task);
  104052. };
  104053. /**
  104054. * Execute next task
  104055. */
  104056. SimplificationQueue.prototype.executeNext = function () {
  104057. var task = this._simplificationArray.pop();
  104058. if (task) {
  104059. this.running = true;
  104060. this.runSimplification(task);
  104061. }
  104062. else {
  104063. this.running = false;
  104064. }
  104065. };
  104066. /**
  104067. * Execute a simplification task
  104068. * @param task defines the task to run
  104069. */
  104070. SimplificationQueue.prototype.runSimplification = function (task) {
  104071. var _this = this;
  104072. if (task.parallelProcessing) {
  104073. //parallel simplifier
  104074. task.settings.forEach(function (setting) {
  104075. var simplifier = _this.getSimplifier(task);
  104076. simplifier.simplify(setting, function (newMesh) {
  104077. task.mesh.addLODLevel(setting.distance, newMesh);
  104078. newMesh.isVisible = true;
  104079. //check if it is the last
  104080. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104081. //all done, run the success callback.
  104082. task.successCallback();
  104083. }
  104084. _this.executeNext();
  104085. });
  104086. });
  104087. }
  104088. else {
  104089. //single simplifier.
  104090. var simplifier = this.getSimplifier(task);
  104091. var runDecimation = function (setting, callback) {
  104092. simplifier.simplify(setting, function (newMesh) {
  104093. task.mesh.addLODLevel(setting.distance, newMesh);
  104094. newMesh.isVisible = true;
  104095. //run the next quality level
  104096. callback();
  104097. });
  104098. };
  104099. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  104100. runDecimation(task.settings[loop.index], function () {
  104101. loop.executeNext();
  104102. });
  104103. }, function () {
  104104. //execution ended, run the success callback.
  104105. if (task.successCallback) {
  104106. task.successCallback();
  104107. }
  104108. _this.executeNext();
  104109. });
  104110. }
  104111. };
  104112. SimplificationQueue.prototype.getSimplifier = function (task) {
  104113. switch (task.simplificationType) {
  104114. case SimplificationType.QUADRATIC:
  104115. default:
  104116. return new QuadraticErrorSimplification(task.mesh);
  104117. }
  104118. };
  104119. return SimplificationQueue;
  104120. }());
  104121. BABYLON.SimplificationQueue = SimplificationQueue;
  104122. /**
  104123. * The implemented types of simplification
  104124. * At the moment only Quadratic Error Decimation is implemented
  104125. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104126. */
  104127. var SimplificationType;
  104128. (function (SimplificationType) {
  104129. /** Quadratic error decimation */
  104130. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  104131. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  104132. var DecimationTriangle = /** @class */ (function () {
  104133. function DecimationTriangle(vertices) {
  104134. this.vertices = vertices;
  104135. this.error = new Array(4);
  104136. this.deleted = false;
  104137. this.isDirty = false;
  104138. this.deletePending = false;
  104139. this.borderFactor = 0;
  104140. }
  104141. return DecimationTriangle;
  104142. }());
  104143. var DecimationVertex = /** @class */ (function () {
  104144. function DecimationVertex(position, id) {
  104145. this.position = position;
  104146. this.id = id;
  104147. this.isBorder = true;
  104148. this.q = new QuadraticMatrix();
  104149. this.triangleCount = 0;
  104150. this.triangleStart = 0;
  104151. this.originalOffsets = [];
  104152. }
  104153. DecimationVertex.prototype.updatePosition = function (newPosition) {
  104154. this.position.copyFrom(newPosition);
  104155. };
  104156. return DecimationVertex;
  104157. }());
  104158. var QuadraticMatrix = /** @class */ (function () {
  104159. function QuadraticMatrix(data) {
  104160. this.data = new Array(10);
  104161. for (var i = 0; i < 10; ++i) {
  104162. if (data && data[i]) {
  104163. this.data[i] = data[i];
  104164. }
  104165. else {
  104166. this.data[i] = 0;
  104167. }
  104168. }
  104169. }
  104170. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  104171. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  104172. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  104173. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  104174. return det;
  104175. };
  104176. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  104177. for (var i = 0; i < 10; ++i) {
  104178. this.data[i] += matrix.data[i];
  104179. }
  104180. };
  104181. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  104182. for (var i = 0; i < 10; ++i) {
  104183. this.data[i] += data[i];
  104184. }
  104185. };
  104186. QuadraticMatrix.prototype.add = function (matrix) {
  104187. var m = new QuadraticMatrix();
  104188. for (var i = 0; i < 10; ++i) {
  104189. m.data[i] = this.data[i] + matrix.data[i];
  104190. }
  104191. return m;
  104192. };
  104193. QuadraticMatrix.FromData = function (a, b, c, d) {
  104194. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  104195. };
  104196. //returning an array to avoid garbage collection
  104197. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  104198. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  104199. };
  104200. return QuadraticMatrix;
  104201. }());
  104202. var Reference = /** @class */ (function () {
  104203. function Reference(vertexId, triangleId) {
  104204. this.vertexId = vertexId;
  104205. this.triangleId = triangleId;
  104206. }
  104207. return Reference;
  104208. }());
  104209. /**
  104210. * An implementation of the Quadratic Error simplification algorithm.
  104211. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  104212. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  104213. * @author RaananW
  104214. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104215. */
  104216. var QuadraticErrorSimplification = /** @class */ (function () {
  104217. function QuadraticErrorSimplification(_mesh) {
  104218. this._mesh = _mesh;
  104219. this.syncIterations = 5000;
  104220. this.aggressiveness = 7;
  104221. this.decimationIterations = 100;
  104222. this.boundingBoxEpsilon = BABYLON.Epsilon;
  104223. }
  104224. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  104225. var _this = this;
  104226. this.initDecimatedMesh();
  104227. //iterating through the submeshes array, one after the other.
  104228. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  104229. _this.initWithMesh(loop.index, function () {
  104230. _this.runDecimation(settings, loop.index, function () {
  104231. loop.executeNext();
  104232. });
  104233. }, settings.optimizeMesh);
  104234. }, function () {
  104235. setTimeout(function () {
  104236. successCallback(_this._reconstructedMesh);
  104237. }, 0);
  104238. });
  104239. };
  104240. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  104241. var _this = this;
  104242. var targetCount = ~~(this.triangles.length * settings.quality);
  104243. var deletedTriangles = 0;
  104244. var triangleCount = this.triangles.length;
  104245. var iterationFunction = function (iteration, callback) {
  104246. setTimeout(function () {
  104247. if (iteration % 5 === 0) {
  104248. _this.updateMesh(iteration === 0);
  104249. }
  104250. for (var i = 0; i < _this.triangles.length; ++i) {
  104251. _this.triangles[i].isDirty = false;
  104252. }
  104253. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  104254. var trianglesIterator = function (i) {
  104255. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  104256. var t = _this.triangles[tIdx];
  104257. if (!t)
  104258. return;
  104259. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  104260. return;
  104261. }
  104262. for (var j = 0; j < 3; ++j) {
  104263. if (t.error[j] < threshold) {
  104264. var deleted0 = [];
  104265. var deleted1 = [];
  104266. var v0 = t.vertices[j];
  104267. var v1 = t.vertices[(j + 1) % 3];
  104268. if (v0.isBorder || v1.isBorder)
  104269. continue;
  104270. var p = BABYLON.Vector3.Zero();
  104271. var n = BABYLON.Vector3.Zero();
  104272. var uv = BABYLON.Vector2.Zero();
  104273. var color = new BABYLON.Color4(0, 0, 0, 1);
  104274. _this.calculateError(v0, v1, p, n, uv, color);
  104275. var delTr = new Array();
  104276. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  104277. continue;
  104278. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  104279. continue;
  104280. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  104281. continue;
  104282. var uniqueArray = new Array();
  104283. delTr.forEach(function (deletedT) {
  104284. if (uniqueArray.indexOf(deletedT) === -1) {
  104285. deletedT.deletePending = true;
  104286. uniqueArray.push(deletedT);
  104287. }
  104288. });
  104289. if (uniqueArray.length % 2 !== 0) {
  104290. continue;
  104291. }
  104292. v0.q = v1.q.add(v0.q);
  104293. v0.updatePosition(p);
  104294. var tStart = _this.references.length;
  104295. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  104296. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  104297. var tCount = _this.references.length - tStart;
  104298. if (tCount <= v0.triangleCount) {
  104299. if (tCount) {
  104300. for (var c = 0; c < tCount; c++) {
  104301. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  104302. }
  104303. }
  104304. }
  104305. else {
  104306. v0.triangleStart = tStart;
  104307. }
  104308. v0.triangleCount = tCount;
  104309. break;
  104310. }
  104311. }
  104312. };
  104313. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  104314. }, 0);
  104315. };
  104316. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  104317. if (triangleCount - deletedTriangles <= targetCount)
  104318. loop.breakLoop();
  104319. else {
  104320. iterationFunction(loop.index, function () {
  104321. loop.executeNext();
  104322. });
  104323. }
  104324. }, function () {
  104325. setTimeout(function () {
  104326. //reconstruct this part of the mesh
  104327. _this.reconstructMesh(submeshIndex);
  104328. successCallback();
  104329. }, 0);
  104330. });
  104331. };
  104332. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  104333. var _this = this;
  104334. this.vertices = [];
  104335. this.triangles = [];
  104336. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104337. var indices = this._mesh.getIndices();
  104338. var submesh = this._mesh.subMeshes[submeshIndex];
  104339. var findInVertices = function (positionToSearch) {
  104340. if (optimizeMesh) {
  104341. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  104342. if (_this.vertices[ii].position.equals(positionToSearch)) {
  104343. return _this.vertices[ii];
  104344. }
  104345. }
  104346. }
  104347. return null;
  104348. };
  104349. var vertexReferences = [];
  104350. var vertexInit = function (i) {
  104351. if (!positionData) {
  104352. return;
  104353. }
  104354. var offset = i + submesh.verticesStart;
  104355. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  104356. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  104357. vertex.originalOffsets.push(offset);
  104358. if (vertex.id === _this.vertices.length) {
  104359. _this.vertices.push(vertex);
  104360. }
  104361. vertexReferences.push(vertex.id);
  104362. };
  104363. //var totalVertices = mesh.getTotalVertices();
  104364. var totalVertices = submesh.verticesCount;
  104365. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  104366. var indicesInit = function (i) {
  104367. if (!indices) {
  104368. return;
  104369. }
  104370. var offset = (submesh.indexStart / 3) + i;
  104371. var pos = (offset * 3);
  104372. var i0 = indices[pos + 0];
  104373. var i1 = indices[pos + 1];
  104374. var i2 = indices[pos + 2];
  104375. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  104376. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  104377. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  104378. var triangle = new DecimationTriangle([v0, v1, v2]);
  104379. triangle.originalOffset = pos;
  104380. _this.triangles.push(triangle);
  104381. };
  104382. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  104383. _this.init(callback);
  104384. });
  104385. });
  104386. };
  104387. QuadraticErrorSimplification.prototype.init = function (callback) {
  104388. var _this = this;
  104389. var triangleInit1 = function (i) {
  104390. var t = _this.triangles[i];
  104391. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  104392. for (var j = 0; j < 3; j++) {
  104393. 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))));
  104394. }
  104395. };
  104396. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  104397. var triangleInit2 = function (i) {
  104398. var t = _this.triangles[i];
  104399. for (var j = 0; j < 3; ++j) {
  104400. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  104401. }
  104402. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  104403. };
  104404. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  104405. callback();
  104406. });
  104407. });
  104408. };
  104409. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  104410. var newTriangles = [];
  104411. var i;
  104412. for (i = 0; i < this.vertices.length; ++i) {
  104413. this.vertices[i].triangleCount = 0;
  104414. }
  104415. var t;
  104416. var j;
  104417. for (i = 0; i < this.triangles.length; ++i) {
  104418. if (!this.triangles[i].deleted) {
  104419. t = this.triangles[i];
  104420. for (j = 0; j < 3; ++j) {
  104421. t.vertices[j].triangleCount = 1;
  104422. }
  104423. newTriangles.push(t);
  104424. }
  104425. }
  104426. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  104427. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  104428. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  104429. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  104430. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  104431. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  104432. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  104433. var vertexCount = 0;
  104434. for (i = 0; i < this.vertices.length; ++i) {
  104435. var vertex = this.vertices[i];
  104436. vertex.id = vertexCount;
  104437. if (vertex.triangleCount) {
  104438. vertex.originalOffsets.forEach(function (originalOffset) {
  104439. if (!normalData) {
  104440. return;
  104441. }
  104442. newPositionData.push(vertex.position.x);
  104443. newPositionData.push(vertex.position.y);
  104444. newPositionData.push(vertex.position.z);
  104445. newNormalData.push(normalData[originalOffset * 3]);
  104446. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  104447. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  104448. if (uvs && uvs.length) {
  104449. newUVsData.push(uvs[(originalOffset * 2)]);
  104450. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  104451. }
  104452. else if (colorsData && colorsData.length) {
  104453. newColorsData.push(colorsData[(originalOffset * 4)]);
  104454. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  104455. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  104456. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  104457. }
  104458. ++vertexCount;
  104459. });
  104460. }
  104461. }
  104462. var startingIndex = this._reconstructedMesh.getTotalIndices();
  104463. var startingVertex = this._reconstructedMesh.getTotalVertices();
  104464. var submeshesArray = this._reconstructedMesh.subMeshes;
  104465. this._reconstructedMesh.subMeshes = [];
  104466. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  104467. var originalIndices = this._mesh.getIndices();
  104468. for (i = 0; i < newTriangles.length; ++i) {
  104469. t = newTriangles[i]; //now get the new referencing point for each vertex
  104470. [0, 1, 2].forEach(function (idx) {
  104471. var id = originalIndices[t.originalOffset + idx];
  104472. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  104473. if (offset < 0)
  104474. offset = 0;
  104475. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  104476. });
  104477. }
  104478. //overwriting the old vertex buffers and indices.
  104479. this._reconstructedMesh.setIndices(newIndicesArray);
  104480. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  104481. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  104482. if (newUVsData.length > 0)
  104483. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  104484. if (newColorsData.length > 0)
  104485. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  104486. //create submesh
  104487. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  104488. if (submeshIndex > 0) {
  104489. this._reconstructedMesh.subMeshes = [];
  104490. submeshesArray.forEach(function (submesh) {
  104491. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  104492. });
  104493. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  104494. }
  104495. };
  104496. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  104497. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  104498. this._reconstructedMesh.material = this._mesh.material;
  104499. this._reconstructedMesh.parent = this._mesh.parent;
  104500. this._reconstructedMesh.isVisible = false;
  104501. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  104502. };
  104503. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  104504. for (var i = 0; i < vertex1.triangleCount; ++i) {
  104505. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  104506. if (t.deleted)
  104507. continue;
  104508. var s = this.references[vertex1.triangleStart + i].vertexId;
  104509. var v1 = t.vertices[(s + 1) % 3];
  104510. var v2 = t.vertices[(s + 2) % 3];
  104511. if ((v1 === vertex2 || v2 === vertex2)) {
  104512. deletedArray[i] = true;
  104513. delTr.push(t);
  104514. continue;
  104515. }
  104516. var d1 = v1.position.subtract(point);
  104517. d1 = d1.normalize();
  104518. var d2 = v2.position.subtract(point);
  104519. d2 = d2.normalize();
  104520. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  104521. return true;
  104522. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  104523. deletedArray[i] = false;
  104524. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  104525. return true;
  104526. }
  104527. return false;
  104528. };
  104529. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  104530. var newDeleted = deletedTriangles;
  104531. for (var i = 0; i < vertex.triangleCount; ++i) {
  104532. var ref = this.references[vertex.triangleStart + i];
  104533. var t = this.triangles[ref.triangleId];
  104534. if (t.deleted)
  104535. continue;
  104536. if (deletedArray[i] && t.deletePending) {
  104537. t.deleted = true;
  104538. newDeleted++;
  104539. continue;
  104540. }
  104541. t.vertices[ref.vertexId] = origVertex;
  104542. t.isDirty = true;
  104543. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  104544. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  104545. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  104546. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  104547. this.references.push(ref);
  104548. }
  104549. return newDeleted;
  104550. };
  104551. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  104552. for (var i = 0; i < this.vertices.length; ++i) {
  104553. var vCount = [];
  104554. var vId = [];
  104555. var v = this.vertices[i];
  104556. var j;
  104557. for (j = 0; j < v.triangleCount; ++j) {
  104558. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  104559. for (var ii = 0; ii < 3; ii++) {
  104560. var ofs = 0;
  104561. var vv = triangle.vertices[ii];
  104562. while (ofs < vCount.length) {
  104563. if (vId[ofs] === vv.id)
  104564. break;
  104565. ++ofs;
  104566. }
  104567. if (ofs === vCount.length) {
  104568. vCount.push(1);
  104569. vId.push(vv.id);
  104570. }
  104571. else {
  104572. vCount[ofs]++;
  104573. }
  104574. }
  104575. }
  104576. for (j = 0; j < vCount.length; ++j) {
  104577. if (vCount[j] === 1) {
  104578. this.vertices[vId[j]].isBorder = true;
  104579. }
  104580. else {
  104581. this.vertices[vId[j]].isBorder = false;
  104582. }
  104583. }
  104584. }
  104585. };
  104586. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  104587. if (identifyBorders === void 0) { identifyBorders = false; }
  104588. var i;
  104589. if (!identifyBorders) {
  104590. var newTrianglesVector = [];
  104591. for (i = 0; i < this.triangles.length; ++i) {
  104592. if (!this.triangles[i].deleted) {
  104593. newTrianglesVector.push(this.triangles[i]);
  104594. }
  104595. }
  104596. this.triangles = newTrianglesVector;
  104597. }
  104598. for (i = 0; i < this.vertices.length; ++i) {
  104599. this.vertices[i].triangleCount = 0;
  104600. this.vertices[i].triangleStart = 0;
  104601. }
  104602. var t;
  104603. var j;
  104604. var v;
  104605. for (i = 0; i < this.triangles.length; ++i) {
  104606. t = this.triangles[i];
  104607. for (j = 0; j < 3; ++j) {
  104608. v = t.vertices[j];
  104609. v.triangleCount++;
  104610. }
  104611. }
  104612. var tStart = 0;
  104613. for (i = 0; i < this.vertices.length; ++i) {
  104614. this.vertices[i].triangleStart = tStart;
  104615. tStart += this.vertices[i].triangleCount;
  104616. this.vertices[i].triangleCount = 0;
  104617. }
  104618. var newReferences = new Array(this.triangles.length * 3);
  104619. for (i = 0; i < this.triangles.length; ++i) {
  104620. t = this.triangles[i];
  104621. for (j = 0; j < 3; ++j) {
  104622. v = t.vertices[j];
  104623. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  104624. v.triangleCount++;
  104625. }
  104626. }
  104627. this.references = newReferences;
  104628. if (identifyBorders) {
  104629. this.identifyBorder();
  104630. }
  104631. };
  104632. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  104633. var x = point.x;
  104634. var y = point.y;
  104635. var z = point.z;
  104636. 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
  104637. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  104638. };
  104639. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  104640. var q = vertex1.q.add(vertex2.q);
  104641. var border = vertex1.isBorder && vertex2.isBorder;
  104642. var error = 0;
  104643. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  104644. if (qDet !== 0 && !border) {
  104645. if (!pointResult) {
  104646. pointResult = BABYLON.Vector3.Zero();
  104647. }
  104648. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  104649. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  104650. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  104651. error = this.vertexError(q, pointResult);
  104652. }
  104653. else {
  104654. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  104655. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  104656. var error1 = this.vertexError(q, vertex1.position);
  104657. var error2 = this.vertexError(q, vertex2.position);
  104658. var error3 = this.vertexError(q, p3);
  104659. error = Math.min(error1, error2, error3);
  104660. if (error === error1) {
  104661. if (pointResult) {
  104662. pointResult.copyFrom(vertex1.position);
  104663. }
  104664. }
  104665. else if (error === error2) {
  104666. if (pointResult) {
  104667. pointResult.copyFrom(vertex2.position);
  104668. }
  104669. }
  104670. else {
  104671. if (pointResult) {
  104672. pointResult.copyFrom(p3);
  104673. }
  104674. }
  104675. }
  104676. return error;
  104677. };
  104678. return QuadraticErrorSimplification;
  104679. }());
  104680. })(BABYLON || (BABYLON = {}));
  104681. //# sourceMappingURL=babylon.meshSimplification.js.map
  104682. var BABYLON;
  104683. (function (BABYLON) {
  104684. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  104685. get: function () {
  104686. if (!this._simplificationQueue) {
  104687. this._simplificationQueue = new BABYLON.SimplificationQueue();
  104688. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  104689. if (!component) {
  104690. component = new SimplicationQueueSceneComponent(this);
  104691. this._addComponent(component);
  104692. }
  104693. }
  104694. return this._simplificationQueue;
  104695. },
  104696. set: function (value) {
  104697. this._simplificationQueue = value;
  104698. },
  104699. enumerable: true,
  104700. configurable: true
  104701. });
  104702. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  104703. if (parallelProcessing === void 0) { parallelProcessing = true; }
  104704. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  104705. this.getScene().simplificationQueue.addTask({
  104706. settings: settings,
  104707. parallelProcessing: parallelProcessing,
  104708. mesh: this,
  104709. simplificationType: simplificationType,
  104710. successCallback: successCallback
  104711. });
  104712. return this;
  104713. };
  104714. /**
  104715. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  104716. * created in a scene
  104717. */
  104718. var SimplicationQueueSceneComponent = /** @class */ (function () {
  104719. /**
  104720. * Creates a new instance of the component for the given scene
  104721. * @param scene Defines the scene to register the component in
  104722. */
  104723. function SimplicationQueueSceneComponent(scene) {
  104724. /**
  104725. * The component name helpfull to identify the component in the list of scene components.
  104726. */
  104727. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  104728. this.scene = scene;
  104729. }
  104730. /**
  104731. * Registers the component in a given scene
  104732. */
  104733. SimplicationQueueSceneComponent.prototype.register = function () {
  104734. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  104735. };
  104736. /**
  104737. * Rebuilds the elements related to this component in case of
  104738. * context lost for instance.
  104739. */
  104740. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  104741. // Nothing to do for this component
  104742. };
  104743. /**
  104744. * Disposes the component and the associated ressources
  104745. */
  104746. SimplicationQueueSceneComponent.prototype.dispose = function () {
  104747. // Nothing to do for this component
  104748. };
  104749. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  104750. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  104751. this.scene._simplificationQueue.executeNext();
  104752. }
  104753. };
  104754. return SimplicationQueueSceneComponent;
  104755. }());
  104756. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  104757. })(BABYLON || (BABYLON = {}));
  104758. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  104759. var BABYLON;
  104760. (function (BABYLON) {
  104761. /**
  104762. * Class used to represent a specific level of detail of a mesh
  104763. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  104764. */
  104765. var MeshLODLevel = /** @class */ (function () {
  104766. /**
  104767. * Creates a new LOD level
  104768. * @param distance defines the distance where this level should star being displayed
  104769. * @param mesh defines the mesh to use to render this level
  104770. */
  104771. function MeshLODLevel(
  104772. /** Defines the distance where this level should star being displayed */
  104773. distance,
  104774. /** Defines the mesh to use to render this level */
  104775. mesh) {
  104776. this.distance = distance;
  104777. this.mesh = mesh;
  104778. }
  104779. return MeshLODLevel;
  104780. }());
  104781. BABYLON.MeshLODLevel = MeshLODLevel;
  104782. })(BABYLON || (BABYLON = {}));
  104783. //# sourceMappingURL=babylon.meshLODLevel.js.map
  104784. var BABYLON;
  104785. (function (BABYLON) {
  104786. /**
  104787. * Defines the root class used to create scene optimization to use with SceneOptimizer
  104788. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104789. */
  104790. var SceneOptimization = /** @class */ (function () {
  104791. /**
  104792. * Creates the SceneOptimization object
  104793. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104794. * @param desc defines the description associated with the optimization
  104795. */
  104796. function SceneOptimization(
  104797. /**
  104798. * Defines the priority of this optimization (0 by default which means first in the list)
  104799. */
  104800. priority) {
  104801. if (priority === void 0) { priority = 0; }
  104802. this.priority = priority;
  104803. }
  104804. /**
  104805. * Gets a string describing the action executed by the current optimization
  104806. * @returns description string
  104807. */
  104808. SceneOptimization.prototype.getDescription = function () {
  104809. return "";
  104810. };
  104811. /**
  104812. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104813. * @param scene defines the current scene where to apply this optimization
  104814. * @param optimizer defines the current optimizer
  104815. * @returns true if everything that can be done was applied
  104816. */
  104817. SceneOptimization.prototype.apply = function (scene, optimizer) {
  104818. return true;
  104819. };
  104820. ;
  104821. return SceneOptimization;
  104822. }());
  104823. BABYLON.SceneOptimization = SceneOptimization;
  104824. /**
  104825. * Defines an optimization used to reduce the size of render target textures
  104826. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104827. */
  104828. var TextureOptimization = /** @class */ (function (_super) {
  104829. __extends(TextureOptimization, _super);
  104830. /**
  104831. * Creates the TextureOptimization object
  104832. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104833. * @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
  104834. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104835. */
  104836. function TextureOptimization(
  104837. /**
  104838. * Defines the priority of this optimization (0 by default which means first in the list)
  104839. */
  104840. priority,
  104841. /**
  104842. * 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
  104843. */
  104844. maximumSize,
  104845. /**
  104846. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104847. */
  104848. step) {
  104849. if (priority === void 0) { priority = 0; }
  104850. if (maximumSize === void 0) { maximumSize = 1024; }
  104851. if (step === void 0) { step = 0.5; }
  104852. var _this = _super.call(this, priority) || this;
  104853. _this.priority = priority;
  104854. _this.maximumSize = maximumSize;
  104855. _this.step = step;
  104856. return _this;
  104857. }
  104858. /**
  104859. * Gets a string describing the action executed by the current optimization
  104860. * @returns description string
  104861. */
  104862. TextureOptimization.prototype.getDescription = function () {
  104863. return "Reducing render target texture size to " + this.maximumSize;
  104864. };
  104865. /**
  104866. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104867. * @param scene defines the current scene where to apply this optimization
  104868. * @param optimizer defines the current optimizer
  104869. * @returns true if everything that can be done was applied
  104870. */
  104871. TextureOptimization.prototype.apply = function (scene, optimizer) {
  104872. var allDone = true;
  104873. for (var index = 0; index < scene.textures.length; index++) {
  104874. var texture = scene.textures[index];
  104875. if (!texture.canRescale || texture.getContext) {
  104876. continue;
  104877. }
  104878. var currentSize = texture.getSize();
  104879. var maxDimension = Math.max(currentSize.width, currentSize.height);
  104880. if (maxDimension > this.maximumSize) {
  104881. texture.scale(this.step);
  104882. allDone = false;
  104883. }
  104884. }
  104885. return allDone;
  104886. };
  104887. return TextureOptimization;
  104888. }(SceneOptimization));
  104889. BABYLON.TextureOptimization = TextureOptimization;
  104890. /**
  104891. * Defines an optimization used to increase or decrease the rendering resolution
  104892. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104893. */
  104894. var HardwareScalingOptimization = /** @class */ (function (_super) {
  104895. __extends(HardwareScalingOptimization, _super);
  104896. /**
  104897. * Creates the HardwareScalingOptimization object
  104898. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104899. * @param maximumScale defines the maximum scale to use (2 by default)
  104900. * @param step defines the step to use between two passes (0.5 by default)
  104901. */
  104902. function HardwareScalingOptimization(
  104903. /**
  104904. * Defines the priority of this optimization (0 by default which means first in the list)
  104905. */
  104906. priority,
  104907. /**
  104908. * Defines the maximum scale to use (2 by default)
  104909. */
  104910. maximumScale,
  104911. /**
  104912. * Defines the step to use between two passes (0.5 by default)
  104913. */
  104914. step) {
  104915. if (priority === void 0) { priority = 0; }
  104916. if (maximumScale === void 0) { maximumScale = 2; }
  104917. if (step === void 0) { step = 0.25; }
  104918. var _this = _super.call(this, priority) || this;
  104919. _this.priority = priority;
  104920. _this.maximumScale = maximumScale;
  104921. _this.step = step;
  104922. _this._currentScale = -1;
  104923. _this._directionOffset = 1;
  104924. return _this;
  104925. }
  104926. /**
  104927. * Gets a string describing the action executed by the current optimization
  104928. * @return description string
  104929. */
  104930. HardwareScalingOptimization.prototype.getDescription = function () {
  104931. return "Setting hardware scaling level to " + this._currentScale;
  104932. };
  104933. /**
  104934. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104935. * @param scene defines the current scene where to apply this optimization
  104936. * @param optimizer defines the current optimizer
  104937. * @returns true if everything that can be done was applied
  104938. */
  104939. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  104940. if (this._currentScale === -1) {
  104941. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  104942. if (this._currentScale > this.maximumScale) {
  104943. this._directionOffset = -1;
  104944. }
  104945. }
  104946. this._currentScale += this._directionOffset * this.step;
  104947. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  104948. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  104949. };
  104950. ;
  104951. return HardwareScalingOptimization;
  104952. }(SceneOptimization));
  104953. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  104954. /**
  104955. * Defines an optimization used to remove shadows
  104956. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104957. */
  104958. var ShadowsOptimization = /** @class */ (function (_super) {
  104959. __extends(ShadowsOptimization, _super);
  104960. function ShadowsOptimization() {
  104961. return _super !== null && _super.apply(this, arguments) || this;
  104962. }
  104963. /**
  104964. * Gets a string describing the action executed by the current optimization
  104965. * @return description string
  104966. */
  104967. ShadowsOptimization.prototype.getDescription = function () {
  104968. return "Turning shadows on/off";
  104969. };
  104970. /**
  104971. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104972. * @param scene defines the current scene where to apply this optimization
  104973. * @param optimizer defines the current optimizer
  104974. * @returns true if everything that can be done was applied
  104975. */
  104976. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  104977. scene.shadowsEnabled = optimizer.isInImprovementMode;
  104978. return true;
  104979. };
  104980. ;
  104981. return ShadowsOptimization;
  104982. }(SceneOptimization));
  104983. BABYLON.ShadowsOptimization = ShadowsOptimization;
  104984. /**
  104985. * Defines an optimization used to turn post-processes off
  104986. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104987. */
  104988. var PostProcessesOptimization = /** @class */ (function (_super) {
  104989. __extends(PostProcessesOptimization, _super);
  104990. function PostProcessesOptimization() {
  104991. return _super !== null && _super.apply(this, arguments) || this;
  104992. }
  104993. /**
  104994. * Gets a string describing the action executed by the current optimization
  104995. * @return description string
  104996. */
  104997. PostProcessesOptimization.prototype.getDescription = function () {
  104998. return "Turning post-processes on/off";
  104999. };
  105000. /**
  105001. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105002. * @param scene defines the current scene where to apply this optimization
  105003. * @param optimizer defines the current optimizer
  105004. * @returns true if everything that can be done was applied
  105005. */
  105006. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  105007. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  105008. return true;
  105009. };
  105010. ;
  105011. return PostProcessesOptimization;
  105012. }(SceneOptimization));
  105013. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  105014. /**
  105015. * Defines an optimization used to turn lens flares off
  105016. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105017. */
  105018. var LensFlaresOptimization = /** @class */ (function (_super) {
  105019. __extends(LensFlaresOptimization, _super);
  105020. function LensFlaresOptimization() {
  105021. return _super !== null && _super.apply(this, arguments) || this;
  105022. }
  105023. /**
  105024. * Gets a string describing the action executed by the current optimization
  105025. * @return description string
  105026. */
  105027. LensFlaresOptimization.prototype.getDescription = function () {
  105028. return "Turning lens flares on/off";
  105029. };
  105030. /**
  105031. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105032. * @param scene defines the current scene where to apply this optimization
  105033. * @param optimizer defines the current optimizer
  105034. * @returns true if everything that can be done was applied
  105035. */
  105036. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105037. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105038. return true;
  105039. };
  105040. ;
  105041. return LensFlaresOptimization;
  105042. }(SceneOptimization));
  105043. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105044. /**
  105045. * Defines an optimization based on user defined callback.
  105046. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105047. */
  105048. var CustomOptimization = /** @class */ (function (_super) {
  105049. __extends(CustomOptimization, _super);
  105050. function CustomOptimization() {
  105051. return _super !== null && _super.apply(this, arguments) || this;
  105052. }
  105053. /**
  105054. * Gets a string describing the action executed by the current optimization
  105055. * @returns description string
  105056. */
  105057. CustomOptimization.prototype.getDescription = function () {
  105058. if (this.onGetDescription) {
  105059. return this.onGetDescription();
  105060. }
  105061. return "Running user defined callback";
  105062. };
  105063. /**
  105064. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105065. * @param scene defines the current scene where to apply this optimization
  105066. * @param optimizer defines the current optimizer
  105067. * @returns true if everything that can be done was applied
  105068. */
  105069. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105070. if (this.onApply) {
  105071. return this.onApply(scene, optimizer);
  105072. }
  105073. return true;
  105074. };
  105075. ;
  105076. return CustomOptimization;
  105077. }(SceneOptimization));
  105078. BABYLON.CustomOptimization = CustomOptimization;
  105079. /**
  105080. * Defines an optimization used to turn particles off
  105081. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105082. */
  105083. var ParticlesOptimization = /** @class */ (function (_super) {
  105084. __extends(ParticlesOptimization, _super);
  105085. function ParticlesOptimization() {
  105086. return _super !== null && _super.apply(this, arguments) || this;
  105087. }
  105088. /**
  105089. * Gets a string describing the action executed by the current optimization
  105090. * @return description string
  105091. */
  105092. ParticlesOptimization.prototype.getDescription = function () {
  105093. return "Turning particles on/off";
  105094. };
  105095. /**
  105096. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105097. * @param scene defines the current scene where to apply this optimization
  105098. * @param optimizer defines the current optimizer
  105099. * @returns true if everything that can be done was applied
  105100. */
  105101. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  105102. scene.particlesEnabled = optimizer.isInImprovementMode;
  105103. return true;
  105104. };
  105105. ;
  105106. return ParticlesOptimization;
  105107. }(SceneOptimization));
  105108. BABYLON.ParticlesOptimization = ParticlesOptimization;
  105109. /**
  105110. * Defines an optimization used to turn render targets off
  105111. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105112. */
  105113. var RenderTargetsOptimization = /** @class */ (function (_super) {
  105114. __extends(RenderTargetsOptimization, _super);
  105115. function RenderTargetsOptimization() {
  105116. return _super !== null && _super.apply(this, arguments) || this;
  105117. }
  105118. /**
  105119. * Gets a string describing the action executed by the current optimization
  105120. * @return description string
  105121. */
  105122. RenderTargetsOptimization.prototype.getDescription = function () {
  105123. return "Turning render targets off";
  105124. };
  105125. /**
  105126. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105127. * @param scene defines the current scene where to apply this optimization
  105128. * @param optimizer defines the current optimizer
  105129. * @returns true if everything that can be done was applied
  105130. */
  105131. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  105132. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  105133. return true;
  105134. };
  105135. ;
  105136. return RenderTargetsOptimization;
  105137. }(SceneOptimization));
  105138. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  105139. /**
  105140. * Defines an optimization used to merge meshes with compatible materials
  105141. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105142. */
  105143. var MergeMeshesOptimization = /** @class */ (function (_super) {
  105144. __extends(MergeMeshesOptimization, _super);
  105145. function MergeMeshesOptimization() {
  105146. var _this = _super !== null && _super.apply(this, arguments) || this;
  105147. _this._canBeMerged = function (abstractMesh) {
  105148. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  105149. return false;
  105150. }
  105151. var mesh = abstractMesh;
  105152. if (mesh.isDisposed()) {
  105153. return false;
  105154. }
  105155. if (!mesh.isVisible || !mesh.isEnabled()) {
  105156. return false;
  105157. }
  105158. if (mesh.instances.length > 0) {
  105159. return false;
  105160. }
  105161. if (mesh.skeleton || mesh.hasLODLevels) {
  105162. return false;
  105163. }
  105164. return true;
  105165. };
  105166. return _this;
  105167. }
  105168. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  105169. /**
  105170. * Gets or sets a boolean which defines if optimization octree has to be updated
  105171. */
  105172. get: function () {
  105173. return MergeMeshesOptimization._UpdateSelectionTree;
  105174. },
  105175. /**
  105176. * Gets or sets a boolean which defines if optimization octree has to be updated
  105177. */
  105178. set: function (value) {
  105179. MergeMeshesOptimization._UpdateSelectionTree = value;
  105180. },
  105181. enumerable: true,
  105182. configurable: true
  105183. });
  105184. /**
  105185. * Gets a string describing the action executed by the current optimization
  105186. * @return description string
  105187. */
  105188. MergeMeshesOptimization.prototype.getDescription = function () {
  105189. return "Merging similar meshes together";
  105190. };
  105191. /**
  105192. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105193. * @param scene defines the current scene where to apply this optimization
  105194. * @param optimizer defines the current optimizer
  105195. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  105196. * @returns true if everything that can be done was applied
  105197. */
  105198. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  105199. var globalPool = scene.meshes.slice(0);
  105200. var globalLength = globalPool.length;
  105201. for (var index = 0; index < globalLength; index++) {
  105202. var currentPool = new Array();
  105203. var current = globalPool[index];
  105204. // Checks
  105205. if (!this._canBeMerged(current)) {
  105206. continue;
  105207. }
  105208. currentPool.push(current);
  105209. // Find compatible meshes
  105210. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  105211. var otherMesh = globalPool[subIndex];
  105212. if (!this._canBeMerged(otherMesh)) {
  105213. continue;
  105214. }
  105215. if (otherMesh.material !== current.material) {
  105216. continue;
  105217. }
  105218. if (otherMesh.checkCollisions !== current.checkCollisions) {
  105219. continue;
  105220. }
  105221. currentPool.push(otherMesh);
  105222. globalLength--;
  105223. globalPool.splice(subIndex, 1);
  105224. subIndex--;
  105225. }
  105226. if (currentPool.length < 2) {
  105227. continue;
  105228. }
  105229. // Merge meshes
  105230. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  105231. }
  105232. // Call the octree system optimization if it is defined.
  105233. var sceneAsAny = scene;
  105234. if (sceneAsAny.createOrUpdateSelectionOctree) {
  105235. if (updateSelectionTree != undefined) {
  105236. if (updateSelectionTree) {
  105237. sceneAsAny.createOrUpdateSelectionOctree();
  105238. }
  105239. }
  105240. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  105241. sceneAsAny.createOrUpdateSelectionOctree();
  105242. }
  105243. }
  105244. return true;
  105245. };
  105246. ;
  105247. MergeMeshesOptimization._UpdateSelectionTree = false;
  105248. return MergeMeshesOptimization;
  105249. }(SceneOptimization));
  105250. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  105251. /**
  105252. * Defines a list of options used by SceneOptimizer
  105253. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105254. */
  105255. var SceneOptimizerOptions = /** @class */ (function () {
  105256. /**
  105257. * Creates a new list of options used by SceneOptimizer
  105258. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  105259. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  105260. */
  105261. function SceneOptimizerOptions(
  105262. /**
  105263. * Defines the target frame rate to reach (60 by default)
  105264. */
  105265. targetFrameRate,
  105266. /**
  105267. * Defines the interval between two checkes (2000ms by default)
  105268. */
  105269. trackerDuration) {
  105270. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  105271. if (trackerDuration === void 0) { trackerDuration = 2000; }
  105272. this.targetFrameRate = targetFrameRate;
  105273. this.trackerDuration = trackerDuration;
  105274. /**
  105275. * Gets the list of optimizations to apply
  105276. */
  105277. this.optimizations = new Array();
  105278. }
  105279. /**
  105280. * Add a new optimization
  105281. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  105282. * @returns the current SceneOptimizerOptions
  105283. */
  105284. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  105285. this.optimizations.push(optimization);
  105286. return this;
  105287. };
  105288. /**
  105289. * Add a new custom optimization
  105290. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  105291. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  105292. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105293. * @returns the current SceneOptimizerOptions
  105294. */
  105295. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  105296. if (priority === void 0) { priority = 0; }
  105297. var optimization = new CustomOptimization(priority);
  105298. optimization.onApply = onApply;
  105299. optimization.onGetDescription = onGetDescription;
  105300. this.optimizations.push(optimization);
  105301. return this;
  105302. };
  105303. /**
  105304. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  105305. * @param targetFrameRate defines the target frame rate (60 by default)
  105306. * @returns a SceneOptimizerOptions object
  105307. */
  105308. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  105309. var result = new SceneOptimizerOptions(targetFrameRate);
  105310. var priority = 0;
  105311. result.addOptimization(new MergeMeshesOptimization(priority));
  105312. result.addOptimization(new ShadowsOptimization(priority));
  105313. result.addOptimization(new LensFlaresOptimization(priority));
  105314. // Next priority
  105315. priority++;
  105316. result.addOptimization(new PostProcessesOptimization(priority));
  105317. result.addOptimization(new ParticlesOptimization(priority));
  105318. // Next priority
  105319. priority++;
  105320. result.addOptimization(new TextureOptimization(priority, 1024));
  105321. return result;
  105322. };
  105323. /**
  105324. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  105325. * @param targetFrameRate defines the target frame rate (60 by default)
  105326. * @returns a SceneOptimizerOptions object
  105327. */
  105328. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  105329. var result = new SceneOptimizerOptions(targetFrameRate);
  105330. var priority = 0;
  105331. result.addOptimization(new MergeMeshesOptimization(priority));
  105332. result.addOptimization(new ShadowsOptimization(priority));
  105333. result.addOptimization(new LensFlaresOptimization(priority));
  105334. // Next priority
  105335. priority++;
  105336. result.addOptimization(new PostProcessesOptimization(priority));
  105337. result.addOptimization(new ParticlesOptimization(priority));
  105338. // Next priority
  105339. priority++;
  105340. result.addOptimization(new TextureOptimization(priority, 512));
  105341. // Next priority
  105342. priority++;
  105343. result.addOptimization(new RenderTargetsOptimization(priority));
  105344. // Next priority
  105345. priority++;
  105346. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  105347. return result;
  105348. };
  105349. /**
  105350. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  105351. * @param targetFrameRate defines the target frame rate (60 by default)
  105352. * @returns a SceneOptimizerOptions object
  105353. */
  105354. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  105355. var result = new SceneOptimizerOptions(targetFrameRate);
  105356. var priority = 0;
  105357. result.addOptimization(new MergeMeshesOptimization(priority));
  105358. result.addOptimization(new ShadowsOptimization(priority));
  105359. result.addOptimization(new LensFlaresOptimization(priority));
  105360. // Next priority
  105361. priority++;
  105362. result.addOptimization(new PostProcessesOptimization(priority));
  105363. result.addOptimization(new ParticlesOptimization(priority));
  105364. // Next priority
  105365. priority++;
  105366. result.addOptimization(new TextureOptimization(priority, 256));
  105367. // Next priority
  105368. priority++;
  105369. result.addOptimization(new RenderTargetsOptimization(priority));
  105370. // Next priority
  105371. priority++;
  105372. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  105373. return result;
  105374. };
  105375. return SceneOptimizerOptions;
  105376. }());
  105377. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  105378. /**
  105379. * Class used to run optimizations in order to reach a target frame rate
  105380. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105381. */
  105382. var SceneOptimizer = /** @class */ (function () {
  105383. /**
  105384. * Creates a new SceneOptimizer
  105385. * @param scene defines the scene to work on
  105386. * @param options defines the options to use with the SceneOptimizer
  105387. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  105388. * @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)
  105389. */
  105390. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  105391. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  105392. if (improvementMode === void 0) { improvementMode = false; }
  105393. var _this = this;
  105394. this._isRunning = false;
  105395. this._currentPriorityLevel = 0;
  105396. this._targetFrameRate = 60;
  105397. this._trackerDuration = 2000;
  105398. this._currentFrameRate = 0;
  105399. this._improvementMode = false;
  105400. /**
  105401. * Defines an observable called when the optimizer reaches the target frame rate
  105402. */
  105403. this.onSuccessObservable = new BABYLON.Observable();
  105404. /**
  105405. * Defines an observable called when the optimizer enables an optimization
  105406. */
  105407. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  105408. /**
  105409. * Defines an observable called when the optimizer is not able to reach the target frame rate
  105410. */
  105411. this.onFailureObservable = new BABYLON.Observable();
  105412. if (!options) {
  105413. this._options = new SceneOptimizerOptions();
  105414. }
  105415. else {
  105416. this._options = options;
  105417. }
  105418. if (this._options.targetFrameRate) {
  105419. this._targetFrameRate = this._options.targetFrameRate;
  105420. }
  105421. if (this._options.trackerDuration) {
  105422. this._trackerDuration = this._options.trackerDuration;
  105423. }
  105424. if (autoGeneratePriorities) {
  105425. var priority = 0;
  105426. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  105427. var optim = _a[_i];
  105428. optim.priority = priority++;
  105429. }
  105430. }
  105431. this._improvementMode = improvementMode;
  105432. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105433. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  105434. _this._sceneDisposeObserver = null;
  105435. _this.dispose();
  105436. });
  105437. }
  105438. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  105439. /**
  105440. * Gets a boolean indicating if the optimizer is in improvement mode
  105441. */
  105442. get: function () {
  105443. return this._improvementMode;
  105444. },
  105445. enumerable: true,
  105446. configurable: true
  105447. });
  105448. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  105449. /**
  105450. * Gets the current priority level (0 at start)
  105451. */
  105452. get: function () {
  105453. return this._currentPriorityLevel;
  105454. },
  105455. enumerable: true,
  105456. configurable: true
  105457. });
  105458. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  105459. /**
  105460. * Gets the current frame rate checked by the SceneOptimizer
  105461. */
  105462. get: function () {
  105463. return this._currentFrameRate;
  105464. },
  105465. enumerable: true,
  105466. configurable: true
  105467. });
  105468. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  105469. /**
  105470. * Gets or sets the current target frame rate (60 by default)
  105471. */
  105472. get: function () {
  105473. return this._targetFrameRate;
  105474. },
  105475. /**
  105476. * Gets or sets the current target frame rate (60 by default)
  105477. */
  105478. set: function (value) {
  105479. this._targetFrameRate = value;
  105480. },
  105481. enumerable: true,
  105482. configurable: true
  105483. });
  105484. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  105485. /**
  105486. * Gets or sets the current interval between two checks (every 2000ms by default)
  105487. */
  105488. get: function () {
  105489. return this._trackerDuration;
  105490. },
  105491. /**
  105492. * Gets or sets the current interval between two checks (every 2000ms by default)
  105493. */
  105494. set: function (value) {
  105495. this._trackerDuration = value;
  105496. },
  105497. enumerable: true,
  105498. configurable: true
  105499. });
  105500. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  105501. /**
  105502. * Gets the list of active optimizations
  105503. */
  105504. get: function () {
  105505. return this._options.optimizations;
  105506. },
  105507. enumerable: true,
  105508. configurable: true
  105509. });
  105510. /**
  105511. * Stops the current optimizer
  105512. */
  105513. SceneOptimizer.prototype.stop = function () {
  105514. this._isRunning = false;
  105515. };
  105516. /**
  105517. * Reset the optimizer to initial step (current priority level = 0)
  105518. */
  105519. SceneOptimizer.prototype.reset = function () {
  105520. this._currentPriorityLevel = 0;
  105521. };
  105522. /**
  105523. * Start the optimizer. By default it will try to reach a specific framerate
  105524. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  105525. */
  105526. SceneOptimizer.prototype.start = function () {
  105527. var _this = this;
  105528. if (this._isRunning) {
  105529. return;
  105530. }
  105531. this._isRunning = true;
  105532. // Let's wait for the scene to be ready before running our check
  105533. this._scene.executeWhenReady(function () {
  105534. setTimeout(function () {
  105535. _this._checkCurrentState();
  105536. }, _this._trackerDuration);
  105537. });
  105538. };
  105539. SceneOptimizer.prototype._checkCurrentState = function () {
  105540. var _this = this;
  105541. if (!this._isRunning) {
  105542. return;
  105543. }
  105544. var scene = this._scene;
  105545. var options = this._options;
  105546. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  105547. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  105548. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  105549. this._isRunning = false;
  105550. this.onSuccessObservable.notifyObservers(this);
  105551. return;
  105552. }
  105553. // Apply current level of optimizations
  105554. var allDone = true;
  105555. var noOptimizationApplied = true;
  105556. for (var index = 0; index < options.optimizations.length; index++) {
  105557. var optimization = options.optimizations[index];
  105558. if (optimization.priority === this._currentPriorityLevel) {
  105559. noOptimizationApplied = false;
  105560. allDone = allDone && optimization.apply(scene, this);
  105561. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  105562. }
  105563. }
  105564. // If no optimization was applied, this is a failure :(
  105565. if (noOptimizationApplied) {
  105566. this._isRunning = false;
  105567. this.onFailureObservable.notifyObservers(this);
  105568. return;
  105569. }
  105570. // If all optimizations were done, move to next level
  105571. if (allDone) {
  105572. this._currentPriorityLevel++;
  105573. }
  105574. // Let's the system running for a specific amount of time before checking FPS
  105575. scene.executeWhenReady(function () {
  105576. setTimeout(function () {
  105577. _this._checkCurrentState();
  105578. }, _this._trackerDuration);
  105579. });
  105580. };
  105581. /**
  105582. * Release all resources
  105583. */
  105584. SceneOptimizer.prototype.dispose = function () {
  105585. this.stop();
  105586. this.onSuccessObservable.clear();
  105587. this.onFailureObservable.clear();
  105588. this.onNewOptimizationAppliedObservable.clear();
  105589. if (this._sceneDisposeObserver) {
  105590. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  105591. }
  105592. };
  105593. /**
  105594. * Helper function to create a SceneOptimizer with one single line of code
  105595. * @param scene defines the scene to work on
  105596. * @param options defines the options to use with the SceneOptimizer
  105597. * @param onSuccess defines a callback to call on success
  105598. * @param onFailure defines a callback to call on failure
  105599. * @returns the new SceneOptimizer object
  105600. */
  105601. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  105602. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  105603. if (onSuccess) {
  105604. optimizer.onSuccessObservable.add(function () {
  105605. onSuccess();
  105606. });
  105607. }
  105608. if (onFailure) {
  105609. optimizer.onFailureObservable.add(function () {
  105610. onFailure();
  105611. });
  105612. }
  105613. optimizer.start();
  105614. return optimizer;
  105615. };
  105616. return SceneOptimizer;
  105617. }());
  105618. BABYLON.SceneOptimizer = SceneOptimizer;
  105619. })(BABYLON || (BABYLON = {}));
  105620. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  105621. var BABYLON;
  105622. (function (BABYLON) {
  105623. /**
  105624. * Gets the outline renderer associated with the scene
  105625. * @returns a OutlineRenderer
  105626. */
  105627. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  105628. if (!this._outlineRenderer) {
  105629. this._outlineRenderer = new OutlineRenderer(this);
  105630. }
  105631. return this._outlineRenderer;
  105632. };
  105633. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  105634. get: function () {
  105635. return this._renderOutline;
  105636. },
  105637. set: function (value) {
  105638. if (value) {
  105639. // Lazy Load the component.
  105640. this.getScene().getOutlineRenderer();
  105641. }
  105642. this._renderOutline = value;
  105643. },
  105644. enumerable: true,
  105645. configurable: true
  105646. });
  105647. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  105648. get: function () {
  105649. return this._renderOverlay;
  105650. },
  105651. set: function (value) {
  105652. if (value) {
  105653. // Lazy Load the component.
  105654. this.getScene().getOutlineRenderer();
  105655. }
  105656. this._renderOverlay = value;
  105657. },
  105658. enumerable: true,
  105659. configurable: true
  105660. });
  105661. /**
  105662. * This class is responsible to draw bothe outline/overlay of meshes.
  105663. * It should not be used directly but through the available method on mesh.
  105664. */
  105665. var OutlineRenderer = /** @class */ (function () {
  105666. /**
  105667. * Instantiates a new outline renderer. (There could be only one per scene).
  105668. * @param scene Defines the scene it belongs to
  105669. */
  105670. function OutlineRenderer(scene) {
  105671. /**
  105672. * The name of the component. Each component must have a unique name.
  105673. */
  105674. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  105675. /**
  105676. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  105677. */
  105678. this.zOffset = 1;
  105679. this.scene = scene;
  105680. this._engine = scene.getEngine();
  105681. this.scene._addComponent(this);
  105682. }
  105683. /**
  105684. * Register the component to one instance of a scene.
  105685. */
  105686. OutlineRenderer.prototype.register = function () {
  105687. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  105688. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  105689. };
  105690. /**
  105691. * Rebuilds the elements related to this component in case of
  105692. * context lost for instance.
  105693. */
  105694. OutlineRenderer.prototype.rebuild = function () {
  105695. // Nothing to do here.
  105696. };
  105697. /**
  105698. * Disposes the component and the associated ressources.
  105699. */
  105700. OutlineRenderer.prototype.dispose = function () {
  105701. // Nothing to do here.
  105702. };
  105703. /**
  105704. * Renders the outline in the canvas.
  105705. * @param subMesh Defines the sumesh to render
  105706. * @param batch Defines the batch of meshes in case of instances
  105707. * @param useOverlay Defines if the rendering is for the overlay or the outline
  105708. */
  105709. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  105710. var _this = this;
  105711. if (useOverlay === void 0) { useOverlay = false; }
  105712. var scene = this.scene;
  105713. var engine = scene.getEngine();
  105714. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105715. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  105716. return;
  105717. }
  105718. var mesh = subMesh.getRenderingMesh();
  105719. var material = subMesh.getMaterial();
  105720. if (!material || !scene.activeCamera) {
  105721. return;
  105722. }
  105723. engine.enableEffect(this._effect);
  105724. // Logarithmic depth
  105725. if (material.useLogarithmicDepth) {
  105726. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  105727. }
  105728. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  105729. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  105730. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  105731. // Bones
  105732. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105733. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105734. }
  105735. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  105736. // Alpha test
  105737. if (material && material.needAlphaTesting()) {
  105738. var alphaTexture = material.getAlphaTestTexture();
  105739. if (alphaTexture) {
  105740. this._effect.setTexture("diffuseSampler", alphaTexture);
  105741. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  105742. }
  105743. }
  105744. engine.setZOffset(-this.zOffset);
  105745. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  105746. engine.setZOffset(0);
  105747. };
  105748. /**
  105749. * Returns whether or not the outline renderer is ready for a given submesh.
  105750. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  105751. * @param subMesh Defines the submesh to check readyness for
  105752. * @param useInstances Defines wheter wee are trying to render instances or not
  105753. * @returns true if ready otherwise false
  105754. */
  105755. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  105756. var defines = [];
  105757. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  105758. var mesh = subMesh.getMesh();
  105759. var material = subMesh.getMaterial();
  105760. if (material) {
  105761. // Alpha test
  105762. if (material.needAlphaTesting()) {
  105763. defines.push("#define ALPHATEST");
  105764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105765. attribs.push(BABYLON.VertexBuffer.UVKind);
  105766. defines.push("#define UV1");
  105767. }
  105768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  105769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105770. defines.push("#define UV2");
  105771. }
  105772. }
  105773. //Logarithmic depth
  105774. if (material.useLogarithmicDepth) {
  105775. defines.push("#define LOGARITHMICDEPTH");
  105776. }
  105777. }
  105778. // Bones
  105779. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105782. if (mesh.numBoneInfluencers > 4) {
  105783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105785. }
  105786. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105787. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  105788. }
  105789. else {
  105790. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105791. }
  105792. // Instances
  105793. if (useInstances) {
  105794. defines.push("#define INSTANCES");
  105795. attribs.push("world0");
  105796. attribs.push("world1");
  105797. attribs.push("world2");
  105798. attribs.push("world3");
  105799. }
  105800. // Get correct effect
  105801. var join = defines.join("\n");
  105802. if (this._cachedDefines !== join) {
  105803. this._cachedDefines = join;
  105804. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  105805. }
  105806. return this._effect.isReady();
  105807. };
  105808. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  105809. // Outline - step 1
  105810. this._savedDepthWrite = this._engine.getDepthWrite();
  105811. if (mesh.renderOutline) {
  105812. this._engine.setDepthWrite(false);
  105813. this.render(subMesh, batch);
  105814. this._engine.setDepthWrite(this._savedDepthWrite);
  105815. }
  105816. };
  105817. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  105818. // Outline - step 2
  105819. if (mesh.renderOutline && this._savedDepthWrite) {
  105820. this._engine.setDepthWrite(true);
  105821. this._engine.setColorWrite(false);
  105822. this.render(subMesh, batch);
  105823. this._engine.setColorWrite(true);
  105824. }
  105825. // Overlay
  105826. if (mesh.renderOverlay) {
  105827. var currentMode = this._engine.getAlphaMode();
  105828. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105829. this.render(subMesh, batch, true);
  105830. this._engine.setAlphaMode(currentMode);
  105831. }
  105832. };
  105833. return OutlineRenderer;
  105834. }());
  105835. BABYLON.OutlineRenderer = OutlineRenderer;
  105836. })(BABYLON || (BABYLON = {}));
  105837. //# sourceMappingURL=babylon.outlineRenderer.js.map
  105838. var BABYLON;
  105839. (function (BABYLON) {
  105840. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  105841. if (this._edgesRenderer) {
  105842. this._edgesRenderer.dispose();
  105843. this._edgesRenderer = null;
  105844. }
  105845. return this;
  105846. };
  105847. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105848. if (epsilon === void 0) { epsilon = 0.95; }
  105849. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105850. this.disableEdgesRendering();
  105851. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105852. return this;
  105853. };
  105854. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  105855. get: function () {
  105856. return this._edgesRenderer;
  105857. },
  105858. enumerable: true,
  105859. configurable: true
  105860. });
  105861. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105862. if (epsilon === void 0) { epsilon = 0.95; }
  105863. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105864. this.disableEdgesRendering();
  105865. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105866. return this;
  105867. };
  105868. /**
  105869. * FaceAdjacencies Helper class to generate edges
  105870. */
  105871. var FaceAdjacencies = /** @class */ (function () {
  105872. function FaceAdjacencies() {
  105873. this.edges = new Array();
  105874. this.edgesConnectedCount = 0;
  105875. }
  105876. return FaceAdjacencies;
  105877. }());
  105878. /**
  105879. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  105880. */
  105881. var EdgesRenderer = /** @class */ (function () {
  105882. /**
  105883. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  105884. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  105885. * @param source Mesh used to create edges
  105886. * @param epsilon sum of angles in adjacency to check for edge
  105887. * @param checkVerticesInsteadOfIndices
  105888. * @param generateEdgesLines - should generate Lines or only prepare resources.
  105889. */
  105890. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  105891. if (epsilon === void 0) { epsilon = 0.95; }
  105892. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105893. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  105894. var _this = this;
  105895. /**
  105896. * Define the size of the edges with an orthographic camera
  105897. */
  105898. this.edgesWidthScalerForOrthographic = 1000.0;
  105899. /**
  105900. * Define the size of the edges with a perspective camera
  105901. */
  105902. this.edgesWidthScalerForPerspective = 50.0;
  105903. this._linesPositions = new Array();
  105904. this._linesNormals = new Array();
  105905. this._linesIndices = new Array();
  105906. this._buffers = {};
  105907. this._checkVerticesInsteadOfIndices = false;
  105908. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  105909. this.isEnabled = true;
  105910. this._source = source;
  105911. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  105912. this._epsilon = epsilon;
  105913. this._prepareRessources();
  105914. if (generateEdgesLines) {
  105915. this._generateEdgesLines();
  105916. }
  105917. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  105918. _this._rebuild();
  105919. });
  105920. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  105921. _this.dispose();
  105922. });
  105923. }
  105924. EdgesRenderer.prototype._prepareRessources = function () {
  105925. if (this._lineShader) {
  105926. return;
  105927. }
  105928. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  105929. attributes: ["position", "normal"],
  105930. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  105931. });
  105932. this._lineShader.disableDepthWrite = true;
  105933. this._lineShader.backFaceCulling = false;
  105934. };
  105935. /** @hidden */
  105936. EdgesRenderer.prototype._rebuild = function () {
  105937. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105938. if (buffer) {
  105939. buffer._rebuild();
  105940. }
  105941. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105942. if (buffer) {
  105943. buffer._rebuild();
  105944. }
  105945. var scene = this._source.getScene();
  105946. var engine = scene.getEngine();
  105947. this._ib = engine.createIndexBuffer(this._linesIndices);
  105948. };
  105949. /**
  105950. * Releases the required resources for the edges renderer
  105951. */
  105952. EdgesRenderer.prototype.dispose = function () {
  105953. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  105954. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  105955. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105956. if (buffer) {
  105957. buffer.dispose();
  105958. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  105959. }
  105960. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105961. if (buffer) {
  105962. buffer.dispose();
  105963. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  105964. }
  105965. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  105966. this._lineShader.dispose();
  105967. };
  105968. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  105969. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  105970. return 0;
  105971. }
  105972. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  105973. return 1;
  105974. }
  105975. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  105976. return 2;
  105977. }
  105978. return -1;
  105979. };
  105980. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  105981. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  105982. return 0;
  105983. }
  105984. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  105985. return 1;
  105986. }
  105987. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  105988. return 2;
  105989. }
  105990. return -1;
  105991. };
  105992. /**
  105993. * Checks if the pair of p0 and p1 is en edge
  105994. * @param faceIndex
  105995. * @param edge
  105996. * @param faceNormals
  105997. * @param p0
  105998. * @param p1
  105999. * @private
  106000. */
  106001. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106002. var needToCreateLine;
  106003. if (edge === undefined) {
  106004. needToCreateLine = true;
  106005. }
  106006. else {
  106007. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  106008. needToCreateLine = dotProduct < this._epsilon;
  106009. }
  106010. if (needToCreateLine) {
  106011. var offset = this._linesPositions.length / 3;
  106012. var normal = p0.subtract(p1);
  106013. normal.normalize();
  106014. // Positions
  106015. this._linesPositions.push(p0.x);
  106016. this._linesPositions.push(p0.y);
  106017. this._linesPositions.push(p0.z);
  106018. this._linesPositions.push(p0.x);
  106019. this._linesPositions.push(p0.y);
  106020. this._linesPositions.push(p0.z);
  106021. this._linesPositions.push(p1.x);
  106022. this._linesPositions.push(p1.y);
  106023. this._linesPositions.push(p1.z);
  106024. this._linesPositions.push(p1.x);
  106025. this._linesPositions.push(p1.y);
  106026. this._linesPositions.push(p1.z);
  106027. // Normals
  106028. this._linesNormals.push(p1.x);
  106029. this._linesNormals.push(p1.y);
  106030. this._linesNormals.push(p1.z);
  106031. this._linesNormals.push(-1);
  106032. this._linesNormals.push(p1.x);
  106033. this._linesNormals.push(p1.y);
  106034. this._linesNormals.push(p1.z);
  106035. this._linesNormals.push(1);
  106036. this._linesNormals.push(p0.x);
  106037. this._linesNormals.push(p0.y);
  106038. this._linesNormals.push(p0.z);
  106039. this._linesNormals.push(-1);
  106040. this._linesNormals.push(p0.x);
  106041. this._linesNormals.push(p0.y);
  106042. this._linesNormals.push(p0.z);
  106043. this._linesNormals.push(1);
  106044. // Indices
  106045. this._linesIndices.push(offset);
  106046. this._linesIndices.push(offset + 1);
  106047. this._linesIndices.push(offset + 2);
  106048. this._linesIndices.push(offset);
  106049. this._linesIndices.push(offset + 2);
  106050. this._linesIndices.push(offset + 3);
  106051. }
  106052. };
  106053. /**
  106054. * Generates lines edges from adjacencjes
  106055. * @private
  106056. */
  106057. EdgesRenderer.prototype._generateEdgesLines = function () {
  106058. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106059. var indices = this._source.getIndices();
  106060. if (!indices || !positions) {
  106061. return;
  106062. }
  106063. // First let's find adjacencies
  106064. var adjacencies = new Array();
  106065. var faceNormals = new Array();
  106066. var index;
  106067. var faceAdjacencies;
  106068. // Prepare faces
  106069. for (index = 0; index < indices.length; index += 3) {
  106070. faceAdjacencies = new FaceAdjacencies();
  106071. var p0Index = indices[index];
  106072. var p1Index = indices[index + 1];
  106073. var p2Index = indices[index + 2];
  106074. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106075. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106076. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106077. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106078. faceNormal.normalize();
  106079. faceNormals.push(faceNormal);
  106080. adjacencies.push(faceAdjacencies);
  106081. }
  106082. // Scan
  106083. for (index = 0; index < adjacencies.length; index++) {
  106084. faceAdjacencies = adjacencies[index];
  106085. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106086. var otherFaceAdjacencies = adjacencies[otherIndex];
  106087. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106088. break;
  106089. }
  106090. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106091. continue;
  106092. }
  106093. var otherP0 = indices[otherIndex * 3];
  106094. var otherP1 = indices[otherIndex * 3 + 1];
  106095. var otherP2 = indices[otherIndex * 3 + 2];
  106096. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  106097. var otherEdgeIndex = 0;
  106098. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  106099. continue;
  106100. }
  106101. switch (edgeIndex) {
  106102. case 0:
  106103. if (this._checkVerticesInsteadOfIndices) {
  106104. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106105. }
  106106. else {
  106107. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  106108. }
  106109. break;
  106110. case 1:
  106111. if (this._checkVerticesInsteadOfIndices) {
  106112. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106113. }
  106114. else {
  106115. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  106116. }
  106117. break;
  106118. case 2:
  106119. if (this._checkVerticesInsteadOfIndices) {
  106120. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106121. }
  106122. else {
  106123. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  106124. }
  106125. break;
  106126. }
  106127. if (otherEdgeIndex === -1) {
  106128. continue;
  106129. }
  106130. faceAdjacencies.edges[edgeIndex] = otherIndex;
  106131. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  106132. faceAdjacencies.edgesConnectedCount++;
  106133. otherFaceAdjacencies.edgesConnectedCount++;
  106134. if (faceAdjacencies.edgesConnectedCount === 3) {
  106135. break;
  106136. }
  106137. }
  106138. }
  106139. }
  106140. // Create lines
  106141. for (index = 0; index < adjacencies.length; index++) {
  106142. // 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
  106143. var current = adjacencies[index];
  106144. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106145. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  106146. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  106147. }
  106148. // Merge into a single mesh
  106149. var engine = this._source.getScene().getEngine();
  106150. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  106151. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  106152. this._ib = engine.createIndexBuffer(this._linesIndices);
  106153. this._indicesCount = this._linesIndices.length;
  106154. };
  106155. /**
  106156. * Checks wether or not the edges renderer is ready to render.
  106157. * @return true if ready, otherwise false.
  106158. */
  106159. EdgesRenderer.prototype.isReady = function () {
  106160. return this._lineShader.isReady();
  106161. };
  106162. /**
  106163. * Renders the edges of the attached mesh,
  106164. */
  106165. EdgesRenderer.prototype.render = function () {
  106166. var scene = this._source.getScene();
  106167. if (!this.isReady() || !scene.activeCamera) {
  106168. return;
  106169. }
  106170. var engine = scene.getEngine();
  106171. this._lineShader._preBind();
  106172. if (this._source.edgesColor.a !== 1) {
  106173. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106174. }
  106175. else {
  106176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  106177. }
  106178. // VBOs
  106179. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  106180. scene.resetCachedMaterial();
  106181. this._lineShader.setColor4("color", this._source.edgesColor);
  106182. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  106183. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  106184. }
  106185. else {
  106186. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  106187. }
  106188. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  106189. this._lineShader.bind(this._source.getWorldMatrix());
  106190. // Draw order
  106191. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  106192. this._lineShader.unbind();
  106193. };
  106194. return EdgesRenderer;
  106195. }());
  106196. BABYLON.EdgesRenderer = EdgesRenderer;
  106197. })(BABYLON || (BABYLON = {}));
  106198. //# sourceMappingURL=babylon.edgesRenderer.js.map
  106199. var BABYLON;
  106200. (function (BABYLON) {
  106201. /**
  106202. * FaceAdjacencies Helper class to generate edges
  106203. */
  106204. var FaceAdjacencies = /** @class */ (function () {
  106205. function FaceAdjacencies() {
  106206. this.edges = new Array();
  106207. this.edgesConnectedCount = 0;
  106208. }
  106209. return FaceAdjacencies;
  106210. }());
  106211. /**
  106212. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  106213. */
  106214. var LineEdgesRenderer = /** @class */ (function (_super) {
  106215. __extends(LineEdgesRenderer, _super);
  106216. /**
  106217. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  106218. * @param source LineMesh used to generate edges
  106219. * @param epsilon not important (specified angle for edge detection)
  106220. * @param checkVerticesInsteadOfIndices not important for LineMesh
  106221. */
  106222. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  106223. if (epsilon === void 0) { epsilon = 0.95; }
  106224. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106225. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  106226. _this._generateEdgesLines();
  106227. return _this;
  106228. }
  106229. /**
  106230. * Always create the edge since its a line so only important things are p0 and p1
  106231. * @param faceIndex not important for LineMesh
  106232. * @param edge not important for LineMesh
  106233. * @param faceNormals not important for LineMesh
  106234. * @param p0 beginnig of line
  106235. * @param p1 end of line
  106236. */
  106237. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106238. var offset = this._linesPositions.length / 3;
  106239. var normal = p0.subtract(p1);
  106240. normal.normalize();
  106241. // Positions
  106242. this._linesPositions.push(p0.x);
  106243. this._linesPositions.push(p0.y);
  106244. this._linesPositions.push(p0.z);
  106245. this._linesPositions.push(p0.x);
  106246. this._linesPositions.push(p0.y);
  106247. this._linesPositions.push(p0.z);
  106248. this._linesPositions.push(p1.x);
  106249. this._linesPositions.push(p1.y);
  106250. this._linesPositions.push(p1.z);
  106251. this._linesPositions.push(p1.x);
  106252. this._linesPositions.push(p1.y);
  106253. this._linesPositions.push(p1.z);
  106254. // Normals
  106255. this._linesNormals.push(p1.x);
  106256. this._linesNormals.push(p1.y);
  106257. this._linesNormals.push(p1.z);
  106258. this._linesNormals.push(-1);
  106259. this._linesNormals.push(p1.x);
  106260. this._linesNormals.push(p1.y);
  106261. this._linesNormals.push(p1.z);
  106262. this._linesNormals.push(1);
  106263. this._linesNormals.push(p0.x);
  106264. this._linesNormals.push(p0.y);
  106265. this._linesNormals.push(p0.z);
  106266. this._linesNormals.push(-1);
  106267. this._linesNormals.push(p0.x);
  106268. this._linesNormals.push(p0.y);
  106269. this._linesNormals.push(p0.z);
  106270. this._linesNormals.push(1);
  106271. // Indices
  106272. this._linesIndices.push(offset);
  106273. this._linesIndices.push(offset + 1);
  106274. this._linesIndices.push(offset + 2);
  106275. this._linesIndices.push(offset);
  106276. this._linesIndices.push(offset + 2);
  106277. this._linesIndices.push(offset + 3);
  106278. };
  106279. /**
  106280. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  106281. */
  106282. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  106283. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106284. var indices = this._source.getIndices();
  106285. if (!indices || !positions) {
  106286. return;
  106287. }
  106288. // First let's find adjacencies
  106289. var adjacencies = new Array();
  106290. var faceNormals = new Array();
  106291. var index;
  106292. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  106293. var currentAdjecancy = new FaceAdjacencies();
  106294. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  106295. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  106296. adjacencies.push(currentAdjecancy);
  106297. }
  106298. // Create lines
  106299. for (index = 0; index < adjacencies.length; index++) {
  106300. // 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
  106301. var current = adjacencies[index];
  106302. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  106303. }
  106304. // Merge into a single mesh
  106305. var engine = this._source.getScene().getEngine();
  106306. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  106307. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  106308. this._ib = engine.createIndexBuffer(this._linesIndices);
  106309. this._indicesCount = this._linesIndices.length;
  106310. };
  106311. return LineEdgesRenderer;
  106312. }(BABYLON.EdgesRenderer));
  106313. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  106314. })(BABYLON || (BABYLON = {}));
  106315. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  106316. var BABYLON;
  106317. (function (BABYLON) {
  106318. // Adds the parser to the scene parsers.
  106319. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  106320. if (parsedData.effectLayers) {
  106321. if (!container.effectLayers) {
  106322. container.effectLayers = new Array();
  106323. }
  106324. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  106325. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  106326. container.effectLayers.push(effectLayer);
  106327. }
  106328. }
  106329. });
  106330. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  106331. var index = this.effectLayers.indexOf(toRemove);
  106332. if (index !== -1) {
  106333. this.effectLayers.splice(index, 1);
  106334. }
  106335. return index;
  106336. };
  106337. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  106338. this.effectLayers.push(newEffectLayer);
  106339. };
  106340. /**
  106341. * Defines the layer scene component responsible to manage any effect layers
  106342. * in a given scene.
  106343. */
  106344. var EffectLayerSceneComponent = /** @class */ (function () {
  106345. /**
  106346. * Creates a new instance of the component for the given scene
  106347. * @param scene Defines the scene to register the component in
  106348. */
  106349. function EffectLayerSceneComponent(scene) {
  106350. /**
  106351. * The component name helpfull to identify the component in the list of scene components.
  106352. */
  106353. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  106354. this._renderEffects = false;
  106355. this._needStencil = false;
  106356. this._previousStencilState = false;
  106357. this.scene = scene;
  106358. this._engine = scene.getEngine();
  106359. scene.effectLayers = new Array();
  106360. }
  106361. /**
  106362. * Registers the component in a given scene
  106363. */
  106364. EffectLayerSceneComponent.prototype.register = function () {
  106365. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  106366. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  106367. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  106368. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  106369. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  106370. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  106371. };
  106372. /**
  106373. * Rebuilds the elements related to this component in case of
  106374. * context lost for instance.
  106375. */
  106376. EffectLayerSceneComponent.prototype.rebuild = function () {
  106377. var layers = this.scene.effectLayers;
  106378. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  106379. var effectLayer = layers_1[_i];
  106380. effectLayer._rebuild();
  106381. }
  106382. };
  106383. /**
  106384. * Serializes the component data to the specified json object
  106385. * @param serializationObject The object to serialize to
  106386. */
  106387. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  106388. // Effect layers
  106389. serializationObject.effectLayers = [];
  106390. var layers = this.scene.effectLayers;
  106391. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  106392. var effectLayer = layers_2[_i];
  106393. if (effectLayer.serialize) {
  106394. serializationObject.effectLayers.push(effectLayer.serialize());
  106395. }
  106396. }
  106397. };
  106398. /**
  106399. * Adds all the element from the container to the scene
  106400. * @param container the container holding the elements
  106401. */
  106402. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  106403. var _this = this;
  106404. if (!container.effectLayers) {
  106405. return;
  106406. }
  106407. container.effectLayers.forEach(function (o) {
  106408. _this.scene.addEffectLayer(o);
  106409. });
  106410. };
  106411. /**
  106412. * Removes all the elements in the container from the scene
  106413. * @param container contains the elements to remove
  106414. */
  106415. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  106416. var _this = this;
  106417. if (!container.effectLayers) {
  106418. return;
  106419. }
  106420. container.effectLayers.forEach(function (o) {
  106421. _this.scene.removeEffectLayer(o);
  106422. });
  106423. };
  106424. /**
  106425. * Disposes the component and the associated ressources.
  106426. */
  106427. EffectLayerSceneComponent.prototype.dispose = function () {
  106428. var layers = this.scene.effectLayers;
  106429. while (layers.length) {
  106430. layers[0].dispose();
  106431. }
  106432. };
  106433. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  106434. var layers = this.scene.effectLayers;
  106435. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  106436. var layer = layers_3[_i];
  106437. if (!layer.hasMesh(mesh)) {
  106438. continue;
  106439. }
  106440. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  106441. var subMesh = _b[_a];
  106442. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  106443. return false;
  106444. }
  106445. }
  106446. }
  106447. return true;
  106448. };
  106449. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  106450. this._renderEffects = false;
  106451. this._needStencil = false;
  106452. var layers = this.scene.effectLayers;
  106453. if (layers && layers.length > 0) {
  106454. this._previousStencilState = this._engine.getStencilBuffer();
  106455. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  106456. var effectLayer = layers_4[_i];
  106457. if (effectLayer.shouldRender() &&
  106458. (!effectLayer.camera ||
  106459. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  106460. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  106461. this._renderEffects = true;
  106462. this._needStencil = this._needStencil || effectLayer.needStencil();
  106463. var renderTarget = effectLayer._mainTexture;
  106464. if (renderTarget._shouldRender()) {
  106465. this.scene.incrementRenderId();
  106466. renderTarget.render(false, false);
  106467. }
  106468. }
  106469. }
  106470. this.scene.incrementRenderId();
  106471. }
  106472. };
  106473. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  106474. // Activate effect Layer stencil
  106475. if (this._needStencil) {
  106476. this._engine.setStencilBuffer(true);
  106477. }
  106478. };
  106479. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  106480. // Restore effect Layer stencil
  106481. if (this._needStencil) {
  106482. this._engine.setStencilBuffer(this._previousStencilState);
  106483. }
  106484. };
  106485. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  106486. if (this._renderEffects) {
  106487. this._engine.setDepthBuffer(false);
  106488. var layers = this.scene.effectLayers;
  106489. for (var i = 0; i < layers.length; i++) {
  106490. var effectLayer = layers[i];
  106491. if (effectLayer.renderingGroupId === renderingGroupId) {
  106492. if (effectLayer.shouldRender()) {
  106493. effectLayer.render();
  106494. }
  106495. }
  106496. }
  106497. this._engine.setDepthBuffer(true);
  106498. }
  106499. };
  106500. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  106501. if (this._renderEffects) {
  106502. this._draw(-1);
  106503. }
  106504. };
  106505. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  106506. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  106507. this._draw(index);
  106508. }
  106509. };
  106510. return EffectLayerSceneComponent;
  106511. }());
  106512. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  106513. })(BABYLON || (BABYLON = {}));
  106514. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  106515. var __assign = (this && this.__assign) || function () {
  106516. __assign = Object.assign || function(t) {
  106517. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106518. s = arguments[i];
  106519. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106520. t[p] = s[p];
  106521. }
  106522. return t;
  106523. };
  106524. return __assign.apply(this, arguments);
  106525. };
  106526. var BABYLON;
  106527. (function (BABYLON) {
  106528. /**
  106529. * The effect layer Helps adding post process effect blended with the main pass.
  106530. *
  106531. * This can be for instance use to generate glow or higlight effects on the scene.
  106532. *
  106533. * The effect layer class can not be used directly and is intented to inherited from to be
  106534. * customized per effects.
  106535. */
  106536. var EffectLayer = /** @class */ (function () {
  106537. /**
  106538. * Instantiates a new effect Layer and references it in the scene.
  106539. * @param name The name of the layer
  106540. * @param scene The scene to use the layer in
  106541. */
  106542. function EffectLayer(
  106543. /** The Friendly of the effect in the scene */
  106544. name, scene) {
  106545. this._vertexBuffers = {};
  106546. this._maxSize = 0;
  106547. this._mainTextureDesiredSize = { width: 0, height: 0 };
  106548. this._shouldRender = true;
  106549. this._postProcesses = [];
  106550. this._textures = [];
  106551. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  106552. /**
  106553. * The clear color of the texture used to generate the glow map.
  106554. */
  106555. this.neutralColor = new BABYLON.Color4();
  106556. /**
  106557. * Specifies wether the highlight layer is enabled or not.
  106558. */
  106559. this.isEnabled = true;
  106560. /**
  106561. * An event triggered when the effect layer has been disposed.
  106562. */
  106563. this.onDisposeObservable = new BABYLON.Observable();
  106564. /**
  106565. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  106566. */
  106567. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  106568. /**
  106569. * An event triggered when the generated texture is being merged in the scene.
  106570. */
  106571. this.onBeforeComposeObservable = new BABYLON.Observable();
  106572. /**
  106573. * An event triggered when the generated texture has been merged in the scene.
  106574. */
  106575. this.onAfterComposeObservable = new BABYLON.Observable();
  106576. /**
  106577. * An event triggered when the efffect layer changes its size.
  106578. */
  106579. this.onSizeChangedObservable = new BABYLON.Observable();
  106580. this.name = name;
  106581. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106582. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  106583. if (!component) {
  106584. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  106585. this._scene._addComponent(component);
  106586. }
  106587. this._engine = this._scene.getEngine();
  106588. this._maxSize = this._engine.getCaps().maxTextureSize;
  106589. this._scene.effectLayers.push(this);
  106590. // Generate Buffers
  106591. this._generateIndexBuffer();
  106592. this._genrateVertexBuffer();
  106593. }
  106594. Object.defineProperty(EffectLayer.prototype, "camera", {
  106595. /**
  106596. * Gets the camera attached to the layer.
  106597. */
  106598. get: function () {
  106599. return this._effectLayerOptions.camera;
  106600. },
  106601. enumerable: true,
  106602. configurable: true
  106603. });
  106604. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  106605. /**
  106606. * Gets the rendering group id the layer should render in.
  106607. */
  106608. get: function () {
  106609. return this._effectLayerOptions.renderingGroupId;
  106610. },
  106611. enumerable: true,
  106612. configurable: true
  106613. });
  106614. /**
  106615. * Initializes the effect layer with the required options.
  106616. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  106617. */
  106618. EffectLayer.prototype._init = function (options) {
  106619. // Adapt options
  106620. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  106621. this._setMainTextureSize();
  106622. this._createMainTexture();
  106623. this._createTextureAndPostProcesses();
  106624. this._mergeEffect = this._createMergeEffect();
  106625. };
  106626. /**
  106627. * Generates the index buffer of the full screen quad blending to the main canvas.
  106628. */
  106629. EffectLayer.prototype._generateIndexBuffer = function () {
  106630. // Indices
  106631. var indices = [];
  106632. indices.push(0);
  106633. indices.push(1);
  106634. indices.push(2);
  106635. indices.push(0);
  106636. indices.push(2);
  106637. indices.push(3);
  106638. this._indexBuffer = this._engine.createIndexBuffer(indices);
  106639. };
  106640. /**
  106641. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  106642. */
  106643. EffectLayer.prototype._genrateVertexBuffer = function () {
  106644. // VBO
  106645. var vertices = [];
  106646. vertices.push(1, 1);
  106647. vertices.push(-1, 1);
  106648. vertices.push(-1, -1);
  106649. vertices.push(1, -1);
  106650. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  106651. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  106652. };
  106653. /**
  106654. * Sets the main texture desired size which is the closest power of two
  106655. * of the engine canvas size.
  106656. */
  106657. EffectLayer.prototype._setMainTextureSize = function () {
  106658. if (this._effectLayerOptions.mainTextureFixedSize) {
  106659. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  106660. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  106661. }
  106662. else {
  106663. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  106664. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  106665. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  106666. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  106667. }
  106668. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  106669. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  106670. };
  106671. /**
  106672. * Creates the main texture for the effect layer.
  106673. */
  106674. EffectLayer.prototype._createMainTexture = function () {
  106675. var _this = this;
  106676. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  106677. width: this._mainTextureDesiredSize.width,
  106678. height: this._mainTextureDesiredSize.height
  106679. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  106680. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  106681. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106682. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106683. this._mainTexture.anisotropicFilteringLevel = 1;
  106684. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106685. this._mainTexture.renderParticles = false;
  106686. this._mainTexture.renderList = null;
  106687. this._mainTexture.ignoreCameraViewport = true;
  106688. // Custom render function
  106689. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  106690. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  106691. var index;
  106692. var engine = _this._scene.getEngine();
  106693. if (depthOnlySubMeshes.length) {
  106694. engine.setColorWrite(false);
  106695. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  106696. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  106697. }
  106698. engine.setColorWrite(true);
  106699. }
  106700. for (index = 0; index < opaqueSubMeshes.length; index++) {
  106701. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  106702. }
  106703. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  106704. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  106705. }
  106706. for (index = 0; index < transparentSubMeshes.length; index++) {
  106707. _this._renderSubMesh(transparentSubMeshes.data[index]);
  106708. }
  106709. };
  106710. this._mainTexture.onClearObservable.add(function (engine) {
  106711. engine.clear(_this.neutralColor, true, true, true);
  106712. });
  106713. };
  106714. /**
  106715. * Checks for the readiness of the element composing the layer.
  106716. * @param subMesh the mesh to check for
  106717. * @param useInstances specify wether or not to use instances to render the mesh
  106718. * @param emissiveTexture the associated emissive texture used to generate the glow
  106719. * @return true if ready otherwise, false
  106720. */
  106721. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  106722. var material = subMesh.getMaterial();
  106723. if (!material) {
  106724. return false;
  106725. }
  106726. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  106727. return false;
  106728. }
  106729. var defines = [];
  106730. var attribs = [BABYLON.VertexBuffer.PositionKind];
  106731. var mesh = subMesh.getMesh();
  106732. var uv1 = false;
  106733. var uv2 = false;
  106734. // Alpha test
  106735. if (material && material.needAlphaTesting()) {
  106736. var alphaTexture = material.getAlphaTestTexture();
  106737. if (alphaTexture) {
  106738. defines.push("#define ALPHATEST");
  106739. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  106740. alphaTexture.coordinatesIndex === 1) {
  106741. defines.push("#define DIFFUSEUV2");
  106742. uv2 = true;
  106743. }
  106744. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106745. defines.push("#define DIFFUSEUV1");
  106746. uv1 = true;
  106747. }
  106748. }
  106749. }
  106750. // Emissive
  106751. if (emissiveTexture) {
  106752. defines.push("#define EMISSIVE");
  106753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  106754. emissiveTexture.coordinatesIndex === 1) {
  106755. defines.push("#define EMISSIVEUV2");
  106756. uv2 = true;
  106757. }
  106758. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106759. defines.push("#define EMISSIVEUV1");
  106760. uv1 = true;
  106761. }
  106762. }
  106763. if (uv1) {
  106764. attribs.push(BABYLON.VertexBuffer.UVKind);
  106765. defines.push("#define UV1");
  106766. }
  106767. if (uv2) {
  106768. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106769. defines.push("#define UV2");
  106770. }
  106771. // Bones
  106772. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106775. if (mesh.numBoneInfluencers > 4) {
  106776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106778. }
  106779. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106780. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  106781. }
  106782. else {
  106783. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106784. }
  106785. // Morph targets
  106786. var manager = mesh.morphTargetManager;
  106787. var morphInfluencers = 0;
  106788. if (manager) {
  106789. if (manager.numInfluencers > 0) {
  106790. defines.push("#define MORPHTARGETS");
  106791. morphInfluencers = manager.numInfluencers;
  106792. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  106793. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  106794. }
  106795. }
  106796. // Instances
  106797. if (useInstances) {
  106798. defines.push("#define INSTANCES");
  106799. attribs.push("world0");
  106800. attribs.push("world1");
  106801. attribs.push("world2");
  106802. attribs.push("world3");
  106803. }
  106804. // Get correct effect
  106805. var join = defines.join("\n");
  106806. if (this._cachedDefines !== join) {
  106807. this._cachedDefines = join;
  106808. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  106809. }
  106810. return this._effectLayerMapGenerationEffect.isReady();
  106811. };
  106812. /**
  106813. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  106814. */
  106815. EffectLayer.prototype.render = function () {
  106816. var currentEffect = this._mergeEffect;
  106817. // Check
  106818. if (!currentEffect.isReady())
  106819. return;
  106820. for (var i = 0; i < this._postProcesses.length; i++) {
  106821. if (!this._postProcesses[i].isReady()) {
  106822. return;
  106823. }
  106824. }
  106825. var engine = this._scene.getEngine();
  106826. this.onBeforeComposeObservable.notifyObservers(this);
  106827. // Render
  106828. engine.enableEffect(currentEffect);
  106829. engine.setState(false);
  106830. // VBOs
  106831. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106832. // Cache
  106833. var previousAlphaMode = engine.getAlphaMode();
  106834. // Go Blend.
  106835. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  106836. // Blends the map on the main canvas.
  106837. this._internalRender(currentEffect);
  106838. // Restore Alpha
  106839. engine.setAlphaMode(previousAlphaMode);
  106840. this.onAfterComposeObservable.notifyObservers(this);
  106841. // Handle size changes.
  106842. var size = this._mainTexture.getSize();
  106843. this._setMainTextureSize();
  106844. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  106845. // Recreate RTT and post processes on size change.
  106846. this.onSizeChangedObservable.notifyObservers(this);
  106847. this._disposeTextureAndPostProcesses();
  106848. this._createMainTexture();
  106849. this._createTextureAndPostProcesses();
  106850. }
  106851. };
  106852. /**
  106853. * Determine if a given mesh will be used in the current effect.
  106854. * @param mesh mesh to test
  106855. * @returns true if the mesh will be used
  106856. */
  106857. EffectLayer.prototype.hasMesh = function (mesh) {
  106858. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  106859. return true;
  106860. }
  106861. return false;
  106862. };
  106863. /**
  106864. * Returns true if the layer contains information to display, otherwise false.
  106865. * @returns true if the glow layer should be rendered
  106866. */
  106867. EffectLayer.prototype.shouldRender = function () {
  106868. return this.isEnabled && this._shouldRender;
  106869. };
  106870. /**
  106871. * Returns true if the mesh should render, otherwise false.
  106872. * @param mesh The mesh to render
  106873. * @returns true if it should render otherwise false
  106874. */
  106875. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  106876. return true;
  106877. };
  106878. /**
  106879. * Returns true if the mesh should render, otherwise false.
  106880. * @param mesh The mesh to render
  106881. * @returns true if it should render otherwise false
  106882. */
  106883. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  106884. return true;
  106885. };
  106886. /**
  106887. * Renders the submesh passed in parameter to the generation map.
  106888. */
  106889. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  106890. var _this = this;
  106891. if (!this.shouldRender()) {
  106892. return;
  106893. }
  106894. var material = subMesh.getMaterial();
  106895. var mesh = subMesh.getRenderingMesh();
  106896. var scene = this._scene;
  106897. var engine = scene.getEngine();
  106898. if (!material) {
  106899. return;
  106900. }
  106901. // Do not block in blend mode.
  106902. if (material.needAlphaBlendingForMesh(mesh)) {
  106903. return;
  106904. }
  106905. // Culling
  106906. engine.setState(material.backFaceCulling);
  106907. // Managing instances
  106908. var batch = mesh._getInstancesRenderList(subMesh._id);
  106909. if (batch.mustReturn) {
  106910. return;
  106911. }
  106912. // Early Exit per mesh
  106913. if (!this._shouldRenderMesh(mesh)) {
  106914. return;
  106915. }
  106916. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106917. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  106918. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  106919. engine.enableEffect(this._effectLayerMapGenerationEffect);
  106920. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  106921. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  106922. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  106923. // Alpha test
  106924. if (material && material.needAlphaTesting()) {
  106925. var alphaTexture = material.getAlphaTestTexture();
  106926. if (alphaTexture) {
  106927. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  106928. var textureMatrix = alphaTexture.getTextureMatrix();
  106929. if (textureMatrix) {
  106930. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  106931. }
  106932. }
  106933. }
  106934. // Glow emissive only
  106935. if (this._emissiveTextureAndColor.texture) {
  106936. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  106937. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  106938. }
  106939. // Bones
  106940. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106941. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106942. }
  106943. // Morph targets
  106944. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  106945. // Draw
  106946. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  106947. }
  106948. else {
  106949. // Need to reset refresh rate of the main map
  106950. this._mainTexture.resetRefreshCounter();
  106951. }
  106952. };
  106953. /**
  106954. * Rebuild the required buffers.
  106955. * @hidden Internal use only.
  106956. */
  106957. EffectLayer.prototype._rebuild = function () {
  106958. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106959. if (vb) {
  106960. vb._rebuild();
  106961. }
  106962. this._generateIndexBuffer();
  106963. };
  106964. /**
  106965. * Dispose only the render target textures and post process.
  106966. */
  106967. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  106968. this._mainTexture.dispose();
  106969. for (var i = 0; i < this._postProcesses.length; i++) {
  106970. if (this._postProcesses[i]) {
  106971. this._postProcesses[i].dispose();
  106972. }
  106973. }
  106974. this._postProcesses = [];
  106975. for (var i = 0; i < this._textures.length; i++) {
  106976. if (this._textures[i]) {
  106977. this._textures[i].dispose();
  106978. }
  106979. }
  106980. this._textures = [];
  106981. };
  106982. /**
  106983. * Dispose the highlight layer and free resources.
  106984. */
  106985. EffectLayer.prototype.dispose = function () {
  106986. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106987. if (vertexBuffer) {
  106988. vertexBuffer.dispose();
  106989. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106990. }
  106991. if (this._indexBuffer) {
  106992. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106993. this._indexBuffer = null;
  106994. }
  106995. // Clean textures and post processes
  106996. this._disposeTextureAndPostProcesses();
  106997. // Remove from scene
  106998. var index = this._scene.effectLayers.indexOf(this, 0);
  106999. if (index > -1) {
  107000. this._scene.effectLayers.splice(index, 1);
  107001. }
  107002. // Callback
  107003. this.onDisposeObservable.notifyObservers(this);
  107004. this.onDisposeObservable.clear();
  107005. this.onBeforeRenderMainTextureObservable.clear();
  107006. this.onBeforeComposeObservable.clear();
  107007. this.onAfterComposeObservable.clear();
  107008. this.onSizeChangedObservable.clear();
  107009. };
  107010. /**
  107011. * Gets the class name of the effect layer
  107012. * @returns the string with the class name of the effect layer
  107013. */
  107014. EffectLayer.prototype.getClassName = function () {
  107015. return "EffectLayer";
  107016. };
  107017. /**
  107018. * Creates an effect layer from parsed effect layer data
  107019. * @param parsedEffectLayer defines effect layer data
  107020. * @param scene defines the current scene
  107021. * @param rootUrl defines the root URL containing the effect layer information
  107022. * @returns a parsed effect Layer
  107023. */
  107024. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  107025. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  107026. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107027. };
  107028. __decorate([
  107029. BABYLON.serialize()
  107030. ], EffectLayer.prototype, "name", void 0);
  107031. __decorate([
  107032. BABYLON.serializeAsColor4()
  107033. ], EffectLayer.prototype, "neutralColor", void 0);
  107034. __decorate([
  107035. BABYLON.serialize()
  107036. ], EffectLayer.prototype, "isEnabled", void 0);
  107037. __decorate([
  107038. BABYLON.serializeAsCameraReference()
  107039. ], EffectLayer.prototype, "camera", null);
  107040. __decorate([
  107041. BABYLON.serialize()
  107042. ], EffectLayer.prototype, "renderingGroupId", null);
  107043. return EffectLayer;
  107044. }());
  107045. BABYLON.EffectLayer = EffectLayer;
  107046. })(BABYLON || (BABYLON = {}));
  107047. //# sourceMappingURL=babylon.effectLayer.js.map
  107048. var BABYLON;
  107049. (function (BABYLON) {
  107050. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107051. for (var index = 0; index < this.effectLayers.length; index++) {
  107052. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107053. return this.effectLayers[index];
  107054. }
  107055. }
  107056. return null;
  107057. };
  107058. /**
  107059. * Special Glow Blur post process only blurring the alpha channel
  107060. * It enforces keeping the most luminous color in the color channel.
  107061. */
  107062. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107063. __extends(GlowBlurPostProcess, _super);
  107064. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107066. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107067. _this.direction = direction;
  107068. _this.kernel = kernel;
  107069. _this.onApplyObservable.add(function (effect) {
  107070. effect.setFloat2("screenSize", _this.width, _this.height);
  107071. effect.setVector2("direction", _this.direction);
  107072. effect.setFloat("blurWidth", _this.kernel);
  107073. });
  107074. return _this;
  107075. }
  107076. return GlowBlurPostProcess;
  107077. }(BABYLON.PostProcess));
  107078. /**
  107079. * The highlight layer Helps adding a glow effect around a mesh.
  107080. *
  107081. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107082. * glowy meshes to your scene.
  107083. *
  107084. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107085. */
  107086. var HighlightLayer = /** @class */ (function (_super) {
  107087. __extends(HighlightLayer, _super);
  107088. /**
  107089. * Instantiates a new highlight Layer and references it to the scene..
  107090. * @param name The name of the layer
  107091. * @param scene The scene to use the layer in
  107092. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107093. */
  107094. function HighlightLayer(name, scene, options) {
  107095. var _this = _super.call(this, name, scene) || this;
  107096. _this.name = name;
  107097. /**
  107098. * Specifies whether or not the inner glow is ACTIVE in the layer.
  107099. */
  107100. _this.innerGlow = true;
  107101. /**
  107102. * Specifies whether or not the outer glow is ACTIVE in the layer.
  107103. */
  107104. _this.outerGlow = true;
  107105. /**
  107106. * An event triggered when the highlight layer is being blurred.
  107107. */
  107108. _this.onBeforeBlurObservable = new BABYLON.Observable();
  107109. /**
  107110. * An event triggered when the highlight layer has been blurred.
  107111. */
  107112. _this.onAfterBlurObservable = new BABYLON.Observable();
  107113. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  107114. _this._meshes = {};
  107115. _this._excludedMeshes = {};
  107116. _this.neutralColor = HighlightLayer.NeutralColor;
  107117. // Warn on stencil
  107118. if (!_this._engine.isStencilEnable) {
  107119. 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 }");
  107120. }
  107121. // Adapt options
  107122. _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);
  107123. // Initialize the layer
  107124. _this._init({
  107125. alphaBlendingMode: _this._options.alphaBlendingMode,
  107126. camera: _this._options.camera,
  107127. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107128. mainTextureRatio: _this._options.mainTextureRatio,
  107129. renderingGroupId: _this._options.renderingGroupId
  107130. });
  107131. // Do not render as long as no meshes have been added
  107132. _this._shouldRender = false;
  107133. return _this;
  107134. }
  107135. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  107136. /**
  107137. * Gets the horizontal size of the blur.
  107138. */
  107139. get: function () {
  107140. return this._horizontalBlurPostprocess.kernel;
  107141. },
  107142. /**
  107143. * Specifies the horizontal size of the blur.
  107144. */
  107145. set: function (value) {
  107146. this._horizontalBlurPostprocess.kernel = value;
  107147. },
  107148. enumerable: true,
  107149. configurable: true
  107150. });
  107151. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  107152. /**
  107153. * Gets the vertical size of the blur.
  107154. */
  107155. get: function () {
  107156. return this._verticalBlurPostprocess.kernel;
  107157. },
  107158. /**
  107159. * Specifies the vertical size of the blur.
  107160. */
  107161. set: function (value) {
  107162. this._verticalBlurPostprocess.kernel = value;
  107163. },
  107164. enumerable: true,
  107165. configurable: true
  107166. });
  107167. /**
  107168. * Get the effect name of the layer.
  107169. * @return The effect name
  107170. */
  107171. HighlightLayer.prototype.getEffectName = function () {
  107172. return HighlightLayer.EffectName;
  107173. };
  107174. /**
  107175. * Create the merge effect. This is the shader use to blit the information back
  107176. * to the main canvas at the end of the scene rendering.
  107177. */
  107178. HighlightLayer.prototype._createMergeEffect = function () {
  107179. // Effect
  107180. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  107181. };
  107182. /**
  107183. * Creates the render target textures and post processes used in the highlight layer.
  107184. */
  107185. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  107186. var _this = this;
  107187. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  107188. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  107189. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  107190. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  107191. var textureType = 0;
  107192. if (this._engine.getCaps().textureHalfFloatRender) {
  107193. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  107194. }
  107195. else {
  107196. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  107197. }
  107198. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  107199. width: blurTextureWidth,
  107200. height: blurTextureHeight
  107201. }, this._scene, false, true, textureType);
  107202. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107203. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107204. this._blurTexture.anisotropicFilteringLevel = 16;
  107205. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  107206. this._blurTexture.renderParticles = false;
  107207. this._blurTexture.ignoreCameraViewport = true;
  107208. this._textures = [this._blurTexture];
  107209. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  107210. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107211. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  107212. effect.setTexture("textureSampler", _this._mainTexture);
  107213. });
  107214. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107215. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  107216. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  107217. });
  107218. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  107219. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  107220. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  107221. });
  107222. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  107223. }
  107224. else {
  107225. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  107226. width: blurTextureWidth,
  107227. height: blurTextureHeight
  107228. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107229. this._horizontalBlurPostprocess.width = blurTextureWidth;
  107230. this._horizontalBlurPostprocess.height = blurTextureHeight;
  107231. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  107232. effect.setTexture("textureSampler", _this._mainTexture);
  107233. });
  107234. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  107235. width: blurTextureWidth,
  107236. height: blurTextureHeight
  107237. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107238. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  107239. }
  107240. this._mainTexture.onAfterUnbindObservable.add(function () {
  107241. _this.onBeforeBlurObservable.notifyObservers(_this);
  107242. var internalTexture = _this._blurTexture.getInternalTexture();
  107243. if (internalTexture) {
  107244. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  107245. }
  107246. _this.onAfterBlurObservable.notifyObservers(_this);
  107247. });
  107248. // Prevent autoClear.
  107249. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  107250. };
  107251. /**
  107252. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107253. */
  107254. HighlightLayer.prototype.needStencil = function () {
  107255. return true;
  107256. };
  107257. /**
  107258. * Checks for the readiness of the element composing the layer.
  107259. * @param subMesh the mesh to check for
  107260. * @param useInstances specify wether or not to use instances to render the mesh
  107261. * @param emissiveTexture the associated emissive texture used to generate the glow
  107262. * @return true if ready otherwise, false
  107263. */
  107264. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  107265. var material = subMesh.getMaterial();
  107266. var mesh = subMesh.getRenderingMesh();
  107267. if (!material || !mesh || !this._meshes) {
  107268. return false;
  107269. }
  107270. var emissiveTexture = null;
  107271. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  107272. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  107273. emissiveTexture = material.emissiveTexture;
  107274. }
  107275. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107276. };
  107277. /**
  107278. * Implementation specific of rendering the generating effect on the main canvas.
  107279. * @param effect The effect used to render through
  107280. */
  107281. HighlightLayer.prototype._internalRender = function (effect) {
  107282. // Texture
  107283. effect.setTexture("textureSampler", this._blurTexture);
  107284. // Cache
  107285. var engine = this._engine;
  107286. var previousStencilBuffer = engine.getStencilBuffer();
  107287. var previousStencilFunction = engine.getStencilFunction();
  107288. var previousStencilMask = engine.getStencilMask();
  107289. var previousStencilOperationPass = engine.getStencilOperationPass();
  107290. var previousStencilOperationFail = engine.getStencilOperationFail();
  107291. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  107292. var previousStencilReference = engine.getStencilFunctionReference();
  107293. // Stencil operations
  107294. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  107295. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  107296. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  107297. // Draw order
  107298. engine.setStencilMask(0x00);
  107299. engine.setStencilBuffer(true);
  107300. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  107301. // 2 passes inner outer
  107302. if (this.outerGlow) {
  107303. effect.setFloat("offset", 0);
  107304. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  107305. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107306. }
  107307. if (this.innerGlow) {
  107308. effect.setFloat("offset", 1);
  107309. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  107310. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107311. }
  107312. // Restore Cache
  107313. engine.setStencilFunction(previousStencilFunction);
  107314. engine.setStencilMask(previousStencilMask);
  107315. engine.setStencilBuffer(previousStencilBuffer);
  107316. engine.setStencilOperationPass(previousStencilOperationPass);
  107317. engine.setStencilOperationFail(previousStencilOperationFail);
  107318. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  107319. engine.setStencilFunctionReference(previousStencilReference);
  107320. };
  107321. /**
  107322. * Returns true if the layer contains information to display, otherwise false.
  107323. */
  107324. HighlightLayer.prototype.shouldRender = function () {
  107325. if (_super.prototype.shouldRender.call(this)) {
  107326. return this._meshes ? true : false;
  107327. }
  107328. return false;
  107329. };
  107330. /**
  107331. * Returns true if the mesh should render, otherwise false.
  107332. * @param mesh The mesh to render
  107333. * @returns true if it should render otherwise false
  107334. */
  107335. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  107336. // Excluded Mesh
  107337. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  107338. return false;
  107339. }
  107340. ;
  107341. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107342. return false;
  107343. }
  107344. return true;
  107345. };
  107346. /**
  107347. * Sets the required values for both the emissive texture and and the main color.
  107348. */
  107349. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107350. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  107351. if (highlightLayerMesh) {
  107352. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  107353. }
  107354. else {
  107355. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107356. }
  107357. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  107358. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107359. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  107360. }
  107361. else {
  107362. this._emissiveTextureAndColor.texture = null;
  107363. }
  107364. };
  107365. /**
  107366. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  107367. * @param mesh The mesh to exclude from the highlight layer
  107368. */
  107369. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  107370. if (!this._excludedMeshes) {
  107371. return;
  107372. }
  107373. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  107374. if (!meshExcluded) {
  107375. this._excludedMeshes[mesh.uniqueId] = {
  107376. mesh: mesh,
  107377. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  107378. mesh.getEngine().setStencilBuffer(false);
  107379. }),
  107380. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  107381. mesh.getEngine().setStencilBuffer(true);
  107382. }),
  107383. };
  107384. }
  107385. };
  107386. /**
  107387. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  107388. * @param mesh The mesh to highlight
  107389. */
  107390. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  107391. if (!this._excludedMeshes) {
  107392. return;
  107393. }
  107394. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  107395. if (meshExcluded) {
  107396. if (meshExcluded.beforeRender) {
  107397. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  107398. }
  107399. if (meshExcluded.afterRender) {
  107400. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  107401. }
  107402. }
  107403. this._excludedMeshes[mesh.uniqueId] = null;
  107404. };
  107405. /**
  107406. * Determine if a given mesh will be highlighted by the current HighlightLayer
  107407. * @param mesh mesh to test
  107408. * @returns true if the mesh will be highlighted by the current HighlightLayer
  107409. */
  107410. HighlightLayer.prototype.hasMesh = function (mesh) {
  107411. if (!this._meshes) {
  107412. return false;
  107413. }
  107414. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107415. return false;
  107416. }
  107417. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  107418. };
  107419. /**
  107420. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  107421. * @param mesh The mesh to highlight
  107422. * @param color The color of the highlight
  107423. * @param glowEmissiveOnly Extract the glow from the emissive texture
  107424. */
  107425. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  107426. var _this = this;
  107427. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  107428. if (!this._meshes) {
  107429. return;
  107430. }
  107431. var meshHighlight = this._meshes[mesh.uniqueId];
  107432. if (meshHighlight) {
  107433. meshHighlight.color = color;
  107434. }
  107435. else {
  107436. this._meshes[mesh.uniqueId] = {
  107437. mesh: mesh,
  107438. color: color,
  107439. // Lambda required for capture due to Observable this context
  107440. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  107441. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  107442. _this._defaultStencilReference(mesh);
  107443. }
  107444. else {
  107445. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  107446. }
  107447. }),
  107448. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  107449. glowEmissiveOnly: glowEmissiveOnly
  107450. };
  107451. mesh.onDisposeObservable.add(function () {
  107452. _this._disposeMesh(mesh);
  107453. });
  107454. }
  107455. this._shouldRender = true;
  107456. };
  107457. /**
  107458. * Remove a mesh from the highlight layer in order to make it stop glowing.
  107459. * @param mesh The mesh to highlight
  107460. */
  107461. HighlightLayer.prototype.removeMesh = function (mesh) {
  107462. if (!this._meshes) {
  107463. return;
  107464. }
  107465. var meshHighlight = this._meshes[mesh.uniqueId];
  107466. if (meshHighlight) {
  107467. if (meshHighlight.observerHighlight) {
  107468. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  107469. }
  107470. if (meshHighlight.observerDefault) {
  107471. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  107472. }
  107473. delete this._meshes[mesh.uniqueId];
  107474. }
  107475. this._shouldRender = false;
  107476. for (var meshHighlightToCheck in this._meshes) {
  107477. if (this._meshes[meshHighlightToCheck]) {
  107478. this._shouldRender = true;
  107479. break;
  107480. }
  107481. }
  107482. };
  107483. /**
  107484. * Force the stencil to the normal expected value for none glowing parts
  107485. */
  107486. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  107487. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  107488. };
  107489. /**
  107490. * Free any resources and references associated to a mesh.
  107491. * Internal use
  107492. * @param mesh The mesh to free.
  107493. * @hidden
  107494. */
  107495. HighlightLayer.prototype._disposeMesh = function (mesh) {
  107496. this.removeMesh(mesh);
  107497. this.removeExcludedMesh(mesh);
  107498. };
  107499. /**
  107500. * Dispose the highlight layer and free resources.
  107501. */
  107502. HighlightLayer.prototype.dispose = function () {
  107503. if (this._meshes) {
  107504. // Clean mesh references
  107505. for (var id in this._meshes) {
  107506. var meshHighlight = this._meshes[id];
  107507. if (meshHighlight && meshHighlight.mesh) {
  107508. if (meshHighlight.observerHighlight) {
  107509. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  107510. }
  107511. if (meshHighlight.observerDefault) {
  107512. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  107513. }
  107514. }
  107515. }
  107516. this._meshes = null;
  107517. }
  107518. if (this._excludedMeshes) {
  107519. for (var id in this._excludedMeshes) {
  107520. var meshHighlight = this._excludedMeshes[id];
  107521. if (meshHighlight) {
  107522. if (meshHighlight.beforeRender) {
  107523. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  107524. }
  107525. if (meshHighlight.afterRender) {
  107526. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  107527. }
  107528. }
  107529. }
  107530. this._excludedMeshes = null;
  107531. }
  107532. _super.prototype.dispose.call(this);
  107533. };
  107534. /**
  107535. * Gets the class name of the effect layer
  107536. * @returns the string with the class name of the effect layer
  107537. */
  107538. HighlightLayer.prototype.getClassName = function () {
  107539. return "HighlightLayer";
  107540. };
  107541. /**
  107542. * Serializes this Highlight layer
  107543. * @returns a serialized Highlight layer object
  107544. */
  107545. HighlightLayer.prototype.serialize = function () {
  107546. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107547. serializationObject.customType = "BABYLON.HighlightLayer";
  107548. // Highlighted meshes
  107549. serializationObject.meshes = [];
  107550. if (this._meshes) {
  107551. for (var m in this._meshes) {
  107552. var mesh = this._meshes[m];
  107553. if (mesh) {
  107554. serializationObject.meshes.push({
  107555. glowEmissiveOnly: mesh.glowEmissiveOnly,
  107556. color: mesh.color.asArray(),
  107557. meshId: mesh.mesh.id
  107558. });
  107559. }
  107560. }
  107561. }
  107562. // Excluded meshes
  107563. serializationObject.excludedMeshes = [];
  107564. if (this._excludedMeshes) {
  107565. for (var e in this._excludedMeshes) {
  107566. var excludedMesh = this._excludedMeshes[e];
  107567. if (excludedMesh) {
  107568. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  107569. }
  107570. }
  107571. }
  107572. return serializationObject;
  107573. };
  107574. /**
  107575. * Creates a Highlight layer from parsed Highlight layer data
  107576. * @param parsedHightlightLayer defines the Highlight layer data
  107577. * @param scene defines the current scene
  107578. * @param rootUrl defines the root URL containing the Highlight layer information
  107579. * @returns a parsed Highlight layer
  107580. */
  107581. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  107582. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  107583. var index;
  107584. // Excluded meshes
  107585. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  107586. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  107587. if (mesh) {
  107588. hl.addExcludedMesh(mesh);
  107589. }
  107590. }
  107591. // Included meshes
  107592. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  107593. var highlightedMesh = parsedHightlightLayer.meshes[index];
  107594. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  107595. if (mesh) {
  107596. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  107597. }
  107598. }
  107599. return hl;
  107600. };
  107601. /**
  107602. * Effect Name of the highlight layer.
  107603. */
  107604. HighlightLayer.EffectName = "HighlightLayer";
  107605. /**
  107606. * The neutral color used during the preparation of the glow effect.
  107607. * This is black by default as the blend operation is a blend operation.
  107608. */
  107609. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  107610. /**
  107611. * Stencil value used for glowing meshes.
  107612. */
  107613. HighlightLayer.GlowingMeshStencilReference = 0x02;
  107614. /**
  107615. * Stencil value used for the other meshes in the scene.
  107616. */
  107617. HighlightLayer.NormalMeshStencilReference = 0x01;
  107618. __decorate([
  107619. BABYLON.serialize()
  107620. ], HighlightLayer.prototype, "innerGlow", void 0);
  107621. __decorate([
  107622. BABYLON.serialize()
  107623. ], HighlightLayer.prototype, "outerGlow", void 0);
  107624. __decorate([
  107625. BABYLON.serialize()
  107626. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  107627. __decorate([
  107628. BABYLON.serialize()
  107629. ], HighlightLayer.prototype, "blurVerticalSize", null);
  107630. __decorate([
  107631. BABYLON.serialize("options")
  107632. ], HighlightLayer.prototype, "_options", void 0);
  107633. return HighlightLayer;
  107634. }(BABYLON.EffectLayer));
  107635. BABYLON.HighlightLayer = HighlightLayer;
  107636. })(BABYLON || (BABYLON = {}));
  107637. //# sourceMappingURL=babylon.highlightLayer.js.map
  107638. var BABYLON;
  107639. (function (BABYLON) {
  107640. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  107641. for (var index = 0; index < this.effectLayers.length; index++) {
  107642. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  107643. return this.effectLayers[index];
  107644. }
  107645. }
  107646. return null;
  107647. };
  107648. /**
  107649. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  107650. *
  107651. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107652. * glowy meshes to your scene.
  107653. *
  107654. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  107655. */
  107656. var GlowLayer = /** @class */ (function (_super) {
  107657. __extends(GlowLayer, _super);
  107658. /**
  107659. * Instantiates a new glow Layer and references it to the scene.
  107660. * @param name The name of the layer
  107661. * @param scene The scene to use the layer in
  107662. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  107663. */
  107664. function GlowLayer(name, scene, options) {
  107665. var _this = _super.call(this, name, scene) || this;
  107666. _this._intensity = 1.0;
  107667. _this._includedOnlyMeshes = [];
  107668. _this._excludedMeshes = [];
  107669. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  107670. // Adapt options
  107671. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  107672. // Initialize the layer
  107673. _this._init({
  107674. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  107675. camera: _this._options.camera,
  107676. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  107677. mainTextureRatio: _this._options.mainTextureRatio,
  107678. renderingGroupId: _this._options.renderingGroupId
  107679. });
  107680. return _this;
  107681. }
  107682. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  107683. /**
  107684. * Gets the kernel size of the blur.
  107685. */
  107686. get: function () {
  107687. return this._horizontalBlurPostprocess1.kernel;
  107688. },
  107689. /**
  107690. * Sets the kernel size of the blur.
  107691. */
  107692. set: function (value) {
  107693. this._horizontalBlurPostprocess1.kernel = value;
  107694. this._verticalBlurPostprocess1.kernel = value;
  107695. this._horizontalBlurPostprocess2.kernel = value;
  107696. this._verticalBlurPostprocess2.kernel = value;
  107697. },
  107698. enumerable: true,
  107699. configurable: true
  107700. });
  107701. Object.defineProperty(GlowLayer.prototype, "intensity", {
  107702. /**
  107703. * Gets the glow intensity.
  107704. */
  107705. get: function () {
  107706. return this._intensity;
  107707. },
  107708. /**
  107709. * Sets the glow intensity.
  107710. */
  107711. set: function (value) {
  107712. this._intensity = value;
  107713. },
  107714. enumerable: true,
  107715. configurable: true
  107716. });
  107717. /**
  107718. * Get the effect name of the layer.
  107719. * @return The effect name
  107720. */
  107721. GlowLayer.prototype.getEffectName = function () {
  107722. return GlowLayer.EffectName;
  107723. };
  107724. /**
  107725. * Create the merge effect. This is the shader use to blit the information back
  107726. * to the main canvas at the end of the scene rendering.
  107727. */
  107728. GlowLayer.prototype._createMergeEffect = function () {
  107729. // Effect
  107730. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  107731. };
  107732. /**
  107733. * Creates the render target textures and post processes used in the glow layer.
  107734. */
  107735. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  107736. var _this = this;
  107737. var blurTextureWidth = this._mainTextureDesiredSize.width;
  107738. var blurTextureHeight = this._mainTextureDesiredSize.height;
  107739. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  107740. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  107741. var textureType = 0;
  107742. if (this._engine.getCaps().textureHalfFloatRender) {
  107743. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  107744. }
  107745. else {
  107746. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  107747. }
  107748. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  107749. width: blurTextureWidth,
  107750. height: blurTextureHeight
  107751. }, this._scene, false, true, textureType);
  107752. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107753. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107754. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107755. this._blurTexture1.renderParticles = false;
  107756. this._blurTexture1.ignoreCameraViewport = true;
  107757. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  107758. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  107759. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  107760. width: blurTextureWidth2,
  107761. height: blurTextureHeight2
  107762. }, this._scene, false, true, textureType);
  107763. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107764. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107765. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107766. this._blurTexture2.renderParticles = false;
  107767. this._blurTexture2.ignoreCameraViewport = true;
  107768. this._textures = [this._blurTexture1, this._blurTexture2];
  107769. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  107770. width: blurTextureWidth,
  107771. height: blurTextureHeight
  107772. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107773. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  107774. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  107775. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  107776. effect.setTexture("textureSampler", _this._mainTexture);
  107777. });
  107778. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  107779. width: blurTextureWidth,
  107780. height: blurTextureHeight
  107781. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107782. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  107783. width: blurTextureWidth2,
  107784. height: blurTextureHeight2
  107785. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107786. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  107787. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  107788. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  107789. effect.setTexture("textureSampler", _this._blurTexture1);
  107790. });
  107791. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  107792. width: blurTextureWidth2,
  107793. height: blurTextureHeight2
  107794. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  107795. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  107796. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  107797. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  107798. this._mainTexture.samples = this._options.mainTextureSamples;
  107799. this._mainTexture.onAfterUnbindObservable.add(function () {
  107800. var internalTexture = _this._blurTexture1.getInternalTexture();
  107801. if (internalTexture) {
  107802. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  107803. internalTexture = _this._blurTexture2.getInternalTexture();
  107804. if (internalTexture) {
  107805. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  107806. }
  107807. }
  107808. });
  107809. // Prevent autoClear.
  107810. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  107811. };
  107812. /**
  107813. * Checks for the readiness of the element composing the layer.
  107814. * @param subMesh the mesh to check for
  107815. * @param useInstances specify wether or not to use instances to render the mesh
  107816. * @param emissiveTexture the associated emissive texture used to generate the glow
  107817. * @return true if ready otherwise, false
  107818. */
  107819. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  107820. var material = subMesh.getMaterial();
  107821. var mesh = subMesh.getRenderingMesh();
  107822. if (!material || !mesh) {
  107823. return false;
  107824. }
  107825. var emissiveTexture = material.emissiveTexture;
  107826. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107827. };
  107828. /**
  107829. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107830. */
  107831. GlowLayer.prototype.needStencil = function () {
  107832. return false;
  107833. };
  107834. /**
  107835. * Implementation specific of rendering the generating effect on the main canvas.
  107836. * @param effect The effect used to render through
  107837. */
  107838. GlowLayer.prototype._internalRender = function (effect) {
  107839. // Texture
  107840. effect.setTexture("textureSampler", this._blurTexture1);
  107841. effect.setTexture("textureSampler2", this._blurTexture2);
  107842. effect.setFloat("offset", this._intensity);
  107843. // Cache
  107844. var engine = this._engine;
  107845. var previousStencilBuffer = engine.getStencilBuffer();
  107846. // Draw order
  107847. engine.setStencilBuffer(false);
  107848. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107849. // Draw order
  107850. engine.setStencilBuffer(previousStencilBuffer);
  107851. };
  107852. /**
  107853. * Sets the required values for both the emissive texture and and the main color.
  107854. */
  107855. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107856. var textureLevel = 1.0;
  107857. if (this.customEmissiveTextureSelector) {
  107858. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  107859. }
  107860. else {
  107861. if (material) {
  107862. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107863. if (this._emissiveTextureAndColor.texture) {
  107864. textureLevel = this._emissiveTextureAndColor.texture.level;
  107865. }
  107866. }
  107867. else {
  107868. this._emissiveTextureAndColor.texture = null;
  107869. }
  107870. }
  107871. if (this.customEmissiveColorSelector) {
  107872. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  107873. }
  107874. else {
  107875. if (material.emissiveColor) {
  107876. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  107877. }
  107878. else {
  107879. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107880. }
  107881. }
  107882. };
  107883. /**
  107884. * Returns true if the mesh should render, otherwise false.
  107885. * @param mesh The mesh to render
  107886. * @returns true if it should render otherwise false
  107887. */
  107888. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  107889. return this.hasMesh(mesh);
  107890. };
  107891. /**
  107892. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  107893. * @param mesh The mesh to exclude from the glow layer
  107894. */
  107895. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  107896. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  107897. this._excludedMeshes.push(mesh.uniqueId);
  107898. }
  107899. };
  107900. /**
  107901. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  107902. * @param mesh The mesh to remove
  107903. */
  107904. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  107905. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  107906. if (index !== -1) {
  107907. this._excludedMeshes.splice(index, 1);
  107908. }
  107909. };
  107910. /**
  107911. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  107912. * @param mesh The mesh to include in the glow layer
  107913. */
  107914. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  107915. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  107916. this._includedOnlyMeshes.push(mesh.uniqueId);
  107917. }
  107918. };
  107919. /**
  107920. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  107921. * @param mesh The mesh to remove
  107922. */
  107923. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  107924. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  107925. if (index !== -1) {
  107926. this._includedOnlyMeshes.splice(index, 1);
  107927. }
  107928. };
  107929. /**
  107930. * Determine if a given mesh will be used in the glow layer
  107931. * @param mesh The mesh to test
  107932. * @returns true if the mesh will be highlighted by the current glow layer
  107933. */
  107934. GlowLayer.prototype.hasMesh = function (mesh) {
  107935. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107936. return false;
  107937. }
  107938. // Included Mesh
  107939. if (this._includedOnlyMeshes.length) {
  107940. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  107941. }
  107942. ;
  107943. // Excluded Mesh
  107944. if (this._excludedMeshes.length) {
  107945. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  107946. }
  107947. ;
  107948. return true;
  107949. };
  107950. /**
  107951. * Free any resources and references associated to a mesh.
  107952. * Internal use
  107953. * @param mesh The mesh to free.
  107954. * @hidden
  107955. */
  107956. GlowLayer.prototype._disposeMesh = function (mesh) {
  107957. this.removeIncludedOnlyMesh(mesh);
  107958. this.removeExcludedMesh(mesh);
  107959. };
  107960. /**
  107961. * Gets the class name of the effect layer
  107962. * @returns the string with the class name of the effect layer
  107963. */
  107964. GlowLayer.prototype.getClassName = function () {
  107965. return "GlowLayer";
  107966. };
  107967. /**
  107968. * Serializes this glow layer
  107969. * @returns a serialized glow layer object
  107970. */
  107971. GlowLayer.prototype.serialize = function () {
  107972. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107973. serializationObject.customType = "BABYLON.GlowLayer";
  107974. var index;
  107975. // Included meshes
  107976. serializationObject.includedMeshes = [];
  107977. if (this._includedOnlyMeshes.length) {
  107978. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  107979. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  107980. if (mesh) {
  107981. serializationObject.includedMeshes.push(mesh.id);
  107982. }
  107983. }
  107984. }
  107985. // Excluded meshes
  107986. serializationObject.excludedMeshes = [];
  107987. if (this._excludedMeshes.length) {
  107988. for (index = 0; index < this._excludedMeshes.length; index++) {
  107989. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  107990. if (mesh) {
  107991. serializationObject.excludedMeshes.push(mesh.id);
  107992. }
  107993. }
  107994. }
  107995. return serializationObject;
  107996. };
  107997. /**
  107998. * Creates a Glow Layer from parsed glow layer data
  107999. * @param parsedGlowLayer defines glow layer data
  108000. * @param scene defines the current scene
  108001. * @param rootUrl defines the root URL containing the glow layer information
  108002. * @returns a parsed Glow Layer
  108003. */
  108004. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  108005. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  108006. var index;
  108007. // Excluded meshes
  108008. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  108009. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  108010. if (mesh) {
  108011. gl.addExcludedMesh(mesh);
  108012. }
  108013. }
  108014. // Included meshes
  108015. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  108016. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  108017. if (mesh) {
  108018. gl.addIncludedOnlyMesh(mesh);
  108019. }
  108020. }
  108021. return gl;
  108022. };
  108023. /**
  108024. * Effect Name of the layer.
  108025. */
  108026. GlowLayer.EffectName = "GlowLayer";
  108027. /**
  108028. * The default blur kernel size used for the glow.
  108029. */
  108030. GlowLayer.DefaultBlurKernelSize = 32;
  108031. /**
  108032. * The default texture size ratio used for the glow.
  108033. */
  108034. GlowLayer.DefaultTextureRatio = 0.5;
  108035. __decorate([
  108036. BABYLON.serialize()
  108037. ], GlowLayer.prototype, "blurKernelSize", null);
  108038. __decorate([
  108039. BABYLON.serialize()
  108040. ], GlowLayer.prototype, "intensity", null);
  108041. __decorate([
  108042. BABYLON.serialize("options")
  108043. ], GlowLayer.prototype, "_options", void 0);
  108044. return GlowLayer;
  108045. }(BABYLON.EffectLayer));
  108046. BABYLON.GlowLayer = GlowLayer;
  108047. })(BABYLON || (BABYLON = {}));
  108048. //# sourceMappingURL=babylon.glowLayer.js.map
  108049. var BABYLON;
  108050. (function (BABYLON) {
  108051. /**
  108052. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108053. */
  108054. var AssetTaskState;
  108055. (function (AssetTaskState) {
  108056. /**
  108057. * Initialization
  108058. */
  108059. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108060. /**
  108061. * Running
  108062. */
  108063. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108064. /**
  108065. * Done
  108066. */
  108067. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108068. /**
  108069. * Error
  108070. */
  108071. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108072. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108073. /**
  108074. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108075. */
  108076. var AbstractAssetTask = /** @class */ (function () {
  108077. /**
  108078. * Creates a new {BABYLON.AssetsManager}
  108079. * @param name defines the name of the task
  108080. */
  108081. function AbstractAssetTask(
  108082. /**
  108083. * Task name
  108084. */ name) {
  108085. this.name = name;
  108086. this._isCompleted = false;
  108087. this._taskState = AssetTaskState.INIT;
  108088. }
  108089. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108090. /**
  108091. * Get if the task is completed
  108092. */
  108093. get: function () {
  108094. return this._isCompleted;
  108095. },
  108096. enumerable: true,
  108097. configurable: true
  108098. });
  108099. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  108100. /**
  108101. * Gets the current state of the task
  108102. */
  108103. get: function () {
  108104. return this._taskState;
  108105. },
  108106. enumerable: true,
  108107. configurable: true
  108108. });
  108109. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  108110. /**
  108111. * Gets the current error object (if task is in error)
  108112. */
  108113. get: function () {
  108114. return this._errorObject;
  108115. },
  108116. enumerable: true,
  108117. configurable: true
  108118. });
  108119. /**
  108120. * Internal only
  108121. * @hidden
  108122. */
  108123. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  108124. if (this._errorObject) {
  108125. return;
  108126. }
  108127. this._errorObject = {
  108128. message: message,
  108129. exception: exception
  108130. };
  108131. };
  108132. /**
  108133. * Execute the current task
  108134. * @param scene defines the scene where you want your assets to be loaded
  108135. * @param onSuccess is a callback called when the task is successfully executed
  108136. * @param onError is a callback called if an error occurs
  108137. */
  108138. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108139. var _this = this;
  108140. this._taskState = AssetTaskState.RUNNING;
  108141. this.runTask(scene, function () {
  108142. _this.onDoneCallback(onSuccess, onError);
  108143. }, function (msg, exception) {
  108144. _this.onErrorCallback(onError, msg, exception);
  108145. });
  108146. };
  108147. /**
  108148. * Execute the current task
  108149. * @param scene defines the scene where you want your assets to be loaded
  108150. * @param onSuccess is a callback called when the task is successfully executed
  108151. * @param onError is a callback called if an error occurs
  108152. */
  108153. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108154. throw new Error("runTask is not implemented");
  108155. };
  108156. /**
  108157. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  108158. * This can be used with failed tasks that have the reason for failure fixed.
  108159. */
  108160. AbstractAssetTask.prototype.reset = function () {
  108161. this._taskState = AssetTaskState.INIT;
  108162. };
  108163. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  108164. this._taskState = AssetTaskState.ERROR;
  108165. this._errorObject = {
  108166. message: message,
  108167. exception: exception
  108168. };
  108169. if (this.onError) {
  108170. this.onError(this, message, exception);
  108171. }
  108172. onError();
  108173. };
  108174. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  108175. try {
  108176. this._taskState = AssetTaskState.DONE;
  108177. this._isCompleted = true;
  108178. if (this.onSuccess) {
  108179. this.onSuccess(this);
  108180. }
  108181. onSuccess();
  108182. }
  108183. catch (e) {
  108184. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  108185. }
  108186. };
  108187. return AbstractAssetTask;
  108188. }());
  108189. BABYLON.AbstractAssetTask = AbstractAssetTask;
  108190. /**
  108191. * Class used to share progress information about assets loading
  108192. */
  108193. var AssetsProgressEvent = /** @class */ (function () {
  108194. /**
  108195. * Creates a {BABYLON.AssetsProgressEvent}
  108196. * @param remainingCount defines the number of remaining tasks to process
  108197. * @param totalCount defines the total number of tasks
  108198. * @param task defines the task that was just processed
  108199. */
  108200. function AssetsProgressEvent(remainingCount, totalCount, task) {
  108201. this.remainingCount = remainingCount;
  108202. this.totalCount = totalCount;
  108203. this.task = task;
  108204. }
  108205. return AssetsProgressEvent;
  108206. }());
  108207. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  108208. /**
  108209. * Define a task used by {BABYLON.AssetsManager} to load meshes
  108210. */
  108211. var MeshAssetTask = /** @class */ (function (_super) {
  108212. __extends(MeshAssetTask, _super);
  108213. /**
  108214. * Creates a new {BABYLON.MeshAssetTask}
  108215. * @param name defines the name of the task
  108216. * @param meshesNames defines the list of mesh's names you want to load
  108217. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  108218. * @param sceneFilename defines the filename of the scene to load from
  108219. */
  108220. function MeshAssetTask(
  108221. /**
  108222. * Defines the name of the task
  108223. */
  108224. name,
  108225. /**
  108226. * Defines the list of mesh's names you want to load
  108227. */
  108228. meshesNames,
  108229. /**
  108230. * Defines the root url to use as a base to load your meshes and associated resources
  108231. */
  108232. rootUrl,
  108233. /**
  108234. * Defines the filename of the scene to load from
  108235. */
  108236. sceneFilename) {
  108237. var _this = _super.call(this, name) || this;
  108238. _this.name = name;
  108239. _this.meshesNames = meshesNames;
  108240. _this.rootUrl = rootUrl;
  108241. _this.sceneFilename = sceneFilename;
  108242. return _this;
  108243. }
  108244. /**
  108245. * Execute the current task
  108246. * @param scene defines the scene where you want your assets to be loaded
  108247. * @param onSuccess is a callback called when the task is successfully executed
  108248. * @param onError is a callback called if an error occurs
  108249. */
  108250. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108251. var _this = this;
  108252. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  108253. _this.loadedMeshes = meshes;
  108254. _this.loadedParticleSystems = particleSystems;
  108255. _this.loadedSkeletons = skeletons;
  108256. onSuccess();
  108257. }, null, function (scene, message, exception) {
  108258. onError(message, exception);
  108259. });
  108260. };
  108261. return MeshAssetTask;
  108262. }(AbstractAssetTask));
  108263. BABYLON.MeshAssetTask = MeshAssetTask;
  108264. /**
  108265. * Define a task used by {BABYLON.AssetsManager} to load text content
  108266. */
  108267. var TextFileAssetTask = /** @class */ (function (_super) {
  108268. __extends(TextFileAssetTask, _super);
  108269. /**
  108270. * Creates a new TextFileAssetTask object
  108271. * @param name defines the name of the task
  108272. * @param url defines the location of the file to load
  108273. */
  108274. function TextFileAssetTask(
  108275. /**
  108276. * Defines the name of the task
  108277. */
  108278. name,
  108279. /**
  108280. * Defines the location of the file to load
  108281. */
  108282. url) {
  108283. var _this = _super.call(this, name) || this;
  108284. _this.name = name;
  108285. _this.url = url;
  108286. return _this;
  108287. }
  108288. /**
  108289. * Execute the current task
  108290. * @param scene defines the scene where you want your assets to be loaded
  108291. * @param onSuccess is a callback called when the task is successfully executed
  108292. * @param onError is a callback called if an error occurs
  108293. */
  108294. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108295. var _this = this;
  108296. scene._loadFile(this.url, function (data) {
  108297. _this.text = data;
  108298. onSuccess();
  108299. }, undefined, false, false, function (request, exception) {
  108300. if (request) {
  108301. onError(request.status + " " + request.statusText, exception);
  108302. }
  108303. });
  108304. };
  108305. return TextFileAssetTask;
  108306. }(AbstractAssetTask));
  108307. BABYLON.TextFileAssetTask = TextFileAssetTask;
  108308. /**
  108309. * Define a task used by {BABYLON.AssetsManager} to load binary data
  108310. */
  108311. var BinaryFileAssetTask = /** @class */ (function (_super) {
  108312. __extends(BinaryFileAssetTask, _super);
  108313. /**
  108314. * Creates a new BinaryFileAssetTask object
  108315. * @param name defines the name of the new task
  108316. * @param url defines the location of the file to load
  108317. */
  108318. function BinaryFileAssetTask(
  108319. /**
  108320. * Defines the name of the task
  108321. */
  108322. name,
  108323. /**
  108324. * Defines the location of the file to load
  108325. */
  108326. url) {
  108327. var _this = _super.call(this, name) || this;
  108328. _this.name = name;
  108329. _this.url = url;
  108330. return _this;
  108331. }
  108332. /**
  108333. * Execute the current task
  108334. * @param scene defines the scene where you want your assets to be loaded
  108335. * @param onSuccess is a callback called when the task is successfully executed
  108336. * @param onError is a callback called if an error occurs
  108337. */
  108338. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108339. var _this = this;
  108340. scene._loadFile(this.url, function (data) {
  108341. _this.data = data;
  108342. onSuccess();
  108343. }, undefined, true, true, function (request, exception) {
  108344. if (request) {
  108345. onError(request.status + " " + request.statusText, exception);
  108346. }
  108347. });
  108348. };
  108349. return BinaryFileAssetTask;
  108350. }(AbstractAssetTask));
  108351. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  108352. /**
  108353. * Define a task used by {BABYLON.AssetsManager} to load images
  108354. */
  108355. var ImageAssetTask = /** @class */ (function (_super) {
  108356. __extends(ImageAssetTask, _super);
  108357. /**
  108358. * Creates a new ImageAssetTask
  108359. * @param name defines the name of the task
  108360. * @param url defines the location of the image to load
  108361. */
  108362. function ImageAssetTask(
  108363. /**
  108364. * Defines the name of the task
  108365. */
  108366. name,
  108367. /**
  108368. * Defines the location of the image to load
  108369. */
  108370. url) {
  108371. var _this = _super.call(this, name) || this;
  108372. _this.name = name;
  108373. _this.url = url;
  108374. return _this;
  108375. }
  108376. /**
  108377. * Execute the current task
  108378. * @param scene defines the scene where you want your assets to be loaded
  108379. * @param onSuccess is a callback called when the task is successfully executed
  108380. * @param onError is a callback called if an error occurs
  108381. */
  108382. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108383. var _this = this;
  108384. var img = new Image();
  108385. BABYLON.Tools.SetCorsBehavior(this.url, img);
  108386. img.onload = function () {
  108387. _this.image = img;
  108388. onSuccess();
  108389. };
  108390. img.onerror = function (err) {
  108391. onError("Error loading image", err);
  108392. };
  108393. img.src = this.url;
  108394. };
  108395. return ImageAssetTask;
  108396. }(AbstractAssetTask));
  108397. BABYLON.ImageAssetTask = ImageAssetTask;
  108398. /**
  108399. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  108400. */
  108401. var TextureAssetTask = /** @class */ (function (_super) {
  108402. __extends(TextureAssetTask, _super);
  108403. /**
  108404. * Creates a new TextureAssetTask object
  108405. * @param name defines the name of the task
  108406. * @param url defines the location of the file to load
  108407. * @param noMipmap defines if mipmap should not be generated (default is false)
  108408. * @param invertY defines if texture must be inverted on Y axis (default is false)
  108409. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  108410. */
  108411. function TextureAssetTask(
  108412. /**
  108413. * Defines the name of the task
  108414. */
  108415. name,
  108416. /**
  108417. * Defines the location of the file to load
  108418. */
  108419. url,
  108420. /**
  108421. * Defines if mipmap should not be generated (default is false)
  108422. */
  108423. noMipmap,
  108424. /**
  108425. * Defines if texture must be inverted on Y axis (default is false)
  108426. */
  108427. invertY,
  108428. /**
  108429. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  108430. */
  108431. samplingMode) {
  108432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108433. var _this = _super.call(this, name) || this;
  108434. _this.name = name;
  108435. _this.url = url;
  108436. _this.noMipmap = noMipmap;
  108437. _this.invertY = invertY;
  108438. _this.samplingMode = samplingMode;
  108439. return _this;
  108440. }
  108441. /**
  108442. * Execute the current task
  108443. * @param scene defines the scene where you want your assets to be loaded
  108444. * @param onSuccess is a callback called when the task is successfully executed
  108445. * @param onError is a callback called if an error occurs
  108446. */
  108447. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108448. var onload = function () {
  108449. onSuccess();
  108450. };
  108451. var onerror = function (message, exception) {
  108452. onError(message, exception);
  108453. };
  108454. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  108455. };
  108456. return TextureAssetTask;
  108457. }(AbstractAssetTask));
  108458. BABYLON.TextureAssetTask = TextureAssetTask;
  108459. /**
  108460. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  108461. */
  108462. var CubeTextureAssetTask = /** @class */ (function (_super) {
  108463. __extends(CubeTextureAssetTask, _super);
  108464. /**
  108465. * Creates a new CubeTextureAssetTask
  108466. * @param name defines the name of the task
  108467. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  108468. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  108469. * @param noMipmap defines if mipmaps should not be generated (default is false)
  108470. * @param files defines the explicit list of files (undefined by default)
  108471. */
  108472. function CubeTextureAssetTask(
  108473. /**
  108474. * Defines the name of the task
  108475. */
  108476. name,
  108477. /**
  108478. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  108479. */
  108480. url,
  108481. /**
  108482. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  108483. */
  108484. extensions,
  108485. /**
  108486. * Defines if mipmaps should not be generated (default is false)
  108487. */
  108488. noMipmap,
  108489. /**
  108490. * Defines the explicit list of files (undefined by default)
  108491. */
  108492. files) {
  108493. var _this = _super.call(this, name) || this;
  108494. _this.name = name;
  108495. _this.url = url;
  108496. _this.extensions = extensions;
  108497. _this.noMipmap = noMipmap;
  108498. _this.files = files;
  108499. return _this;
  108500. }
  108501. /**
  108502. * Execute the current task
  108503. * @param scene defines the scene where you want your assets to be loaded
  108504. * @param onSuccess is a callback called when the task is successfully executed
  108505. * @param onError is a callback called if an error occurs
  108506. */
  108507. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  108508. var onload = function () {
  108509. onSuccess();
  108510. };
  108511. var onerror = function (message, exception) {
  108512. onError(message, exception);
  108513. };
  108514. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  108515. };
  108516. return CubeTextureAssetTask;
  108517. }(AbstractAssetTask));
  108518. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  108519. /**
  108520. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  108521. */
  108522. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  108523. __extends(HDRCubeTextureAssetTask, _super);
  108524. /**
  108525. * Creates a new HDRCubeTextureAssetTask object
  108526. * @param name defines the name of the task
  108527. * @param url defines the location of the file to load
  108528. * @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.
  108529. * @param noMipmap defines if mipmaps should not be generated (default is false)
  108530. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  108531. * @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)
  108532. * @param reserved Internal use only
  108533. */
  108534. function HDRCubeTextureAssetTask(
  108535. /**
  108536. * Defines the name of the task
  108537. */
  108538. name,
  108539. /**
  108540. * Defines the location of the file to load
  108541. */
  108542. url,
  108543. /**
  108544. * Defines the desired size (the more it increases the longer the generation will be)
  108545. */
  108546. size,
  108547. /**
  108548. * Defines if mipmaps should not be generated (default is false)
  108549. */
  108550. noMipmap,
  108551. /**
  108552. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  108553. */
  108554. generateHarmonics,
  108555. /**
  108556. * 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)
  108557. */
  108558. gammaSpace,
  108559. /**
  108560. * Internal Use Only
  108561. */
  108562. reserved) {
  108563. if (noMipmap === void 0) { noMipmap = false; }
  108564. if (generateHarmonics === void 0) { generateHarmonics = true; }
  108565. if (gammaSpace === void 0) { gammaSpace = false; }
  108566. if (reserved === void 0) { reserved = false; }
  108567. var _this = _super.call(this, name) || this;
  108568. _this.name = name;
  108569. _this.url = url;
  108570. _this.size = size;
  108571. _this.noMipmap = noMipmap;
  108572. _this.generateHarmonics = generateHarmonics;
  108573. _this.gammaSpace = gammaSpace;
  108574. _this.reserved = reserved;
  108575. return _this;
  108576. }
  108577. /**
  108578. * Execute the current task
  108579. * @param scene defines the scene where you want your assets to be loaded
  108580. * @param onSuccess is a callback called when the task is successfully executed
  108581. * @param onError is a callback called if an error occurs
  108582. */
  108583. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  108584. var onload = function () {
  108585. onSuccess();
  108586. };
  108587. var onerror = function (message, exception) {
  108588. onError(message, exception);
  108589. };
  108590. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  108591. };
  108592. return HDRCubeTextureAssetTask;
  108593. }(AbstractAssetTask));
  108594. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  108595. /**
  108596. * This class can be used to easily import assets into a scene
  108597. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  108598. */
  108599. var AssetsManager = /** @class */ (function () {
  108600. /**
  108601. * Creates a new AssetsManager
  108602. * @param scene defines the scene to work on
  108603. */
  108604. function AssetsManager(scene) {
  108605. this._isLoading = false;
  108606. this._tasks = new Array();
  108607. this._waitingTasksCount = 0;
  108608. this._totalTasksCount = 0;
  108609. /**
  108610. * Observable called when all tasks are processed
  108611. */
  108612. this.onTaskSuccessObservable = new BABYLON.Observable();
  108613. /**
  108614. * Observable called when a task had an error
  108615. */
  108616. this.onTaskErrorObservable = new BABYLON.Observable();
  108617. /**
  108618. * Observable called when a task is successful
  108619. */
  108620. this.onTasksDoneObservable = new BABYLON.Observable();
  108621. /**
  108622. * Observable called when a task is done (whatever the result is)
  108623. */
  108624. this.onProgressObservable = new BABYLON.Observable();
  108625. /**
  108626. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  108627. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  108628. */
  108629. this.useDefaultLoadingScreen = true;
  108630. this._scene = scene;
  108631. }
  108632. /**
  108633. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  108634. * @param taskName defines the name of the new task
  108635. * @param meshesNames defines the name of meshes to load
  108636. * @param rootUrl defines the root url to use to locate files
  108637. * @param sceneFilename defines the filename of the scene file
  108638. * @returns a new {BABYLON.MeshAssetTask} object
  108639. */
  108640. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  108641. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  108642. this._tasks.push(task);
  108643. return task;
  108644. };
  108645. /**
  108646. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  108647. * @param taskName defines the name of the new task
  108648. * @param url defines the url of the file to load
  108649. * @returns a new {BABYLON.TextFileAssetTask} object
  108650. */
  108651. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  108652. var task = new TextFileAssetTask(taskName, url);
  108653. this._tasks.push(task);
  108654. return task;
  108655. };
  108656. /**
  108657. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  108658. * @param taskName defines the name of the new task
  108659. * @param url defines the url of the file to load
  108660. * @returns a new {BABYLON.BinaryFileAssetTask} object
  108661. */
  108662. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  108663. var task = new BinaryFileAssetTask(taskName, url);
  108664. this._tasks.push(task);
  108665. return task;
  108666. };
  108667. /**
  108668. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  108669. * @param taskName defines the name of the new task
  108670. * @param url defines the url of the file to load
  108671. * @returns a new {BABYLON.ImageAssetTask} object
  108672. */
  108673. AssetsManager.prototype.addImageTask = function (taskName, url) {
  108674. var task = new ImageAssetTask(taskName, url);
  108675. this._tasks.push(task);
  108676. return task;
  108677. };
  108678. /**
  108679. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  108680. * @param taskName defines the name of the new task
  108681. * @param url defines the url of the file to load
  108682. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108683. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  108684. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  108685. * @returns a new {BABYLON.TextureAssetTask} object
  108686. */
  108687. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  108688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108689. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  108690. this._tasks.push(task);
  108691. return task;
  108692. };
  108693. /**
  108694. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  108695. * @param taskName defines the name of the new task
  108696. * @param url defines the url of the file to load
  108697. * @param extensions defines the extension to use to load the cube map (can be null)
  108698. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108699. * @param files defines the list of files to load (can be null)
  108700. * @returns a new {BABYLON.CubeTextureAssetTask} object
  108701. */
  108702. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  108703. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  108704. this._tasks.push(task);
  108705. return task;
  108706. };
  108707. /**
  108708. *
  108709. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  108710. * @param taskName defines the name of the new task
  108711. * @param url defines the url of the file to load
  108712. * @param size defines the size you want for the cubemap (can be null)
  108713. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  108714. * @param generateHarmonics defines if you want to automatically generate (true by default)
  108715. * @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)
  108716. * @param reserved Internal use only
  108717. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  108718. */
  108719. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  108720. if (noMipmap === void 0) { noMipmap = false; }
  108721. if (generateHarmonics === void 0) { generateHarmonics = true; }
  108722. if (gammaSpace === void 0) { gammaSpace = false; }
  108723. if (reserved === void 0) { reserved = false; }
  108724. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  108725. this._tasks.push(task);
  108726. return task;
  108727. };
  108728. /**
  108729. * Remove a task from the assets manager.
  108730. * @param task the task to remove
  108731. */
  108732. AssetsManager.prototype.removeTask = function (task) {
  108733. var index = this._tasks.indexOf(task);
  108734. if (index > -1) {
  108735. this._tasks.splice(index, 1);
  108736. }
  108737. };
  108738. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  108739. this._waitingTasksCount--;
  108740. try {
  108741. if (this.onProgress) {
  108742. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  108743. }
  108744. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  108745. }
  108746. catch (e) {
  108747. BABYLON.Tools.Error("Error running progress callbacks.");
  108748. console.log(e);
  108749. }
  108750. if (this._waitingTasksCount === 0) {
  108751. try {
  108752. if (this.onFinish) {
  108753. this.onFinish(this._tasks);
  108754. }
  108755. // Let's remove successfull tasks
  108756. var currentTasks = this._tasks.slice();
  108757. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  108758. var task = currentTasks_1[_i];
  108759. if (task.taskState === AssetTaskState.DONE) {
  108760. var index = this._tasks.indexOf(task);
  108761. if (index > -1) {
  108762. this._tasks.splice(index, 1);
  108763. }
  108764. }
  108765. }
  108766. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108767. }
  108768. catch (e) {
  108769. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  108770. console.log(e);
  108771. }
  108772. this._isLoading = false;
  108773. this._scene.getEngine().hideLoadingUI();
  108774. }
  108775. };
  108776. AssetsManager.prototype._runTask = function (task) {
  108777. var _this = this;
  108778. var done = function () {
  108779. try {
  108780. if (_this.onTaskSuccess) {
  108781. _this.onTaskSuccess(task);
  108782. }
  108783. _this.onTaskSuccessObservable.notifyObservers(task);
  108784. _this._decreaseWaitingTasksCount(task);
  108785. }
  108786. catch (e) {
  108787. error("Error executing task success callbacks", e);
  108788. }
  108789. };
  108790. var error = function (message, exception) {
  108791. task._setErrorObject(message, exception);
  108792. if (_this.onTaskError) {
  108793. _this.onTaskError(task);
  108794. }
  108795. _this.onTaskErrorObservable.notifyObservers(task);
  108796. _this._decreaseWaitingTasksCount(task);
  108797. };
  108798. task.run(this._scene, done, error);
  108799. };
  108800. /**
  108801. * Reset the {BABYLON.AssetsManager} and remove all tasks
  108802. * @return the current instance of the {BABYLON.AssetsManager}
  108803. */
  108804. AssetsManager.prototype.reset = function () {
  108805. this._isLoading = false;
  108806. this._tasks = new Array();
  108807. return this;
  108808. };
  108809. /**
  108810. * Start the loading process
  108811. * @return the current instance of the {BABYLON.AssetsManager}
  108812. */
  108813. AssetsManager.prototype.load = function () {
  108814. if (this._isLoading) {
  108815. return this;
  108816. }
  108817. this._isLoading = true;
  108818. this._waitingTasksCount = this._tasks.length;
  108819. this._totalTasksCount = this._tasks.length;
  108820. if (this._waitingTasksCount === 0) {
  108821. this._isLoading = false;
  108822. if (this.onFinish) {
  108823. this.onFinish(this._tasks);
  108824. }
  108825. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108826. return this;
  108827. }
  108828. if (this.useDefaultLoadingScreen) {
  108829. this._scene.getEngine().displayLoadingUI();
  108830. }
  108831. for (var index = 0; index < this._tasks.length; index++) {
  108832. var task = this._tasks[index];
  108833. if (task.taskState === AssetTaskState.INIT) {
  108834. this._runTask(task);
  108835. }
  108836. }
  108837. return this;
  108838. };
  108839. return AssetsManager;
  108840. }());
  108841. BABYLON.AssetsManager = AssetsManager;
  108842. })(BABYLON || (BABYLON = {}));
  108843. //# sourceMappingURL=babylon.assetsManager.js.map
  108844. var BABYLON;
  108845. (function (BABYLON) {
  108846. var serializedGeometries = [];
  108847. var serializeGeometry = function (geometry, serializationGeometries) {
  108848. if (serializedGeometries[geometry.id]) {
  108849. return;
  108850. }
  108851. if (geometry.doNotSerialize) {
  108852. return;
  108853. }
  108854. if (geometry instanceof BABYLON.BoxGeometry) {
  108855. serializationGeometries.boxes.push(geometry.serialize());
  108856. }
  108857. else if (geometry instanceof BABYLON.SphereGeometry) {
  108858. serializationGeometries.spheres.push(geometry.serialize());
  108859. }
  108860. else if (geometry instanceof BABYLON.CylinderGeometry) {
  108861. serializationGeometries.cylinders.push(geometry.serialize());
  108862. }
  108863. else if (geometry instanceof BABYLON.TorusGeometry) {
  108864. serializationGeometries.toruses.push(geometry.serialize());
  108865. }
  108866. else if (geometry instanceof BABYLON.GroundGeometry) {
  108867. serializationGeometries.grounds.push(geometry.serialize());
  108868. }
  108869. else if (geometry instanceof BABYLON.Plane) {
  108870. serializationGeometries.planes.push(geometry.serialize());
  108871. }
  108872. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  108873. serializationGeometries.torusKnots.push(geometry.serialize());
  108874. }
  108875. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  108876. throw new Error("Unknown primitive type");
  108877. }
  108878. else {
  108879. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  108880. }
  108881. serializedGeometries[geometry.id] = true;
  108882. };
  108883. var serializeMesh = function (mesh, serializationScene) {
  108884. var serializationObject = {};
  108885. // Geometry
  108886. var geometry = mesh._geometry;
  108887. if (geometry) {
  108888. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  108889. // 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
  108890. serializeGeometry(geometry, serializationScene.geometries);
  108891. }
  108892. }
  108893. // Custom
  108894. if (mesh.serialize) {
  108895. mesh.serialize(serializationObject);
  108896. }
  108897. return serializationObject;
  108898. };
  108899. var finalizeSingleMesh = function (mesh, serializationObject) {
  108900. //only works if the mesh is already loaded
  108901. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108902. //serialize material
  108903. if (mesh.material) {
  108904. if (mesh.material instanceof BABYLON.MultiMaterial) {
  108905. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  108906. serializationObject.materials = serializationObject.materials || [];
  108907. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108908. serializationObject.multiMaterials.push(mesh.material.serialize());
  108909. var _loop_1 = function (submaterial) {
  108910. if (submaterial) {
  108911. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  108912. serializationObject.materials.push(submaterial.serialize());
  108913. }
  108914. }
  108915. };
  108916. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  108917. var submaterial = _a[_i];
  108918. _loop_1(submaterial);
  108919. }
  108920. }
  108921. }
  108922. else {
  108923. serializationObject.materials = serializationObject.materials || [];
  108924. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108925. serializationObject.materials.push(mesh.material.serialize());
  108926. }
  108927. }
  108928. }
  108929. //serialize geometry
  108930. var geometry = mesh._geometry;
  108931. if (geometry) {
  108932. if (!serializationObject.geometries) {
  108933. serializationObject.geometries = {};
  108934. serializationObject.geometries.boxes = [];
  108935. serializationObject.geometries.spheres = [];
  108936. serializationObject.geometries.cylinders = [];
  108937. serializationObject.geometries.toruses = [];
  108938. serializationObject.geometries.grounds = [];
  108939. serializationObject.geometries.planes = [];
  108940. serializationObject.geometries.torusKnots = [];
  108941. serializationObject.geometries.vertexData = [];
  108942. }
  108943. serializeGeometry(geometry, serializationObject.geometries);
  108944. }
  108945. // Skeletons
  108946. if (mesh.skeleton) {
  108947. serializationObject.skeletons = serializationObject.skeletons || [];
  108948. serializationObject.skeletons.push(mesh.skeleton.serialize());
  108949. }
  108950. //serialize the actual mesh
  108951. serializationObject.meshes = serializationObject.meshes || [];
  108952. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108953. }
  108954. };
  108955. /**
  108956. * Class used to serialize a scene into a string
  108957. */
  108958. var SceneSerializer = /** @class */ (function () {
  108959. function SceneSerializer() {
  108960. }
  108961. /**
  108962. * Clear cache used by a previous serialization
  108963. */
  108964. SceneSerializer.ClearCache = function () {
  108965. serializedGeometries = [];
  108966. };
  108967. /**
  108968. * Serialize a scene into a JSON compatible object
  108969. * @param scene defines the scene to serialize
  108970. * @returns a JSON compatible object
  108971. */
  108972. SceneSerializer.Serialize = function (scene) {
  108973. var serializationObject = {};
  108974. SceneSerializer.ClearCache();
  108975. // Scene
  108976. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  108977. serializationObject.autoClear = scene.autoClear;
  108978. serializationObject.clearColor = scene.clearColor.asArray();
  108979. serializationObject.ambientColor = scene.ambientColor.asArray();
  108980. serializationObject.gravity = scene.gravity.asArray();
  108981. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  108982. serializationObject.workerCollisions = scene.workerCollisions;
  108983. // Fog
  108984. if (scene.fogMode && scene.fogMode !== 0) {
  108985. serializationObject.fogMode = scene.fogMode;
  108986. serializationObject.fogColor = scene.fogColor.asArray();
  108987. serializationObject.fogStart = scene.fogStart;
  108988. serializationObject.fogEnd = scene.fogEnd;
  108989. serializationObject.fogDensity = scene.fogDensity;
  108990. }
  108991. //Physics
  108992. if (scene.isPhysicsEnabled()) {
  108993. var physicEngine = scene.getPhysicsEngine();
  108994. if (physicEngine) {
  108995. serializationObject.physicsEnabled = true;
  108996. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  108997. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  108998. }
  108999. }
  109000. // Metadata
  109001. if (scene.metadata) {
  109002. serializationObject.metadata = scene.metadata;
  109003. }
  109004. // Morph targets
  109005. serializationObject.morphTargetManagers = [];
  109006. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  109007. var abstractMesh = _a[_i];
  109008. var manager = abstractMesh.morphTargetManager;
  109009. if (manager) {
  109010. serializationObject.morphTargetManagers.push(manager.serialize());
  109011. }
  109012. }
  109013. // Lights
  109014. serializationObject.lights = [];
  109015. var index;
  109016. var light;
  109017. for (index = 0; index < scene.lights.length; index++) {
  109018. light = scene.lights[index];
  109019. if (!light.doNotSerialize) {
  109020. serializationObject.lights.push(light.serialize());
  109021. }
  109022. }
  109023. // Cameras
  109024. serializationObject.cameras = [];
  109025. for (index = 0; index < scene.cameras.length; index++) {
  109026. var camera = scene.cameras[index];
  109027. if (!camera.doNotSerialize) {
  109028. serializationObject.cameras.push(camera.serialize());
  109029. }
  109030. }
  109031. if (scene.activeCamera) {
  109032. serializationObject.activeCameraID = scene.activeCamera.id;
  109033. }
  109034. // Animations
  109035. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109036. // Materials
  109037. serializationObject.materials = [];
  109038. serializationObject.multiMaterials = [];
  109039. var material;
  109040. for (index = 0; index < scene.materials.length; index++) {
  109041. material = scene.materials[index];
  109042. if (!material.doNotSerialize) {
  109043. serializationObject.materials.push(material.serialize());
  109044. }
  109045. }
  109046. // MultiMaterials
  109047. serializationObject.multiMaterials = [];
  109048. for (index = 0; index < scene.multiMaterials.length; index++) {
  109049. var multiMaterial = scene.multiMaterials[index];
  109050. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109051. }
  109052. // Environment texture
  109053. if (scene.environmentTexture) {
  109054. serializationObject.environmentTexture = scene.environmentTexture.name;
  109055. }
  109056. // Skeletons
  109057. serializationObject.skeletons = [];
  109058. for (index = 0; index < scene.skeletons.length; index++) {
  109059. var skeleton = scene.skeletons[index];
  109060. if (!skeleton.doNotSerialize) {
  109061. serializationObject.skeletons.push(skeleton.serialize());
  109062. }
  109063. }
  109064. // Transform nodes
  109065. serializationObject.transformNodes = [];
  109066. for (index = 0; index < scene.transformNodes.length; index++) {
  109067. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109068. }
  109069. // Geometries
  109070. serializationObject.geometries = {};
  109071. serializationObject.geometries.boxes = [];
  109072. serializationObject.geometries.spheres = [];
  109073. serializationObject.geometries.cylinders = [];
  109074. serializationObject.geometries.toruses = [];
  109075. serializationObject.geometries.grounds = [];
  109076. serializationObject.geometries.planes = [];
  109077. serializationObject.geometries.torusKnots = [];
  109078. serializationObject.geometries.vertexData = [];
  109079. serializedGeometries = [];
  109080. var geometries = scene.getGeometries();
  109081. for (index = 0; index < geometries.length; index++) {
  109082. var geometry = geometries[index];
  109083. if (geometry.isReady()) {
  109084. serializeGeometry(geometry, serializationObject.geometries);
  109085. }
  109086. }
  109087. // Meshes
  109088. serializationObject.meshes = [];
  109089. for (index = 0; index < scene.meshes.length; index++) {
  109090. var abstractMesh = scene.meshes[index];
  109091. if (abstractMesh instanceof BABYLON.Mesh) {
  109092. var mesh = abstractMesh;
  109093. if (!mesh.doNotSerialize) {
  109094. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109095. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109096. }
  109097. }
  109098. }
  109099. }
  109100. // Particles Systems
  109101. serializationObject.particleSystems = [];
  109102. for (index = 0; index < scene.particleSystems.length; index++) {
  109103. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  109104. }
  109105. // Action Manager
  109106. if (scene.actionManager) {
  109107. serializationObject.actions = scene.actionManager.serialize("scene");
  109108. }
  109109. // Components
  109110. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  109111. var component = _c[_b];
  109112. component.serialize(serializationObject);
  109113. }
  109114. return serializationObject;
  109115. };
  109116. /**
  109117. * Serialize a mesh into a JSON compatible object
  109118. * @param toSerialize defines the mesh to serialize
  109119. * @param withParents defines if parents must be serialized as well
  109120. * @param withChildren defines if children must be serialized as well
  109121. * @returns a JSON compatible object
  109122. */
  109123. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  109124. if (withParents === void 0) { withParents = false; }
  109125. if (withChildren === void 0) { withChildren = false; }
  109126. var serializationObject = {};
  109127. SceneSerializer.ClearCache();
  109128. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  109129. if (withParents || withChildren) {
  109130. //deliberate for loop! not for each, appended should be processed as well.
  109131. for (var i = 0; i < toSerialize.length; ++i) {
  109132. if (withChildren) {
  109133. toSerialize[i].getDescendants().forEach(function (node) {
  109134. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  109135. toSerialize.push(node);
  109136. }
  109137. });
  109138. }
  109139. //make sure the array doesn't contain the object already
  109140. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  109141. toSerialize.push(toSerialize[i].parent);
  109142. }
  109143. }
  109144. }
  109145. toSerialize.forEach(function (mesh) {
  109146. finalizeSingleMesh(mesh, serializationObject);
  109147. });
  109148. return serializationObject;
  109149. };
  109150. return SceneSerializer;
  109151. }());
  109152. BABYLON.SceneSerializer = SceneSerializer;
  109153. })(BABYLON || (BABYLON = {}));
  109154. //# sourceMappingURL=babylon.sceneSerializer.js.map
  109155. var BABYLON;
  109156. (function (BABYLON) {
  109157. /**
  109158. * Class used to generate realtime reflection / refraction cube textures
  109159. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  109160. */
  109161. var ReflectionProbe = /** @class */ (function () {
  109162. /**
  109163. * Creates a new reflection probe
  109164. * @param name defines the name of the probe
  109165. * @param size defines the texture resolution (for each face)
  109166. * @param scene defines the hosting scene
  109167. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  109168. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  109169. */
  109170. function ReflectionProbe(
  109171. /** defines the name of the probe */
  109172. name, size, scene, generateMipMaps, useFloat) {
  109173. if (generateMipMaps === void 0) { generateMipMaps = true; }
  109174. if (useFloat === void 0) { useFloat = false; }
  109175. var _this = this;
  109176. this.name = name;
  109177. this._viewMatrix = BABYLON.Matrix.Identity();
  109178. this._target = BABYLON.Vector3.Zero();
  109179. this._add = BABYLON.Vector3.Zero();
  109180. this._invertYAxis = false;
  109181. /** Gets or sets probe position (center of the cube map) */
  109182. this.position = BABYLON.Vector3.Zero();
  109183. this._scene = scene;
  109184. // Create the scene field if not exist.
  109185. if (!this._scene.reflectionProbes) {
  109186. this._scene.reflectionProbes = new Array();
  109187. }
  109188. this._scene.reflectionProbes.push(this);
  109189. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  109190. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  109191. switch (faceIndex) {
  109192. case 0:
  109193. _this._add.copyFromFloats(1, 0, 0);
  109194. break;
  109195. case 1:
  109196. _this._add.copyFromFloats(-1, 0, 0);
  109197. break;
  109198. case 2:
  109199. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  109200. break;
  109201. case 3:
  109202. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  109203. break;
  109204. case 4:
  109205. _this._add.copyFromFloats(0, 0, 1);
  109206. break;
  109207. case 5:
  109208. _this._add.copyFromFloats(0, 0, -1);
  109209. break;
  109210. }
  109211. if (_this._attachedMesh) {
  109212. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  109213. }
  109214. _this.position.addToRef(_this._add, _this._target);
  109215. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  109216. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  109217. scene._forcedViewPosition = _this.position;
  109218. });
  109219. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  109220. scene._forcedViewPosition = null;
  109221. scene.updateTransformMatrix(true);
  109222. });
  109223. if (scene.activeCamera) {
  109224. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  109225. }
  109226. }
  109227. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  109228. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  109229. get: function () {
  109230. return this._renderTargetTexture.samples;
  109231. },
  109232. set: function (value) {
  109233. this._renderTargetTexture.samples = value;
  109234. },
  109235. enumerable: true,
  109236. configurable: true
  109237. });
  109238. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  109239. /** Gets or sets the refresh rate to use (on every frame by default) */
  109240. get: function () {
  109241. return this._renderTargetTexture.refreshRate;
  109242. },
  109243. set: function (value) {
  109244. this._renderTargetTexture.refreshRate = value;
  109245. },
  109246. enumerable: true,
  109247. configurable: true
  109248. });
  109249. /**
  109250. * Gets the hosting scene
  109251. * @returns a Scene
  109252. */
  109253. ReflectionProbe.prototype.getScene = function () {
  109254. return this._scene;
  109255. };
  109256. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  109257. /** Gets the internal CubeTexture used to render to */
  109258. get: function () {
  109259. return this._renderTargetTexture;
  109260. },
  109261. enumerable: true,
  109262. configurable: true
  109263. });
  109264. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  109265. /** Gets the list of meshes to render */
  109266. get: function () {
  109267. return this._renderTargetTexture.renderList;
  109268. },
  109269. enumerable: true,
  109270. configurable: true
  109271. });
  109272. /**
  109273. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  109274. * @param mesh defines the mesh to attach to
  109275. */
  109276. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  109277. this._attachedMesh = mesh;
  109278. };
  109279. /**
  109280. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  109281. * @param renderingGroupId The rendering group id corresponding to its index
  109282. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  109283. */
  109284. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  109285. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  109286. };
  109287. /**
  109288. * Clean all associated resources
  109289. */
  109290. ReflectionProbe.prototype.dispose = function () {
  109291. var index = this._scene.reflectionProbes.indexOf(this);
  109292. if (index !== -1) {
  109293. // Remove from the scene if found
  109294. this._scene.reflectionProbes.splice(index, 1);
  109295. }
  109296. if (this._renderTargetTexture) {
  109297. this._renderTargetTexture.dispose();
  109298. this._renderTargetTexture = null;
  109299. }
  109300. };
  109301. return ReflectionProbe;
  109302. }());
  109303. BABYLON.ReflectionProbe = ReflectionProbe;
  109304. })(BABYLON || (BABYLON = {}));
  109305. //# sourceMappingURL=babylon.reflectionProbe.js.map
  109306. var BABYLON;
  109307. (function (BABYLON) {
  109308. /**
  109309. * Defines the layer scene component responsible to manage any layers
  109310. * in a given scene.
  109311. */
  109312. var LayerSceneComponent = /** @class */ (function () {
  109313. /**
  109314. * Creates a new instance of the component for the given scene
  109315. * @param scene Defines the scene to register the component in
  109316. */
  109317. function LayerSceneComponent(scene) {
  109318. /**
  109319. * The component name helpfull to identify the component in the list of scene components.
  109320. */
  109321. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  109322. this.scene = scene;
  109323. this._engine = scene.getEngine();
  109324. scene.layers = new Array();
  109325. }
  109326. /**
  109327. * Registers the component in a given scene
  109328. */
  109329. LayerSceneComponent.prototype.register = function () {
  109330. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  109331. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  109332. };
  109333. /**
  109334. * Rebuilds the elements related to this component in case of
  109335. * context lost for instance.
  109336. */
  109337. LayerSceneComponent.prototype.rebuild = function () {
  109338. var layers = this.scene.layers;
  109339. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  109340. var layer = layers_1[_i];
  109341. layer._rebuild();
  109342. }
  109343. };
  109344. /**
  109345. * Disposes the component and the associated ressources.
  109346. */
  109347. LayerSceneComponent.prototype.dispose = function () {
  109348. var layers = this.scene.layers;
  109349. while (layers.length) {
  109350. layers[0].dispose();
  109351. }
  109352. };
  109353. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  109354. var layers = this.scene.layers;
  109355. if (layers.length) {
  109356. this._engine.setDepthBuffer(false);
  109357. var cameraLayerMask = camera.layerMask;
  109358. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  109359. var layer = layers_2[_i];
  109360. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  109361. layer.render();
  109362. }
  109363. }
  109364. this._engine.setDepthBuffer(true);
  109365. }
  109366. };
  109367. LayerSceneComponent.prototype._drawBackground = function (camera) {
  109368. this._draw(camera, true);
  109369. };
  109370. LayerSceneComponent.prototype._drawForeground = function (camera) {
  109371. this._draw(camera, false);
  109372. };
  109373. return LayerSceneComponent;
  109374. }());
  109375. BABYLON.LayerSceneComponent = LayerSceneComponent;
  109376. })(BABYLON || (BABYLON = {}));
  109377. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  109378. var BABYLON;
  109379. (function (BABYLON) {
  109380. /**
  109381. * This represents a full screen 2d layer.
  109382. * This can be usefull to display a picture in the background of your scene for instance.
  109383. * @see https://www.babylonjs-playground.com/#08A2BS#1
  109384. */
  109385. var Layer = /** @class */ (function () {
  109386. /**
  109387. * Instantiates a new layer.
  109388. * This represents a full screen 2d layer.
  109389. * This can be usefull to display a picture in the background of your scene for instance.
  109390. * @see https://www.babylonjs-playground.com/#08A2BS#1
  109391. * @param name Define the name of the layer in the scene
  109392. * @param imgUrl Define the url of the texture to display in the layer
  109393. * @param scene Define the scene the layer belongs to
  109394. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  109395. * @param color Defines a color for the layer
  109396. */
  109397. function Layer(
  109398. /**
  109399. * Define the name of the layer.
  109400. */
  109401. name, imgUrl, scene, isBackground, color) {
  109402. this.name = name;
  109403. /**
  109404. * Define the scale of the layer in order to zoom in out of the texture.
  109405. */
  109406. this.scale = new BABYLON.Vector2(1, 1);
  109407. /**
  109408. * Define an offset for the layer in order to shift the texture.
  109409. */
  109410. this.offset = new BABYLON.Vector2(0, 0);
  109411. /**
  109412. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  109413. */
  109414. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  109415. /**
  109416. * Define a mask to restrict the layer to only some of the scene cameras.
  109417. */
  109418. this.layerMask = 0x0FFFFFFF;
  109419. this._vertexBuffers = {};
  109420. /**
  109421. * An event triggered when the layer is disposed.
  109422. */
  109423. this.onDisposeObservable = new BABYLON.Observable();
  109424. /**
  109425. * An event triggered before rendering the scene
  109426. */
  109427. this.onBeforeRenderObservable = new BABYLON.Observable();
  109428. /**
  109429. * An event triggered after rendering the scene
  109430. */
  109431. this.onAfterRenderObservable = new BABYLON.Observable();
  109432. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  109433. this.isBackground = isBackground === undefined ? true : isBackground;
  109434. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  109435. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  109436. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  109437. if (!layerComponent) {
  109438. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  109439. this._scene._addComponent(layerComponent);
  109440. }
  109441. this._scene.layers.push(this);
  109442. var engine = this._scene.getEngine();
  109443. // VBO
  109444. var vertices = [];
  109445. vertices.push(1, 1);
  109446. vertices.push(-1, 1);
  109447. vertices.push(-1, -1);
  109448. vertices.push(1, -1);
  109449. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109450. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109451. this._createIndexBuffer();
  109452. // Effects
  109453. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  109454. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  109455. }
  109456. Object.defineProperty(Layer.prototype, "onDispose", {
  109457. /**
  109458. * Back compatibility with callback before the onDisposeObservable existed.
  109459. * The set callback will be triggered when the layer has been disposed.
  109460. */
  109461. set: function (callback) {
  109462. if (this._onDisposeObserver) {
  109463. this.onDisposeObservable.remove(this._onDisposeObserver);
  109464. }
  109465. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  109466. },
  109467. enumerable: true,
  109468. configurable: true
  109469. });
  109470. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  109471. /**
  109472. * Back compatibility with callback before the onBeforeRenderObservable existed.
  109473. * The set callback will be triggered just before rendering the layer.
  109474. */
  109475. set: function (callback) {
  109476. if (this._onBeforeRenderObserver) {
  109477. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  109478. }
  109479. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  109480. },
  109481. enumerable: true,
  109482. configurable: true
  109483. });
  109484. Object.defineProperty(Layer.prototype, "onAfterRender", {
  109485. /**
  109486. * Back compatibility with callback before the onAfterRenderObservable existed.
  109487. * The set callback will be triggered just after rendering the layer.
  109488. */
  109489. set: function (callback) {
  109490. if (this._onAfterRenderObserver) {
  109491. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109492. }
  109493. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  109494. },
  109495. enumerable: true,
  109496. configurable: true
  109497. });
  109498. Layer.prototype._createIndexBuffer = function () {
  109499. var engine = this._scene.getEngine();
  109500. // Indices
  109501. var indices = [];
  109502. indices.push(0);
  109503. indices.push(1);
  109504. indices.push(2);
  109505. indices.push(0);
  109506. indices.push(2);
  109507. indices.push(3);
  109508. this._indexBuffer = engine.createIndexBuffer(indices);
  109509. };
  109510. /** @hidden */
  109511. Layer.prototype._rebuild = function () {
  109512. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109513. if (vb) {
  109514. vb._rebuild();
  109515. }
  109516. this._createIndexBuffer();
  109517. };
  109518. /**
  109519. * Renders the layer in the scene.
  109520. */
  109521. Layer.prototype.render = function () {
  109522. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  109523. // Check
  109524. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  109525. return;
  109526. var engine = this._scene.getEngine();
  109527. this.onBeforeRenderObservable.notifyObservers(this);
  109528. // Render
  109529. engine.enableEffect(currentEffect);
  109530. engine.setState(false);
  109531. // Texture
  109532. currentEffect.setTexture("textureSampler", this.texture);
  109533. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  109534. // Color
  109535. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  109536. // Scale / offset
  109537. currentEffect.setVector2("offset", this.offset);
  109538. currentEffect.setVector2("scale", this.scale);
  109539. // VBOs
  109540. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109541. // Draw order
  109542. if (!this.alphaTest) {
  109543. engine.setAlphaMode(this.alphaBlendingMode);
  109544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109545. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  109546. }
  109547. else {
  109548. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109549. }
  109550. this.onAfterRenderObservable.notifyObservers(this);
  109551. };
  109552. /**
  109553. * Disposes and releases the associated ressources.
  109554. */
  109555. Layer.prototype.dispose = function () {
  109556. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109557. if (vertexBuffer) {
  109558. vertexBuffer.dispose();
  109559. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109560. }
  109561. if (this._indexBuffer) {
  109562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109563. this._indexBuffer = null;
  109564. }
  109565. if (this.texture) {
  109566. this.texture.dispose();
  109567. this.texture = null;
  109568. }
  109569. // Remove from scene
  109570. var index = this._scene.layers.indexOf(this);
  109571. this._scene.layers.splice(index, 1);
  109572. // Callback
  109573. this.onDisposeObservable.notifyObservers(this);
  109574. this.onDisposeObservable.clear();
  109575. this.onAfterRenderObservable.clear();
  109576. this.onBeforeRenderObservable.clear();
  109577. };
  109578. return Layer;
  109579. }());
  109580. BABYLON.Layer = Layer;
  109581. })(BABYLON || (BABYLON = {}));
  109582. //# sourceMappingURL=babylon.layer.js.map
  109583. var BABYLON;
  109584. (function (BABYLON) {
  109585. /**
  109586. * Class used to host texture specific utilities
  109587. */
  109588. var TextureTools = /** @class */ (function () {
  109589. function TextureTools() {
  109590. }
  109591. /**
  109592. * Uses the GPU to create a copy texture rescaled at a given size
  109593. * @param texture Texture to copy from
  109594. * @param width defines the desired width
  109595. * @param height defines the desired height
  109596. * @param useBilinearMode defines if bilinear mode has to be used
  109597. * @return the generated texture
  109598. */
  109599. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  109600. if (useBilinearMode === void 0) { useBilinearMode = true; }
  109601. var scene = texture.getScene();
  109602. var engine = scene.getEngine();
  109603. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  109604. rtt.wrapU = texture.wrapU;
  109605. rtt.wrapV = texture.wrapV;
  109606. rtt.uOffset = texture.uOffset;
  109607. rtt.vOffset = texture.vOffset;
  109608. rtt.uScale = texture.uScale;
  109609. rtt.vScale = texture.vScale;
  109610. rtt.uAng = texture.uAng;
  109611. rtt.vAng = texture.vAng;
  109612. rtt.wAng = texture.wAng;
  109613. rtt.coordinatesIndex = texture.coordinatesIndex;
  109614. rtt.level = texture.level;
  109615. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  109616. rtt._texture.isReady = false;
  109617. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109618. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109619. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109620. passPostProcess.getEffect().executeWhenCompiled(function () {
  109621. passPostProcess.onApply = function (effect) {
  109622. effect.setTexture("textureSampler", texture);
  109623. };
  109624. var internalTexture = rtt.getInternalTexture();
  109625. if (internalTexture) {
  109626. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  109627. engine.unBindFramebuffer(internalTexture);
  109628. rtt.disposeFramebufferObjects();
  109629. passPostProcess.dispose();
  109630. internalTexture.isReady = true;
  109631. }
  109632. });
  109633. return rtt;
  109634. };
  109635. /**
  109636. * Gets an environment BRDF texture for a given scene
  109637. * @param scene defines the hosting scene
  109638. * @returns the environment BRDF texture
  109639. */
  109640. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  109641. if (!scene._environmentBRDFTexture) {
  109642. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109643. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109644. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109645. scene._environmentBRDFTexture = texture;
  109646. }
  109647. return scene._environmentBRDFTexture;
  109648. };
  109649. 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=";
  109650. return TextureTools;
  109651. }());
  109652. BABYLON.TextureTools = TextureTools;
  109653. })(BABYLON || (BABYLON = {}));
  109654. //# sourceMappingURL=babylon.textureTools.js.map
  109655. var BABYLON;
  109656. (function (BABYLON) {
  109657. /**
  109658. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  109659. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  109660. */
  109661. var FramingBehavior = /** @class */ (function () {
  109662. function FramingBehavior() {
  109663. this._mode = FramingBehavior.FitFrustumSidesMode;
  109664. this._radiusScale = 1.0;
  109665. this._positionScale = 0.5;
  109666. this._defaultElevation = 0.3;
  109667. this._elevationReturnTime = 1500;
  109668. this._elevationReturnWaitTime = 1000;
  109669. this._zoomStopsAnimation = false;
  109670. this._framingTime = 1500;
  109671. /**
  109672. * Define if the behavior should automatically change the configured
  109673. * camera limits and sensibilities.
  109674. */
  109675. this.autoCorrectCameraLimitsAndSensibility = true;
  109676. this._isPointerDown = false;
  109677. this._lastInteractionTime = -Infinity;
  109678. // Framing control
  109679. this._animatables = new Array();
  109680. this._betaIsAnimating = false;
  109681. }
  109682. Object.defineProperty(FramingBehavior.prototype, "name", {
  109683. /**
  109684. * Gets the name of the behavior.
  109685. */
  109686. get: function () {
  109687. return "Framing";
  109688. },
  109689. enumerable: true,
  109690. configurable: true
  109691. });
  109692. Object.defineProperty(FramingBehavior.prototype, "mode", {
  109693. /**
  109694. * Gets current mode used by the behavior.
  109695. */
  109696. get: function () {
  109697. return this._mode;
  109698. },
  109699. /**
  109700. * Sets the current mode used by the behavior
  109701. */
  109702. set: function (mode) {
  109703. this._mode = mode;
  109704. },
  109705. enumerable: true,
  109706. configurable: true
  109707. });
  109708. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  109709. /**
  109710. * Gets the scale applied to the radius
  109711. */
  109712. get: function () {
  109713. return this._radiusScale;
  109714. },
  109715. /**
  109716. * Sets the scale applied to the radius (1 by default)
  109717. */
  109718. set: function (radius) {
  109719. this._radiusScale = radius;
  109720. },
  109721. enumerable: true,
  109722. configurable: true
  109723. });
  109724. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  109725. /**
  109726. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  109727. */
  109728. get: function () {
  109729. return this._positionScale;
  109730. },
  109731. /**
  109732. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  109733. */
  109734. set: function (scale) {
  109735. this._positionScale = scale;
  109736. },
  109737. enumerable: true,
  109738. configurable: true
  109739. });
  109740. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  109741. /**
  109742. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  109743. * behaviour is triggered, in radians.
  109744. */
  109745. get: function () {
  109746. return this._defaultElevation;
  109747. },
  109748. /**
  109749. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  109750. * behaviour is triggered, in radians.
  109751. */
  109752. set: function (elevation) {
  109753. this._defaultElevation = elevation;
  109754. },
  109755. enumerable: true,
  109756. configurable: true
  109757. });
  109758. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  109759. /**
  109760. * Gets the time (in milliseconds) taken to return to the default beta position.
  109761. * Negative value indicates camera should not return to default.
  109762. */
  109763. get: function () {
  109764. return this._elevationReturnTime;
  109765. },
  109766. /**
  109767. * Sets the time (in milliseconds) taken to return to the default beta position.
  109768. * Negative value indicates camera should not return to default.
  109769. */
  109770. set: function (speed) {
  109771. this._elevationReturnTime = speed;
  109772. },
  109773. enumerable: true,
  109774. configurable: true
  109775. });
  109776. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  109777. /**
  109778. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  109779. */
  109780. get: function () {
  109781. return this._elevationReturnWaitTime;
  109782. },
  109783. /**
  109784. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  109785. */
  109786. set: function (time) {
  109787. this._elevationReturnWaitTime = time;
  109788. },
  109789. enumerable: true,
  109790. configurable: true
  109791. });
  109792. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  109793. /**
  109794. * Gets the flag that indicates if user zooming should stop animation.
  109795. */
  109796. get: function () {
  109797. return this._zoomStopsAnimation;
  109798. },
  109799. /**
  109800. * Sets the flag that indicates if user zooming should stop animation.
  109801. */
  109802. set: function (flag) {
  109803. this._zoomStopsAnimation = flag;
  109804. },
  109805. enumerable: true,
  109806. configurable: true
  109807. });
  109808. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  109809. /**
  109810. * Gets the transition time when framing the mesh, in milliseconds
  109811. */
  109812. get: function () {
  109813. return this._framingTime;
  109814. },
  109815. /**
  109816. * Sets the transition time when framing the mesh, in milliseconds
  109817. */
  109818. set: function (time) {
  109819. this._framingTime = time;
  109820. },
  109821. enumerable: true,
  109822. configurable: true
  109823. });
  109824. /**
  109825. * Initializes the behavior.
  109826. */
  109827. FramingBehavior.prototype.init = function () {
  109828. // Do notihng
  109829. };
  109830. /**
  109831. * Attaches the behavior to its arc rotate camera.
  109832. * @param camera Defines the camera to attach the behavior to
  109833. */
  109834. FramingBehavior.prototype.attach = function (camera) {
  109835. var _this = this;
  109836. this._attachedCamera = camera;
  109837. var scene = this._attachedCamera.getScene();
  109838. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  109839. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109840. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109841. _this._isPointerDown = true;
  109842. return;
  109843. }
  109844. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109845. _this._isPointerDown = false;
  109846. }
  109847. });
  109848. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109849. if (mesh) {
  109850. _this.zoomOnMesh(mesh);
  109851. }
  109852. });
  109853. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109854. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109855. _this._applyUserInteraction();
  109856. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  109857. // back to the default position after a given timeout
  109858. _this._maintainCameraAboveGround();
  109859. });
  109860. };
  109861. /**
  109862. * Detaches the behavior from its current arc rotate camera.
  109863. */
  109864. FramingBehavior.prototype.detach = function () {
  109865. if (!this._attachedCamera) {
  109866. return;
  109867. }
  109868. var scene = this._attachedCamera.getScene();
  109869. if (this._onPrePointerObservableObserver) {
  109870. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109871. }
  109872. if (this._onAfterCheckInputsObserver) {
  109873. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109874. }
  109875. if (this._onMeshTargetChangedObserver) {
  109876. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109877. }
  109878. this._attachedCamera = null;
  109879. };
  109880. /**
  109881. * Targets the given mesh and updates zoom level accordingly.
  109882. * @param mesh The mesh to target.
  109883. * @param radius Optional. If a cached radius position already exists, overrides default.
  109884. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109885. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109886. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109887. */
  109888. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109889. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109890. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109891. mesh.computeWorldMatrix(true);
  109892. var boundingBox = mesh.getBoundingInfo().boundingBox;
  109893. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  109894. };
  109895. /**
  109896. * Targets the given mesh with its children and updates zoom level accordingly.
  109897. * @param mesh The mesh to target.
  109898. * @param radius Optional. If a cached radius position already exists, overrides default.
  109899. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109900. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109901. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109902. */
  109903. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109904. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109905. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109906. mesh.computeWorldMatrix(true);
  109907. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  109908. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  109909. };
  109910. /**
  109911. * Targets the given meshes with their children and updates zoom level accordingly.
  109912. * @param meshes The mesh to target.
  109913. * @param radius Optional. If a cached radius position already exists, overrides default.
  109914. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109915. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109916. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109917. */
  109918. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  109919. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109920. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109921. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  109922. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  109923. for (var i = 0; i < meshes.length; i++) {
  109924. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  109925. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  109926. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  109927. }
  109928. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  109929. };
  109930. /**
  109931. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  109932. * @param minimumWorld Determines the smaller position of the bounding box extend
  109933. * @param maximumWorld Determines the bigger position of the bounding box extend
  109934. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109935. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109936. */
  109937. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  109938. var _this = this;
  109939. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109940. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109941. var zoomTarget;
  109942. if (!this._attachedCamera) {
  109943. return;
  109944. }
  109945. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  109946. var bottom = minimumWorld.y;
  109947. var top = maximumWorld.y;
  109948. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  109949. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  109950. if (focusOnOriginXZ) {
  109951. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  109952. }
  109953. else {
  109954. var centerWorld = minimumWorld.add(radiusWorld);
  109955. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  109956. }
  109957. if (!this._vectorTransition) {
  109958. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  109959. }
  109960. this._betaIsAnimating = true;
  109961. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  109962. if (animatable) {
  109963. this._animatables.push(animatable);
  109964. }
  109965. // sets the radius and lower radius bounds
  109966. // Small delta ensures camera is not always at lower zoom limit.
  109967. var radius = 0;
  109968. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  109969. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109970. if (this.autoCorrectCameraLimitsAndSensibility) {
  109971. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  109972. }
  109973. radius = position;
  109974. }
  109975. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109976. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109977. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  109978. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  109979. }
  109980. }
  109981. // Set sensibilities
  109982. if (this.autoCorrectCameraLimitsAndSensibility) {
  109983. var extend = maximumWorld.subtract(minimumWorld).length();
  109984. this._attachedCamera.panningSensibility = 5000 / extend;
  109985. this._attachedCamera.wheelPrecision = 100 / radius;
  109986. }
  109987. // transition to new radius
  109988. if (!this._radiusTransition) {
  109989. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109990. }
  109991. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  109992. _this.stopAllAnimations();
  109993. if (onAnimationEnd) {
  109994. onAnimationEnd();
  109995. }
  109996. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  109997. _this._attachedCamera.storeState();
  109998. }
  109999. });
  110000. if (animatable) {
  110001. this._animatables.push(animatable);
  110002. }
  110003. };
  110004. /**
  110005. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  110006. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  110007. * frustum width.
  110008. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  110009. * to fully enclose the mesh in the viewing frustum.
  110010. */
  110011. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  110012. var size = maximumWorld.subtract(minimumWorld);
  110013. var boxVectorGlobalDiagonal = size.length();
  110014. var frustumSlope = this._getFrustumSlope();
  110015. // Formula for setting distance
  110016. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  110017. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  110018. // Horizon distance
  110019. var radius = radiusWithoutFraming * this._radiusScale;
  110020. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  110021. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  110022. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  110023. var camera = this._attachedCamera;
  110024. if (!camera) {
  110025. return 0;
  110026. }
  110027. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110028. // Don't exceed the requested limit
  110029. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110030. }
  110031. // Don't exceed the upper radius limit
  110032. if (camera.upperRadiusLimit) {
  110033. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110034. }
  110035. return distance;
  110036. };
  110037. /**
  110038. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110039. * is automatically returned to its default position (expected to be above ground plane).
  110040. */
  110041. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110042. var _this = this;
  110043. if (this._elevationReturnTime < 0) {
  110044. return;
  110045. }
  110046. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110047. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110048. var limitBeta = Math.PI * 0.5;
  110049. // Bring the camera back up if below the ground plane
  110050. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110051. this._betaIsAnimating = true;
  110052. //Transition to new position
  110053. this.stopAllAnimations();
  110054. if (!this._betaTransition) {
  110055. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110056. }
  110057. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110058. _this._clearAnimationLocks();
  110059. _this.stopAllAnimations();
  110060. });
  110061. if (animatabe) {
  110062. this._animatables.push(animatabe);
  110063. }
  110064. }
  110065. };
  110066. /**
  110067. * Returns the frustum slope based on the canvas ratio and camera FOV
  110068. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110069. */
  110070. FramingBehavior.prototype._getFrustumSlope = function () {
  110071. // Calculate the viewport ratio
  110072. // Aspect Ratio is Height/Width.
  110073. var camera = this._attachedCamera;
  110074. if (!camera) {
  110075. return BABYLON.Vector2.Zero();
  110076. }
  110077. var engine = camera.getScene().getEngine();
  110078. var aspectRatio = engine.getAspectRatio(camera);
  110079. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110080. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110081. var frustumSlopeY = Math.tan(camera.fov / 2);
  110082. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110083. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110084. // along the forward vector.
  110085. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110086. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110087. };
  110088. /**
  110089. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110090. */
  110091. FramingBehavior.prototype._clearAnimationLocks = function () {
  110092. this._betaIsAnimating = false;
  110093. };
  110094. /**
  110095. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110096. */
  110097. FramingBehavior.prototype._applyUserInteraction = function () {
  110098. if (this.isUserIsMoving) {
  110099. this._lastInteractionTime = BABYLON.Tools.Now;
  110100. this.stopAllAnimations();
  110101. this._clearAnimationLocks();
  110102. }
  110103. };
  110104. /**
  110105. * Stops and removes all animations that have been applied to the camera
  110106. */
  110107. FramingBehavior.prototype.stopAllAnimations = function () {
  110108. if (this._attachedCamera) {
  110109. this._attachedCamera.animations = [];
  110110. }
  110111. while (this._animatables.length) {
  110112. if (this._animatables[0]) {
  110113. this._animatables[0].onAnimationEnd = null;
  110114. this._animatables[0].stop();
  110115. }
  110116. this._animatables.shift();
  110117. }
  110118. };
  110119. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  110120. /**
  110121. * Gets a value indicating if the user is moving the camera
  110122. */
  110123. get: function () {
  110124. if (!this._attachedCamera) {
  110125. return false;
  110126. }
  110127. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110128. this._attachedCamera.inertialBetaOffset !== 0 ||
  110129. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110130. this._attachedCamera.inertialPanningX !== 0 ||
  110131. this._attachedCamera.inertialPanningY !== 0 ||
  110132. this._isPointerDown;
  110133. },
  110134. enumerable: true,
  110135. configurable: true
  110136. });
  110137. /**
  110138. * The easing function used by animations
  110139. */
  110140. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  110141. /**
  110142. * The easing mode used by animations
  110143. */
  110144. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  110145. // Statics
  110146. /**
  110147. * The camera can move all the way towards the mesh.
  110148. */
  110149. FramingBehavior.IgnoreBoundsSizeMode = 0;
  110150. /**
  110151. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  110152. */
  110153. FramingBehavior.FitFrustumSidesMode = 1;
  110154. return FramingBehavior;
  110155. }());
  110156. BABYLON.FramingBehavior = FramingBehavior;
  110157. })(BABYLON || (BABYLON = {}));
  110158. //# sourceMappingURL=babylon.framingBehavior.js.map
  110159. var BABYLON;
  110160. (function (BABYLON) {
  110161. /**
  110162. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  110163. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  110164. */
  110165. var BouncingBehavior = /** @class */ (function () {
  110166. function BouncingBehavior() {
  110167. /**
  110168. * The duration of the animation, in milliseconds
  110169. */
  110170. this.transitionDuration = 450;
  110171. /**
  110172. * Length of the distance animated by the transition when lower radius is reached
  110173. */
  110174. this.lowerRadiusTransitionRange = 2;
  110175. /**
  110176. * Length of the distance animated by the transition when upper radius is reached
  110177. */
  110178. this.upperRadiusTransitionRange = -2;
  110179. this._autoTransitionRange = false;
  110180. // Animations
  110181. this._radiusIsAnimating = false;
  110182. this._radiusBounceTransition = null;
  110183. this._animatables = new Array();
  110184. }
  110185. Object.defineProperty(BouncingBehavior.prototype, "name", {
  110186. /**
  110187. * Gets the name of the behavior.
  110188. */
  110189. get: function () {
  110190. return "Bouncing";
  110191. },
  110192. enumerable: true,
  110193. configurable: true
  110194. });
  110195. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  110196. /**
  110197. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  110198. */
  110199. get: function () {
  110200. return this._autoTransitionRange;
  110201. },
  110202. /**
  110203. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  110204. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  110205. */
  110206. set: function (value) {
  110207. var _this = this;
  110208. if (this._autoTransitionRange === value) {
  110209. return;
  110210. }
  110211. this._autoTransitionRange = value;
  110212. var camera = this._attachedCamera;
  110213. if (!camera) {
  110214. return;
  110215. }
  110216. if (value) {
  110217. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110218. if (!mesh) {
  110219. return;
  110220. }
  110221. mesh.computeWorldMatrix(true);
  110222. var diagonal = mesh.getBoundingInfo().diagonalLength;
  110223. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  110224. _this.upperRadiusTransitionRange = diagonal * 0.05;
  110225. });
  110226. }
  110227. else if (this._onMeshTargetChangedObserver) {
  110228. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110229. }
  110230. },
  110231. enumerable: true,
  110232. configurable: true
  110233. });
  110234. /**
  110235. * Initializes the behavior.
  110236. */
  110237. BouncingBehavior.prototype.init = function () {
  110238. // Do notihng
  110239. };
  110240. /**
  110241. * Attaches the behavior to its arc rotate camera.
  110242. * @param camera Defines the camera to attach the behavior to
  110243. */
  110244. BouncingBehavior.prototype.attach = function (camera) {
  110245. var _this = this;
  110246. this._attachedCamera = camera;
  110247. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110248. if (!_this._attachedCamera) {
  110249. return;
  110250. }
  110251. // Add the bounce animation to the lower radius limit
  110252. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  110253. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  110254. }
  110255. // Add the bounce animation to the upper radius limit
  110256. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  110257. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  110258. }
  110259. });
  110260. };
  110261. /**
  110262. * Detaches the behavior from its current arc rotate camera.
  110263. */
  110264. BouncingBehavior.prototype.detach = function () {
  110265. if (!this._attachedCamera) {
  110266. return;
  110267. }
  110268. if (this._onAfterCheckInputsObserver) {
  110269. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110270. }
  110271. if (this._onMeshTargetChangedObserver) {
  110272. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110273. }
  110274. this._attachedCamera = null;
  110275. };
  110276. /**
  110277. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  110278. * @param radiusLimit The limit to check against.
  110279. * @return Bool to indicate if at limit.
  110280. */
  110281. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  110282. if (!this._attachedCamera) {
  110283. return false;
  110284. }
  110285. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  110286. return true;
  110287. }
  110288. return false;
  110289. };
  110290. /**
  110291. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  110292. * @param radiusDelta The delta by which to animate to. Can be negative.
  110293. */
  110294. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  110295. var _this = this;
  110296. if (!this._attachedCamera) {
  110297. return;
  110298. }
  110299. if (!this._radiusBounceTransition) {
  110300. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  110301. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  110302. }
  110303. // Prevent zoom until bounce has completed
  110304. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  110305. this._attachedCamera.wheelPrecision = Infinity;
  110306. this._attachedCamera.inertialRadiusOffset = 0;
  110307. // Animate to the radius limit
  110308. this.stopAllAnimations();
  110309. this._radiusIsAnimating = true;
  110310. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  110311. if (animatable) {
  110312. this._animatables.push(animatable);
  110313. }
  110314. };
  110315. /**
  110316. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  110317. */
  110318. BouncingBehavior.prototype._clearAnimationLocks = function () {
  110319. this._radiusIsAnimating = false;
  110320. if (this._attachedCamera) {
  110321. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  110322. }
  110323. };
  110324. /**
  110325. * Stops and removes all animations that have been applied to the camera
  110326. */
  110327. BouncingBehavior.prototype.stopAllAnimations = function () {
  110328. if (this._attachedCamera) {
  110329. this._attachedCamera.animations = [];
  110330. }
  110331. while (this._animatables.length) {
  110332. this._animatables[0].onAnimationEnd = null;
  110333. this._animatables[0].stop();
  110334. this._animatables.shift();
  110335. }
  110336. };
  110337. /**
  110338. * The easing function used by animations
  110339. */
  110340. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  110341. /**
  110342. * The easing mode used by animations
  110343. */
  110344. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  110345. return BouncingBehavior;
  110346. }());
  110347. BABYLON.BouncingBehavior = BouncingBehavior;
  110348. })(BABYLON || (BABYLON = {}));
  110349. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  110350. var BABYLON;
  110351. (function (BABYLON) {
  110352. /**
  110353. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  110354. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  110355. */
  110356. var AutoRotationBehavior = /** @class */ (function () {
  110357. function AutoRotationBehavior() {
  110358. this._zoomStopsAnimation = false;
  110359. this._idleRotationSpeed = 0.05;
  110360. this._idleRotationWaitTime = 2000;
  110361. this._idleRotationSpinupTime = 2000;
  110362. this._isPointerDown = false;
  110363. this._lastFrameTime = null;
  110364. this._lastInteractionTime = -Infinity;
  110365. this._cameraRotationSpeed = 0;
  110366. this._lastFrameRadius = 0;
  110367. }
  110368. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  110369. /**
  110370. * Gets the name of the behavior.
  110371. */
  110372. get: function () {
  110373. return "AutoRotation";
  110374. },
  110375. enumerable: true,
  110376. configurable: true
  110377. });
  110378. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  110379. /**
  110380. * Gets the flag that indicates if user zooming should stop animation.
  110381. */
  110382. get: function () {
  110383. return this._zoomStopsAnimation;
  110384. },
  110385. /**
  110386. * Sets the flag that indicates if user zooming should stop animation.
  110387. */
  110388. set: function (flag) {
  110389. this._zoomStopsAnimation = flag;
  110390. },
  110391. enumerable: true,
  110392. configurable: true
  110393. });
  110394. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  110395. /**
  110396. * Gets the default speed at which the camera rotates around the model.
  110397. */
  110398. get: function () {
  110399. return this._idleRotationSpeed;
  110400. },
  110401. /**
  110402. * Sets the default speed at which the camera rotates around the model.
  110403. */
  110404. set: function (speed) {
  110405. this._idleRotationSpeed = speed;
  110406. },
  110407. enumerable: true,
  110408. configurable: true
  110409. });
  110410. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  110411. /**
  110412. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  110413. */
  110414. get: function () {
  110415. return this._idleRotationWaitTime;
  110416. },
  110417. /**
  110418. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  110419. */
  110420. set: function (time) {
  110421. this._idleRotationWaitTime = time;
  110422. },
  110423. enumerable: true,
  110424. configurable: true
  110425. });
  110426. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  110427. /**
  110428. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  110429. */
  110430. get: function () {
  110431. return this._idleRotationSpinupTime;
  110432. },
  110433. /**
  110434. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  110435. */
  110436. set: function (time) {
  110437. this._idleRotationSpinupTime = time;
  110438. },
  110439. enumerable: true,
  110440. configurable: true
  110441. });
  110442. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  110443. /**
  110444. * Gets a value indicating if the camera is currently rotating because of this behavior
  110445. */
  110446. get: function () {
  110447. return Math.abs(this._cameraRotationSpeed) > 0;
  110448. },
  110449. enumerable: true,
  110450. configurable: true
  110451. });
  110452. /**
  110453. * Initializes the behavior.
  110454. */
  110455. AutoRotationBehavior.prototype.init = function () {
  110456. // Do notihng
  110457. };
  110458. /**
  110459. * Attaches the behavior to its arc rotate camera.
  110460. * @param camera Defines the camera to attach the behavior to
  110461. */
  110462. AutoRotationBehavior.prototype.attach = function (camera) {
  110463. var _this = this;
  110464. this._attachedCamera = camera;
  110465. var scene = this._attachedCamera.getScene();
  110466. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110467. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110468. _this._isPointerDown = true;
  110469. return;
  110470. }
  110471. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110472. _this._isPointerDown = false;
  110473. }
  110474. });
  110475. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110476. var now = BABYLON.Tools.Now;
  110477. var dt = 0;
  110478. if (_this._lastFrameTime != null) {
  110479. dt = now - _this._lastFrameTime;
  110480. }
  110481. _this._lastFrameTime = now;
  110482. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110483. _this._applyUserInteraction();
  110484. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  110485. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  110486. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  110487. // Step camera rotation by rotation speed
  110488. if (_this._attachedCamera) {
  110489. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  110490. }
  110491. });
  110492. };
  110493. /**
  110494. * Detaches the behavior from its current arc rotate camera.
  110495. */
  110496. AutoRotationBehavior.prototype.detach = function () {
  110497. if (!this._attachedCamera) {
  110498. return;
  110499. }
  110500. var scene = this._attachedCamera.getScene();
  110501. if (this._onPrePointerObservableObserver) {
  110502. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110503. }
  110504. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110505. this._attachedCamera = null;
  110506. };
  110507. /**
  110508. * Returns true if user is scrolling.
  110509. * @return true if user is scrolling.
  110510. */
  110511. AutoRotationBehavior.prototype._userIsZooming = function () {
  110512. if (!this._attachedCamera) {
  110513. return false;
  110514. }
  110515. return this._attachedCamera.inertialRadiusOffset !== 0;
  110516. };
  110517. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  110518. if (!this._attachedCamera) {
  110519. return false;
  110520. }
  110521. var zoomHasHitLimit = false;
  110522. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  110523. zoomHasHitLimit = true;
  110524. }
  110525. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  110526. this._lastFrameRadius = this._attachedCamera.radius;
  110527. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  110528. };
  110529. /**
  110530. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110531. */
  110532. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  110533. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  110534. this._lastInteractionTime = BABYLON.Tools.Now;
  110535. }
  110536. };
  110537. // Tools
  110538. AutoRotationBehavior.prototype._userIsMoving = function () {
  110539. if (!this._attachedCamera) {
  110540. return false;
  110541. }
  110542. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  110543. this._attachedCamera.inertialBetaOffset !== 0 ||
  110544. this._attachedCamera.inertialRadiusOffset !== 0 ||
  110545. this._attachedCamera.inertialPanningX !== 0 ||
  110546. this._attachedCamera.inertialPanningY !== 0 ||
  110547. this._isPointerDown;
  110548. };
  110549. return AutoRotationBehavior;
  110550. }());
  110551. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  110552. })(BABYLON || (BABYLON = {}));
  110553. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  110554. var BABYLON;
  110555. (function (BABYLON) {
  110556. var NullEngineOptions = /** @class */ (function () {
  110557. function NullEngineOptions() {
  110558. this.renderWidth = 512;
  110559. this.renderHeight = 256;
  110560. this.textureSize = 512;
  110561. this.deterministicLockstep = false;
  110562. this.lockstepMaxSteps = 4;
  110563. }
  110564. return NullEngineOptions;
  110565. }());
  110566. BABYLON.NullEngineOptions = NullEngineOptions;
  110567. /**
  110568. * The null engine class provides support for headless version of babylon.js.
  110569. * This can be used in server side scenario or for testing purposes
  110570. */
  110571. var NullEngine = /** @class */ (function (_super) {
  110572. __extends(NullEngine, _super);
  110573. function NullEngine(options) {
  110574. if (options === void 0) { options = new NullEngineOptions(); }
  110575. var _this = _super.call(this, null) || this;
  110576. if (options.deterministicLockstep === undefined) {
  110577. options.deterministicLockstep = false;
  110578. }
  110579. if (options.lockstepMaxSteps === undefined) {
  110580. options.lockstepMaxSteps = 4;
  110581. }
  110582. _this._options = options;
  110583. // Init caps
  110584. // We consider we are on a webgl1 capable device
  110585. _this._caps = new BABYLON.EngineCapabilities();
  110586. _this._caps.maxTexturesImageUnits = 16;
  110587. _this._caps.maxVertexTextureImageUnits = 16;
  110588. _this._caps.maxTextureSize = 512;
  110589. _this._caps.maxCubemapTextureSize = 512;
  110590. _this._caps.maxRenderTextureSize = 512;
  110591. _this._caps.maxVertexAttribs = 16;
  110592. _this._caps.maxVaryingVectors = 16;
  110593. _this._caps.maxFragmentUniformVectors = 16;
  110594. _this._caps.maxVertexUniformVectors = 16;
  110595. // Extensions
  110596. _this._caps.standardDerivatives = false;
  110597. _this._caps.astc = null;
  110598. _this._caps.s3tc = null;
  110599. _this._caps.pvrtc = null;
  110600. _this._caps.etc1 = null;
  110601. _this._caps.etc2 = null;
  110602. _this._caps.textureAnisotropicFilterExtension = null;
  110603. _this._caps.maxAnisotropy = 0;
  110604. _this._caps.uintIndices = false;
  110605. _this._caps.fragmentDepthSupported = false;
  110606. _this._caps.highPrecisionShaderSupported = true;
  110607. _this._caps.colorBufferFloat = false;
  110608. _this._caps.textureFloat = false;
  110609. _this._caps.textureFloatLinearFiltering = false;
  110610. _this._caps.textureFloatRender = false;
  110611. _this._caps.textureHalfFloat = false;
  110612. _this._caps.textureHalfFloatLinearFiltering = false;
  110613. _this._caps.textureHalfFloatRender = false;
  110614. _this._caps.textureLOD = false;
  110615. _this._caps.drawBuffersExtension = false;
  110616. _this._caps.depthTextureExtension = false;
  110617. _this._caps.vertexArrayObject = false;
  110618. _this._caps.instancedArrays = false;
  110619. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  110620. // Wrappers
  110621. if (typeof URL === "undefined") {
  110622. URL = {
  110623. createObjectURL: function () { },
  110624. revokeObjectURL: function () { }
  110625. };
  110626. }
  110627. if (typeof Blob === "undefined") {
  110628. Blob = function () { };
  110629. }
  110630. return _this;
  110631. }
  110632. NullEngine.prototype.isDeterministicLockStep = function () {
  110633. return this._options.deterministicLockstep;
  110634. };
  110635. NullEngine.prototype.getLockstepMaxSteps = function () {
  110636. return this._options.lockstepMaxSteps;
  110637. };
  110638. NullEngine.prototype.getHardwareScalingLevel = function () {
  110639. return 1.0;
  110640. };
  110641. NullEngine.prototype.createVertexBuffer = function (vertices) {
  110642. return {
  110643. capacity: 0,
  110644. references: 1,
  110645. is32Bits: false
  110646. };
  110647. };
  110648. NullEngine.prototype.createIndexBuffer = function (indices) {
  110649. return {
  110650. capacity: 0,
  110651. references: 1,
  110652. is32Bits: false
  110653. };
  110654. };
  110655. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  110656. if (stencil === void 0) { stencil = false; }
  110657. };
  110658. NullEngine.prototype.getRenderWidth = function (useScreen) {
  110659. if (useScreen === void 0) { useScreen = false; }
  110660. if (!useScreen && this._currentRenderTarget) {
  110661. return this._currentRenderTarget.width;
  110662. }
  110663. return this._options.renderWidth;
  110664. };
  110665. NullEngine.prototype.getRenderHeight = function (useScreen) {
  110666. if (useScreen === void 0) { useScreen = false; }
  110667. if (!useScreen && this._currentRenderTarget) {
  110668. return this._currentRenderTarget.height;
  110669. }
  110670. return this._options.renderHeight;
  110671. };
  110672. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  110673. this._cachedViewport = viewport;
  110674. };
  110675. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  110676. return {
  110677. transformFeedback: null,
  110678. __SPECTOR_rebuildProgram: null
  110679. };
  110680. };
  110681. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  110682. return [];
  110683. };
  110684. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  110685. return [];
  110686. };
  110687. NullEngine.prototype.bindSamplers = function (effect) {
  110688. this._currentEffect = null;
  110689. };
  110690. NullEngine.prototype.enableEffect = function (effect) {
  110691. this._currentEffect = effect;
  110692. if (effect.onBind) {
  110693. effect.onBind(effect);
  110694. }
  110695. if (effect._onBindObservable) {
  110696. effect._onBindObservable.notifyObservers(effect);
  110697. }
  110698. };
  110699. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  110700. if (zOffset === void 0) { zOffset = 0; }
  110701. if (reverseSide === void 0) { reverseSide = false; }
  110702. };
  110703. NullEngine.prototype.setIntArray = function (uniform, array) {
  110704. };
  110705. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  110706. };
  110707. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  110708. };
  110709. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  110710. };
  110711. NullEngine.prototype.setFloatArray = function (uniform, array) {
  110712. };
  110713. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  110714. };
  110715. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  110716. };
  110717. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  110718. };
  110719. NullEngine.prototype.setArray = function (uniform, array) {
  110720. };
  110721. NullEngine.prototype.setArray2 = function (uniform, array) {
  110722. };
  110723. NullEngine.prototype.setArray3 = function (uniform, array) {
  110724. };
  110725. NullEngine.prototype.setArray4 = function (uniform, array) {
  110726. };
  110727. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  110728. };
  110729. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  110730. };
  110731. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  110732. };
  110733. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  110734. };
  110735. NullEngine.prototype.setFloat = function (uniform, value) {
  110736. };
  110737. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  110738. };
  110739. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  110740. };
  110741. NullEngine.prototype.setBool = function (uniform, bool) {
  110742. };
  110743. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  110744. };
  110745. NullEngine.prototype.setColor3 = function (uniform, color3) {
  110746. };
  110747. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  110748. };
  110749. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  110750. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  110751. if (this._alphaMode === mode) {
  110752. return;
  110753. }
  110754. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  110755. if (!noDepthWriteChange) {
  110756. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  110757. }
  110758. this._alphaMode = mode;
  110759. };
  110760. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  110761. };
  110762. NullEngine.prototype.wipeCaches = function (bruteForce) {
  110763. if (this.preventCacheWipeBetweenFrames) {
  110764. return;
  110765. }
  110766. this.resetTextureCache();
  110767. this._currentEffect = null;
  110768. if (bruteForce) {
  110769. this._currentProgram = null;
  110770. this._stencilState.reset();
  110771. this._depthCullingState.reset();
  110772. this._alphaState.reset();
  110773. }
  110774. this._cachedVertexBuffers = null;
  110775. this._cachedIndexBuffer = null;
  110776. this._cachedEffectForVertexBuffers = null;
  110777. };
  110778. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  110779. };
  110780. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  110781. };
  110782. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  110783. };
  110784. /** @hidden */
  110785. NullEngine.prototype._createTexture = function () {
  110786. return {};
  110787. };
  110788. /** @hidden */
  110789. NullEngine.prototype._releaseTexture = function (texture) {
  110790. };
  110791. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  110792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110793. if (onLoad === void 0) { onLoad = null; }
  110794. if (onError === void 0) { onError = null; }
  110795. if (buffer === void 0) { buffer = null; }
  110796. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  110797. var url = String(urlArg);
  110798. texture.url = url;
  110799. texture.generateMipMaps = !noMipmap;
  110800. texture.samplingMode = samplingMode;
  110801. texture.invertY = invertY;
  110802. texture.baseWidth = this._options.textureSize;
  110803. texture.baseHeight = this._options.textureSize;
  110804. texture.width = this._options.textureSize;
  110805. texture.height = this._options.textureSize;
  110806. if (format) {
  110807. texture.format = format;
  110808. }
  110809. texture.isReady = true;
  110810. if (onLoad) {
  110811. onLoad();
  110812. }
  110813. this._internalTexturesCache.push(texture);
  110814. return texture;
  110815. };
  110816. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  110817. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  110818. if (options !== undefined && typeof options === "object") {
  110819. fullOptions.generateMipMaps = options.generateMipMaps;
  110820. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  110821. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  110822. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  110823. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  110824. }
  110825. else {
  110826. fullOptions.generateMipMaps = options;
  110827. fullOptions.generateDepthBuffer = true;
  110828. fullOptions.generateStencilBuffer = false;
  110829. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110830. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  110831. }
  110832. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  110833. var width = size.width || size;
  110834. var height = size.height || size;
  110835. texture._depthStencilBuffer = {};
  110836. texture._framebuffer = {};
  110837. texture.baseWidth = width;
  110838. texture.baseHeight = height;
  110839. texture.width = width;
  110840. texture.height = height;
  110841. texture.isReady = true;
  110842. texture.samples = 1;
  110843. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  110844. texture.samplingMode = fullOptions.samplingMode;
  110845. texture.type = fullOptions.type;
  110846. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  110847. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  110848. this._internalTexturesCache.push(texture);
  110849. return texture;
  110850. };
  110851. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  110852. texture.samplingMode = samplingMode;
  110853. };
  110854. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  110855. if (this._currentRenderTarget) {
  110856. this.unBindFramebuffer(this._currentRenderTarget);
  110857. }
  110858. this._currentRenderTarget = texture;
  110859. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  110860. if (this._cachedViewport && !forceFullscreenViewport) {
  110861. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  110862. }
  110863. };
  110864. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  110865. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  110866. this._currentRenderTarget = null;
  110867. if (onBeforeUnbind) {
  110868. if (texture._MSAAFramebuffer) {
  110869. this._currentFramebuffer = texture._framebuffer;
  110870. }
  110871. onBeforeUnbind();
  110872. }
  110873. this._currentFramebuffer = null;
  110874. };
  110875. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  110876. var vbo = {
  110877. capacity: 1,
  110878. references: 1,
  110879. is32Bits: false
  110880. };
  110881. return vbo;
  110882. };
  110883. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  110884. if (premulAlpha === void 0) { premulAlpha = false; }
  110885. };
  110886. /**
  110887. * @hidden
  110888. * Get the current error code of the webGL context
  110889. * @returns the error code
  110890. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  110891. */
  110892. NullEngine.prototype.getError = function () {
  110893. return 0;
  110894. };
  110895. /** @hidden */
  110896. NullEngine.prototype._getUnpackAlignement = function () {
  110897. return 1;
  110898. };
  110899. /** @hidden */
  110900. NullEngine.prototype._unpackFlipY = function (value) {
  110901. };
  110902. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  110903. if (offset === void 0) { offset = 0; }
  110904. };
  110905. /**
  110906. * Updates a dynamic vertex buffer.
  110907. * @param vertexBuffer the vertex buffer to update
  110908. * @param data the data used to update the vertex buffer
  110909. * @param byteOffset the byte offset of the data (optional)
  110910. * @param byteLength the byte length of the data (optional)
  110911. */
  110912. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  110913. };
  110914. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  110915. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  110916. this._boundTexturesCache[this._activeChannel] = texture;
  110917. return true;
  110918. }
  110919. return false;
  110920. };
  110921. /** @hidden */
  110922. NullEngine.prototype._bindTexture = function (channel, texture) {
  110923. if (channel < 0) {
  110924. return;
  110925. }
  110926. this._bindTextureDirectly(0, texture);
  110927. };
  110928. /** @hidden */
  110929. NullEngine.prototype._releaseBuffer = function (buffer) {
  110930. buffer.references--;
  110931. if (buffer.references === 0) {
  110932. return true;
  110933. }
  110934. return false;
  110935. };
  110936. NullEngine.prototype.releaseEffects = function () {
  110937. };
  110938. NullEngine.prototype.displayLoadingUI = function () {
  110939. };
  110940. NullEngine.prototype.hideLoadingUI = function () {
  110941. };
  110942. /** @hidden */
  110943. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  110944. if (faceIndex === void 0) { faceIndex = 0; }
  110945. if (lod === void 0) { lod = 0; }
  110946. };
  110947. /** @hidden */
  110948. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  110949. if (faceIndex === void 0) { faceIndex = 0; }
  110950. if (lod === void 0) { lod = 0; }
  110951. };
  110952. /** @hidden */
  110953. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  110954. if (faceIndex === void 0) { faceIndex = 0; }
  110955. if (lod === void 0) { lod = 0; }
  110956. };
  110957. /** @hidden */
  110958. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  110959. if (faceIndex === void 0) { faceIndex = 0; }
  110960. if (lod === void 0) { lod = 0; }
  110961. };
  110962. return NullEngine;
  110963. }(BABYLON.Engine));
  110964. BABYLON.NullEngine = NullEngine;
  110965. })(BABYLON || (BABYLON = {}));
  110966. //# sourceMappingURL=babylon.nullEngine.js.map
  110967. var BABYLON;
  110968. (function (BABYLON) {
  110969. /**
  110970. * This class can be used to get instrumentation data from a Babylon engine
  110971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110972. */
  110973. var EngineInstrumentation = /** @class */ (function () {
  110974. /**
  110975. * Instantiates a new engine instrumentation.
  110976. * This class can be used to get instrumentation data from a Babylon engine
  110977. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110978. * @param engine Defines the engine to instrument
  110979. */
  110980. function EngineInstrumentation(
  110981. /**
  110982. * Define the instrumented engine.
  110983. */
  110984. engine) {
  110985. this.engine = engine;
  110986. this._captureGPUFrameTime = false;
  110987. this._gpuFrameTime = new BABYLON.PerfCounter();
  110988. this._captureShaderCompilationTime = false;
  110989. this._shaderCompilationTime = new BABYLON.PerfCounter();
  110990. // Observers
  110991. this._onBeginFrameObserver = null;
  110992. this._onEndFrameObserver = null;
  110993. this._onBeforeShaderCompilationObserver = null;
  110994. this._onAfterShaderCompilationObserver = null;
  110995. }
  110996. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  110997. // Properties
  110998. /**
  110999. * Gets the perf counter used for GPU frame time
  111000. */
  111001. get: function () {
  111002. return this._gpuFrameTime;
  111003. },
  111004. enumerable: true,
  111005. configurable: true
  111006. });
  111007. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  111008. /**
  111009. * Gets the GPU frame time capture status
  111010. */
  111011. get: function () {
  111012. return this._captureGPUFrameTime;
  111013. },
  111014. /**
  111015. * Enable or disable the GPU frame time capture
  111016. */
  111017. set: function (value) {
  111018. var _this = this;
  111019. if (value === this._captureGPUFrameTime) {
  111020. return;
  111021. }
  111022. this._captureGPUFrameTime = value;
  111023. if (value) {
  111024. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  111025. if (!_this._gpuFrameTimeToken) {
  111026. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111027. }
  111028. });
  111029. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111030. if (!_this._gpuFrameTimeToken) {
  111031. return;
  111032. }
  111033. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111034. if (time > -1) {
  111035. _this._gpuFrameTimeToken = null;
  111036. _this._gpuFrameTime.fetchNewFrame();
  111037. _this._gpuFrameTime.addCount(time, true);
  111038. }
  111039. });
  111040. }
  111041. else {
  111042. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111043. this._onBeginFrameObserver = null;
  111044. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111045. this._onEndFrameObserver = null;
  111046. }
  111047. },
  111048. enumerable: true,
  111049. configurable: true
  111050. });
  111051. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111052. /**
  111053. * Gets the perf counter used for shader compilation time
  111054. */
  111055. get: function () {
  111056. return this._shaderCompilationTime;
  111057. },
  111058. enumerable: true,
  111059. configurable: true
  111060. });
  111061. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111062. /**
  111063. * Gets the shader compilation time capture status
  111064. */
  111065. get: function () {
  111066. return this._captureShaderCompilationTime;
  111067. },
  111068. /**
  111069. * Enable or disable the shader compilation time capture
  111070. */
  111071. set: function (value) {
  111072. var _this = this;
  111073. if (value === this._captureShaderCompilationTime) {
  111074. return;
  111075. }
  111076. this._captureShaderCompilationTime = value;
  111077. if (value) {
  111078. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111079. _this._shaderCompilationTime.fetchNewFrame();
  111080. _this._shaderCompilationTime.beginMonitoring();
  111081. });
  111082. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111083. _this._shaderCompilationTime.endMonitoring();
  111084. });
  111085. }
  111086. else {
  111087. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111088. this._onBeforeShaderCompilationObserver = null;
  111089. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111090. this._onAfterShaderCompilationObserver = null;
  111091. }
  111092. },
  111093. enumerable: true,
  111094. configurable: true
  111095. });
  111096. /**
  111097. * Dispose and release associated resources.
  111098. */
  111099. EngineInstrumentation.prototype.dispose = function () {
  111100. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111101. this._onBeginFrameObserver = null;
  111102. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111103. this._onEndFrameObserver = null;
  111104. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111105. this._onBeforeShaderCompilationObserver = null;
  111106. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111107. this._onAfterShaderCompilationObserver = null;
  111108. this.engine = null;
  111109. };
  111110. return EngineInstrumentation;
  111111. }());
  111112. BABYLON.EngineInstrumentation = EngineInstrumentation;
  111113. })(BABYLON || (BABYLON = {}));
  111114. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  111115. var BABYLON;
  111116. (function (BABYLON) {
  111117. /**
  111118. * This class can be used to get instrumentation data from a Babylon engine
  111119. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111120. */
  111121. var SceneInstrumentation = /** @class */ (function () {
  111122. /**
  111123. * Instantiates a new scene instrumentation.
  111124. * This class can be used to get instrumentation data from a Babylon engine
  111125. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111126. * @param scene Defines the scene to instrument
  111127. */
  111128. function SceneInstrumentation(
  111129. /**
  111130. * Defines the scene to instrument
  111131. */
  111132. scene) {
  111133. var _this = this;
  111134. this.scene = scene;
  111135. this._captureActiveMeshesEvaluationTime = false;
  111136. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  111137. this._captureRenderTargetsRenderTime = false;
  111138. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  111139. this._captureFrameTime = false;
  111140. this._frameTime = new BABYLON.PerfCounter();
  111141. this._captureRenderTime = false;
  111142. this._renderTime = new BABYLON.PerfCounter();
  111143. this._captureInterFrameTime = false;
  111144. this._interFrameTime = new BABYLON.PerfCounter();
  111145. this._captureParticlesRenderTime = false;
  111146. this._particlesRenderTime = new BABYLON.PerfCounter();
  111147. this._captureSpritesRenderTime = false;
  111148. this._spritesRenderTime = new BABYLON.PerfCounter();
  111149. this._capturePhysicsTime = false;
  111150. this._physicsTime = new BABYLON.PerfCounter();
  111151. this._captureAnimationsTime = false;
  111152. this._animationsTime = new BABYLON.PerfCounter();
  111153. this._captureCameraRenderTime = false;
  111154. this._cameraRenderTime = new BABYLON.PerfCounter();
  111155. // Observers
  111156. this._onBeforeActiveMeshesEvaluationObserver = null;
  111157. this._onAfterActiveMeshesEvaluationObserver = null;
  111158. this._onBeforeRenderTargetsRenderObserver = null;
  111159. this._onAfterRenderTargetsRenderObserver = null;
  111160. this._onAfterRenderObserver = null;
  111161. this._onBeforeDrawPhaseObserver = null;
  111162. this._onAfterDrawPhaseObserver = null;
  111163. this._onBeforeAnimationsObserver = null;
  111164. this._onBeforeParticlesRenderingObserver = null;
  111165. this._onAfterParticlesRenderingObserver = null;
  111166. this._onBeforeSpritesRenderingObserver = null;
  111167. this._onAfterSpritesRenderingObserver = null;
  111168. this._onBeforePhysicsObserver = null;
  111169. this._onAfterPhysicsObserver = null;
  111170. this._onAfterAnimationsObserver = null;
  111171. this._onBeforeCameraRenderObserver = null;
  111172. this._onAfterCameraRenderObserver = null;
  111173. // Before render
  111174. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  111175. if (_this._captureActiveMeshesEvaluationTime) {
  111176. _this._activeMeshesEvaluationTime.fetchNewFrame();
  111177. }
  111178. if (_this._captureRenderTargetsRenderTime) {
  111179. _this._renderTargetsRenderTime.fetchNewFrame();
  111180. }
  111181. if (_this._captureFrameTime) {
  111182. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  111183. _this._frameTime.beginMonitoring();
  111184. }
  111185. if (_this._captureInterFrameTime) {
  111186. _this._interFrameTime.endMonitoring();
  111187. }
  111188. if (_this._captureParticlesRenderTime) {
  111189. _this._particlesRenderTime.fetchNewFrame();
  111190. }
  111191. if (_this._captureSpritesRenderTime) {
  111192. _this._spritesRenderTime.fetchNewFrame();
  111193. }
  111194. if (_this._captureAnimationsTime) {
  111195. _this._animationsTime.beginMonitoring();
  111196. }
  111197. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  111198. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  111199. });
  111200. // After render
  111201. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  111202. if (_this._captureFrameTime) {
  111203. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  111204. _this._frameTime.endMonitoring();
  111205. }
  111206. if (_this._captureRenderTime) {
  111207. _this._renderTime.endMonitoring(false);
  111208. }
  111209. if (_this._captureInterFrameTime) {
  111210. _this._interFrameTime.beginMonitoring();
  111211. }
  111212. });
  111213. }
  111214. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  111215. // Properties
  111216. /**
  111217. * Gets the perf counter used for active meshes evaluation time
  111218. */
  111219. get: function () {
  111220. return this._activeMeshesEvaluationTime;
  111221. },
  111222. enumerable: true,
  111223. configurable: true
  111224. });
  111225. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  111226. /**
  111227. * Gets the active meshes evaluation time capture status
  111228. */
  111229. get: function () {
  111230. return this._captureActiveMeshesEvaluationTime;
  111231. },
  111232. /**
  111233. * Enable or disable the active meshes evaluation time capture
  111234. */
  111235. set: function (value) {
  111236. var _this = this;
  111237. if (value === this._captureActiveMeshesEvaluationTime) {
  111238. return;
  111239. }
  111240. this._captureActiveMeshesEvaluationTime = value;
  111241. if (value) {
  111242. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  111243. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  111244. _this._activeMeshesEvaluationTime.beginMonitoring();
  111245. });
  111246. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  111247. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  111248. _this._activeMeshesEvaluationTime.endMonitoring();
  111249. });
  111250. }
  111251. else {
  111252. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  111253. this._onBeforeActiveMeshesEvaluationObserver = null;
  111254. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  111255. this._onAfterActiveMeshesEvaluationObserver = null;
  111256. }
  111257. },
  111258. enumerable: true,
  111259. configurable: true
  111260. });
  111261. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  111262. /**
  111263. * Gets the perf counter used for render targets render time
  111264. */
  111265. get: function () {
  111266. return this._renderTargetsRenderTime;
  111267. },
  111268. enumerable: true,
  111269. configurable: true
  111270. });
  111271. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  111272. /**
  111273. * Gets the render targets render time capture status
  111274. */
  111275. get: function () {
  111276. return this._captureRenderTargetsRenderTime;
  111277. },
  111278. /**
  111279. * Enable or disable the render targets render time capture
  111280. */
  111281. set: function (value) {
  111282. var _this = this;
  111283. if (value === this._captureRenderTargetsRenderTime) {
  111284. return;
  111285. }
  111286. this._captureRenderTargetsRenderTime = value;
  111287. if (value) {
  111288. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  111289. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  111290. _this._renderTargetsRenderTime.beginMonitoring();
  111291. });
  111292. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  111293. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  111294. _this._renderTargetsRenderTime.endMonitoring(false);
  111295. });
  111296. }
  111297. else {
  111298. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  111299. this._onBeforeRenderTargetsRenderObserver = null;
  111300. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  111301. this._onAfterRenderTargetsRenderObserver = null;
  111302. }
  111303. },
  111304. enumerable: true,
  111305. configurable: true
  111306. });
  111307. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  111308. /**
  111309. * Gets the perf counter used for particles render time
  111310. */
  111311. get: function () {
  111312. return this._particlesRenderTime;
  111313. },
  111314. enumerable: true,
  111315. configurable: true
  111316. });
  111317. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  111318. /**
  111319. * Gets the particles render time capture status
  111320. */
  111321. get: function () {
  111322. return this._captureParticlesRenderTime;
  111323. },
  111324. /**
  111325. * Enable or disable the particles render time capture
  111326. */
  111327. set: function (value) {
  111328. var _this = this;
  111329. if (value === this._captureParticlesRenderTime) {
  111330. return;
  111331. }
  111332. this._captureParticlesRenderTime = value;
  111333. if (value) {
  111334. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  111335. BABYLON.Tools.StartPerformanceCounter("Particles");
  111336. _this._particlesRenderTime.beginMonitoring();
  111337. });
  111338. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  111339. BABYLON.Tools.EndPerformanceCounter("Particles");
  111340. _this._particlesRenderTime.endMonitoring(false);
  111341. });
  111342. }
  111343. else {
  111344. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  111345. this._onBeforeParticlesRenderingObserver = null;
  111346. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  111347. this._onAfterParticlesRenderingObserver = null;
  111348. }
  111349. },
  111350. enumerable: true,
  111351. configurable: true
  111352. });
  111353. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  111354. /**
  111355. * Gets the perf counter used for sprites render time
  111356. */
  111357. get: function () {
  111358. return this._spritesRenderTime;
  111359. },
  111360. enumerable: true,
  111361. configurable: true
  111362. });
  111363. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  111364. /**
  111365. * Gets the sprites render time capture status
  111366. */
  111367. get: function () {
  111368. return this._captureSpritesRenderTime;
  111369. },
  111370. /**
  111371. * Enable or disable the sprites render time capture
  111372. */
  111373. set: function (value) {
  111374. var _this = this;
  111375. if (value === this._captureSpritesRenderTime) {
  111376. return;
  111377. }
  111378. this._captureSpritesRenderTime = value;
  111379. if (!this.scene.spriteManagers) {
  111380. return;
  111381. }
  111382. if (value) {
  111383. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  111384. BABYLON.Tools.StartPerformanceCounter("Sprites");
  111385. _this._spritesRenderTime.beginMonitoring();
  111386. });
  111387. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  111388. BABYLON.Tools.EndPerformanceCounter("Sprites");
  111389. _this._spritesRenderTime.endMonitoring(false);
  111390. });
  111391. }
  111392. else {
  111393. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  111394. this._onBeforeSpritesRenderingObserver = null;
  111395. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  111396. this._onAfterSpritesRenderingObserver = null;
  111397. }
  111398. },
  111399. enumerable: true,
  111400. configurable: true
  111401. });
  111402. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  111403. /**
  111404. * Gets the perf counter used for physics time
  111405. */
  111406. get: function () {
  111407. return this._physicsTime;
  111408. },
  111409. enumerable: true,
  111410. configurable: true
  111411. });
  111412. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  111413. /**
  111414. * Gets the physics time capture status
  111415. */
  111416. get: function () {
  111417. return this._capturePhysicsTime;
  111418. },
  111419. /**
  111420. * Enable or disable the physics time capture
  111421. */
  111422. set: function (value) {
  111423. var _this = this;
  111424. if (value === this._capturePhysicsTime) {
  111425. return;
  111426. }
  111427. if (!this.scene.onBeforePhysicsObservable) {
  111428. return;
  111429. }
  111430. this._capturePhysicsTime = value;
  111431. if (value) {
  111432. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  111433. BABYLON.Tools.StartPerformanceCounter("Physics");
  111434. _this._physicsTime.beginMonitoring();
  111435. });
  111436. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  111437. BABYLON.Tools.EndPerformanceCounter("Physics");
  111438. _this._physicsTime.endMonitoring();
  111439. });
  111440. }
  111441. else {
  111442. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  111443. this._onBeforePhysicsObserver = null;
  111444. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  111445. this._onAfterPhysicsObserver = null;
  111446. }
  111447. },
  111448. enumerable: true,
  111449. configurable: true
  111450. });
  111451. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  111452. /**
  111453. * Gets the perf counter used for animations time
  111454. */
  111455. get: function () {
  111456. return this._animationsTime;
  111457. },
  111458. enumerable: true,
  111459. configurable: true
  111460. });
  111461. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  111462. /**
  111463. * Gets the animations time capture status
  111464. */
  111465. get: function () {
  111466. return this._captureAnimationsTime;
  111467. },
  111468. /**
  111469. * Enable or disable the animations time capture
  111470. */
  111471. set: function (value) {
  111472. var _this = this;
  111473. if (value === this._captureAnimationsTime) {
  111474. return;
  111475. }
  111476. this._captureAnimationsTime = value;
  111477. if (value) {
  111478. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  111479. _this._animationsTime.endMonitoring();
  111480. });
  111481. }
  111482. else {
  111483. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  111484. this._onAfterAnimationsObserver = null;
  111485. }
  111486. },
  111487. enumerable: true,
  111488. configurable: true
  111489. });
  111490. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  111491. /**
  111492. * Gets the perf counter used for frame time capture
  111493. */
  111494. get: function () {
  111495. return this._frameTime;
  111496. },
  111497. enumerable: true,
  111498. configurable: true
  111499. });
  111500. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  111501. /**
  111502. * Gets the frame time capture status
  111503. */
  111504. get: function () {
  111505. return this._captureFrameTime;
  111506. },
  111507. /**
  111508. * Enable or disable the frame time capture
  111509. */
  111510. set: function (value) {
  111511. this._captureFrameTime = value;
  111512. },
  111513. enumerable: true,
  111514. configurable: true
  111515. });
  111516. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  111517. /**
  111518. * Gets the perf counter used for inter-frames time capture
  111519. */
  111520. get: function () {
  111521. return this._interFrameTime;
  111522. },
  111523. enumerable: true,
  111524. configurable: true
  111525. });
  111526. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  111527. /**
  111528. * Gets the inter-frames time capture status
  111529. */
  111530. get: function () {
  111531. return this._captureInterFrameTime;
  111532. },
  111533. /**
  111534. * Enable or disable the inter-frames time capture
  111535. */
  111536. set: function (value) {
  111537. this._captureInterFrameTime = value;
  111538. },
  111539. enumerable: true,
  111540. configurable: true
  111541. });
  111542. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  111543. /**
  111544. * Gets the perf counter used for render time capture
  111545. */
  111546. get: function () {
  111547. return this._renderTime;
  111548. },
  111549. enumerable: true,
  111550. configurable: true
  111551. });
  111552. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  111553. /**
  111554. * Gets the render time capture status
  111555. */
  111556. get: function () {
  111557. return this._captureRenderTime;
  111558. },
  111559. /**
  111560. * Enable or disable the render time capture
  111561. */
  111562. set: function (value) {
  111563. var _this = this;
  111564. if (value === this._captureRenderTime) {
  111565. return;
  111566. }
  111567. this._captureRenderTime = value;
  111568. if (value) {
  111569. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  111570. _this._renderTime.beginMonitoring();
  111571. BABYLON.Tools.StartPerformanceCounter("Main render");
  111572. });
  111573. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  111574. _this._renderTime.endMonitoring(false);
  111575. BABYLON.Tools.EndPerformanceCounter("Main render");
  111576. });
  111577. }
  111578. else {
  111579. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  111580. this._onBeforeDrawPhaseObserver = null;
  111581. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  111582. this._onAfterDrawPhaseObserver = null;
  111583. }
  111584. },
  111585. enumerable: true,
  111586. configurable: true
  111587. });
  111588. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  111589. /**
  111590. * Gets the perf counter used for camera render time capture
  111591. */
  111592. get: function () {
  111593. return this._cameraRenderTime;
  111594. },
  111595. enumerable: true,
  111596. configurable: true
  111597. });
  111598. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  111599. /**
  111600. * Gets the camera render time capture status
  111601. */
  111602. get: function () {
  111603. return this._captureCameraRenderTime;
  111604. },
  111605. /**
  111606. * Enable or disable the camera render time capture
  111607. */
  111608. set: function (value) {
  111609. var _this = this;
  111610. if (value === this._captureCameraRenderTime) {
  111611. return;
  111612. }
  111613. this._captureCameraRenderTime = value;
  111614. if (value) {
  111615. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  111616. _this._cameraRenderTime.beginMonitoring();
  111617. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  111618. });
  111619. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  111620. _this._cameraRenderTime.endMonitoring(false);
  111621. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  111622. });
  111623. }
  111624. else {
  111625. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  111626. this._onBeforeCameraRenderObserver = null;
  111627. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  111628. this._onAfterCameraRenderObserver = null;
  111629. }
  111630. },
  111631. enumerable: true,
  111632. configurable: true
  111633. });
  111634. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  111635. /**
  111636. * Gets the perf counter used for draw calls
  111637. */
  111638. get: function () {
  111639. return this.scene.getEngine()._drawCalls;
  111640. },
  111641. enumerable: true,
  111642. configurable: true
  111643. });
  111644. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  111645. /**
  111646. * Gets the perf counter used for texture collisions
  111647. */
  111648. get: function () {
  111649. return this.scene.getEngine()._textureCollisions;
  111650. },
  111651. enumerable: true,
  111652. configurable: true
  111653. });
  111654. /**
  111655. * Dispose and release associated resources.
  111656. */
  111657. SceneInstrumentation.prototype.dispose = function () {
  111658. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  111659. this._onAfterRenderObserver = null;
  111660. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  111661. this._onBeforeActiveMeshesEvaluationObserver = null;
  111662. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  111663. this._onAfterActiveMeshesEvaluationObserver = null;
  111664. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  111665. this._onBeforeRenderTargetsRenderObserver = null;
  111666. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  111667. this._onAfterRenderTargetsRenderObserver = null;
  111668. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  111669. this._onBeforeAnimationsObserver = null;
  111670. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  111671. this._onBeforeParticlesRenderingObserver = null;
  111672. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  111673. this._onAfterParticlesRenderingObserver = null;
  111674. if (this._onBeforeSpritesRenderingObserver) {
  111675. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  111676. this._onBeforeSpritesRenderingObserver = null;
  111677. }
  111678. if (this._onAfterSpritesRenderingObserver) {
  111679. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  111680. this._onAfterSpritesRenderingObserver = null;
  111681. }
  111682. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  111683. this._onBeforeDrawPhaseObserver = null;
  111684. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  111685. this._onAfterDrawPhaseObserver = null;
  111686. if (this._onBeforePhysicsObserver) {
  111687. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  111688. this._onBeforePhysicsObserver = null;
  111689. }
  111690. if (this._onAfterPhysicsObserver) {
  111691. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  111692. this._onAfterPhysicsObserver = null;
  111693. }
  111694. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  111695. this._onAfterAnimationsObserver = null;
  111696. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  111697. this._onBeforeCameraRenderObserver = null;
  111698. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  111699. this._onAfterCameraRenderObserver = null;
  111700. this.scene = null;
  111701. };
  111702. return SceneInstrumentation;
  111703. }());
  111704. BABYLON.SceneInstrumentation = SceneInstrumentation;
  111705. })(BABYLON || (BABYLON = {}));
  111706. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  111707. var BABYLON;
  111708. (function (BABYLON) {
  111709. /**
  111710. * @hidden
  111711. **/
  111712. var _TimeToken = /** @class */ (function () {
  111713. function _TimeToken() {
  111714. this._timeElapsedQueryEnded = false;
  111715. }
  111716. return _TimeToken;
  111717. }());
  111718. BABYLON._TimeToken = _TimeToken;
  111719. })(BABYLON || (BABYLON = {}));
  111720. //# sourceMappingURL=babylon.timeToken.js.map
  111721. var BABYLON;
  111722. (function (BABYLON) {
  111723. /**
  111724. * Background material defines definition.
  111725. * @hidden Mainly internal Use
  111726. */
  111727. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  111728. __extends(BackgroundMaterialDefines, _super);
  111729. /**
  111730. * Constructor of the defines.
  111731. */
  111732. function BackgroundMaterialDefines() {
  111733. var _this = _super.call(this) || this;
  111734. /**
  111735. * True if the diffuse texture is in use.
  111736. */
  111737. _this.DIFFUSE = false;
  111738. /**
  111739. * The direct UV channel to use.
  111740. */
  111741. _this.DIFFUSEDIRECTUV = 0;
  111742. /**
  111743. * True if the diffuse texture is in gamma space.
  111744. */
  111745. _this.GAMMADIFFUSE = false;
  111746. /**
  111747. * True if the diffuse texture has opacity in the alpha channel.
  111748. */
  111749. _this.DIFFUSEHASALPHA = false;
  111750. /**
  111751. * True if you want the material to fade to transparent at grazing angle.
  111752. */
  111753. _this.OPACITYFRESNEL = false;
  111754. /**
  111755. * True if an extra blur needs to be added in the reflection.
  111756. */
  111757. _this.REFLECTIONBLUR = false;
  111758. /**
  111759. * True if you want the material to fade to reflection at grazing angle.
  111760. */
  111761. _this.REFLECTIONFRESNEL = false;
  111762. /**
  111763. * True if you want the material to falloff as far as you move away from the scene center.
  111764. */
  111765. _this.REFLECTIONFALLOFF = false;
  111766. /**
  111767. * False if the current Webgl implementation does not support the texture lod extension.
  111768. */
  111769. _this.TEXTURELODSUPPORT = false;
  111770. /**
  111771. * True to ensure the data are premultiplied.
  111772. */
  111773. _this.PREMULTIPLYALPHA = false;
  111774. /**
  111775. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  111776. */
  111777. _this.USERGBCOLOR = false;
  111778. /**
  111779. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  111780. * stays aligned with the desired configuration.
  111781. */
  111782. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  111783. /**
  111784. * True to add noise in order to reduce the banding effect.
  111785. */
  111786. _this.NOISE = false;
  111787. /**
  111788. * is the reflection texture in BGR color scheme?
  111789. * Mainly used to solve a bug in ios10 video tag
  111790. */
  111791. _this.REFLECTIONBGR = false;
  111792. _this.IMAGEPROCESSING = false;
  111793. _this.VIGNETTE = false;
  111794. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  111795. _this.VIGNETTEBLENDMODEOPAQUE = false;
  111796. _this.TONEMAPPING = false;
  111797. _this.TONEMAPPING_ACES = false;
  111798. _this.CONTRAST = false;
  111799. _this.COLORCURVES = false;
  111800. _this.COLORGRADING = false;
  111801. _this.COLORGRADING3D = false;
  111802. _this.SAMPLER3DGREENDEPTH = false;
  111803. _this.SAMPLER3DBGRMAP = false;
  111804. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  111805. _this.EXPOSURE = false;
  111806. // Reflection.
  111807. _this.REFLECTION = false;
  111808. _this.REFLECTIONMAP_3D = false;
  111809. _this.REFLECTIONMAP_SPHERICAL = false;
  111810. _this.REFLECTIONMAP_PLANAR = false;
  111811. _this.REFLECTIONMAP_CUBIC = false;
  111812. _this.REFLECTIONMAP_PROJECTION = false;
  111813. _this.REFLECTIONMAP_SKYBOX = false;
  111814. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  111815. _this.REFLECTIONMAP_EXPLICIT = false;
  111816. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  111817. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  111818. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  111819. _this.INVERTCUBICMAP = false;
  111820. _this.REFLECTIONMAP_OPPOSITEZ = false;
  111821. _this.LODINREFLECTIONALPHA = false;
  111822. _this.GAMMAREFLECTION = false;
  111823. _this.RGBDREFLECTION = false;
  111824. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  111825. // Default BJS.
  111826. _this.MAINUV1 = false;
  111827. _this.MAINUV2 = false;
  111828. _this.UV1 = false;
  111829. _this.UV2 = false;
  111830. _this.CLIPPLANE = false;
  111831. _this.CLIPPLANE2 = false;
  111832. _this.CLIPPLANE3 = false;
  111833. _this.CLIPPLANE4 = false;
  111834. _this.POINTSIZE = false;
  111835. _this.FOG = false;
  111836. _this.NORMAL = false;
  111837. _this.NUM_BONE_INFLUENCERS = 0;
  111838. _this.BonesPerMesh = 0;
  111839. _this.INSTANCES = false;
  111840. _this.SHADOWFLOAT = false;
  111841. _this.rebuild();
  111842. return _this;
  111843. }
  111844. return BackgroundMaterialDefines;
  111845. }(BABYLON.MaterialDefines));
  111846. /**
  111847. * Background material used to create an efficient environement around your scene.
  111848. */
  111849. var BackgroundMaterial = /** @class */ (function (_super) {
  111850. __extends(BackgroundMaterial, _super);
  111851. /**
  111852. * Instantiates a Background Material in the given scene
  111853. * @param name The friendly name of the material
  111854. * @param scene The scene to add the material to
  111855. */
  111856. function BackgroundMaterial(name, scene) {
  111857. var _this = _super.call(this, name, scene) || this;
  111858. /**
  111859. * Key light Color (multiply against the environement texture)
  111860. */
  111861. _this.primaryColor = BABYLON.Color3.White();
  111862. _this._primaryColorShadowLevel = 0;
  111863. _this._primaryColorHighlightLevel = 0;
  111864. /**
  111865. * Reflection Texture used in the material.
  111866. * Should be author in a specific way for the best result (refer to the documentation).
  111867. */
  111868. _this.reflectionTexture = null;
  111869. /**
  111870. * Reflection Texture level of blur.
  111871. *
  111872. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  111873. * texture twice.
  111874. */
  111875. _this.reflectionBlur = 0;
  111876. /**
  111877. * Diffuse Texture used in the material.
  111878. * Should be author in a specific way for the best result (refer to the documentation).
  111879. */
  111880. _this.diffuseTexture = null;
  111881. _this._shadowLights = null;
  111882. /**
  111883. * Specify the list of lights casting shadow on the material.
  111884. * All scene shadow lights will be included if null.
  111885. */
  111886. _this.shadowLights = null;
  111887. /**
  111888. * Helps adjusting the shadow to a softer level if required.
  111889. * 0 means black shadows and 1 means no shadows.
  111890. */
  111891. _this.shadowLevel = 0;
  111892. /**
  111893. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  111894. * It is usually zero but might be interesting to modify according to your setup.
  111895. */
  111896. _this.sceneCenter = BABYLON.Vector3.Zero();
  111897. /**
  111898. * This helps specifying that the material is falling off to the sky box at grazing angle.
  111899. * This helps ensuring a nice transition when the camera goes under the ground.
  111900. */
  111901. _this.opacityFresnel = true;
  111902. /**
  111903. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  111904. * This helps adding a mirror texture on the ground.
  111905. */
  111906. _this.reflectionFresnel = false;
  111907. /**
  111908. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  111909. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  111910. */
  111911. _this.reflectionFalloffDistance = 0.0;
  111912. /**
  111913. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  111914. */
  111915. _this.reflectionAmount = 1.0;
  111916. /**
  111917. * This specifies the weight of the reflection at grazing angle.
  111918. */
  111919. _this.reflectionReflectance0 = 0.05;
  111920. /**
  111921. * This specifies the weight of the reflection at a perpendicular point of view.
  111922. */
  111923. _this.reflectionReflectance90 = 0.5;
  111924. /**
  111925. * Helps to directly use the maps channels instead of their level.
  111926. */
  111927. _this.useRGBColor = true;
  111928. /**
  111929. * This helps reducing the banding effect that could occur on the background.
  111930. */
  111931. _this.enableNoise = false;
  111932. _this._fovMultiplier = 1.0;
  111933. /**
  111934. * Enable the FOV adjustment feature controlled by fovMultiplier.
  111935. */
  111936. _this.useEquirectangularFOV = false;
  111937. _this._maxSimultaneousLights = 4;
  111938. /**
  111939. * Number of Simultaneous lights allowed on the material.
  111940. */
  111941. _this.maxSimultaneousLights = 4;
  111942. /**
  111943. * Keep track of the image processing observer to allow dispose and replace.
  111944. */
  111945. _this._imageProcessingObserver = null;
  111946. /**
  111947. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  111948. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  111949. */
  111950. _this.switchToBGR = false;
  111951. // Temp values kept as cache in the material.
  111952. _this._renderTargets = new BABYLON.SmartArray(16);
  111953. _this._reflectionControls = BABYLON.Vector4.Zero();
  111954. _this._white = BABYLON.Color3.White();
  111955. _this._primaryShadowColor = BABYLON.Color3.Black();
  111956. _this._primaryHighlightColor = BABYLON.Color3.Black();
  111957. // Setup the default processing configuration to the scene.
  111958. _this._attachImageProcessingConfiguration(null);
  111959. _this.getRenderTargetTextures = function () {
  111960. _this._renderTargets.reset();
  111961. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  111962. _this._renderTargets.push(_this._diffuseTexture);
  111963. }
  111964. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  111965. _this._renderTargets.push(_this._reflectionTexture);
  111966. }
  111967. return _this._renderTargets;
  111968. };
  111969. return _this;
  111970. }
  111971. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  111972. /**
  111973. * Experimental Internal Use Only.
  111974. *
  111975. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  111976. * This acts as a helper to set the primary color to a more "human friendly" value.
  111977. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  111978. * output color as close as possible from the chosen value.
  111979. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  111980. * part of lighting setup.)
  111981. */
  111982. get: function () {
  111983. return this.__perceptualColor;
  111984. },
  111985. set: function (value) {
  111986. this.__perceptualColor = value;
  111987. this._computePrimaryColorFromPerceptualColor();
  111988. this._markAllSubMeshesAsLightsDirty();
  111989. },
  111990. enumerable: true,
  111991. configurable: true
  111992. });
  111993. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  111994. /**
  111995. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  111996. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  111997. */
  111998. get: function () {
  111999. return this._primaryColorShadowLevel;
  112000. },
  112001. set: function (value) {
  112002. this._primaryColorShadowLevel = value;
  112003. this._computePrimaryColors();
  112004. this._markAllSubMeshesAsLightsDirty();
  112005. },
  112006. enumerable: true,
  112007. configurable: true
  112008. });
  112009. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  112010. /**
  112011. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  112012. * The primary color is used at the level chosen to define what the white area would look.
  112013. */
  112014. get: function () {
  112015. return this._primaryColorHighlightLevel;
  112016. },
  112017. set: function (value) {
  112018. this._primaryColorHighlightLevel = value;
  112019. this._computePrimaryColors();
  112020. this._markAllSubMeshesAsLightsDirty();
  112021. },
  112022. enumerable: true,
  112023. configurable: true
  112024. });
  112025. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  112026. /**
  112027. * Sets the reflection reflectance fresnel values according to the default standard
  112028. * empirically know to work well :-)
  112029. */
  112030. set: function (value) {
  112031. var reflectionWeight = value;
  112032. if (reflectionWeight < 0.5) {
  112033. reflectionWeight = reflectionWeight * 2.0;
  112034. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112035. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112036. }
  112037. else {
  112038. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112039. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112040. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112041. }
  112042. },
  112043. enumerable: true,
  112044. configurable: true
  112045. });
  112046. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112047. /**
  112048. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112049. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112050. * Recommended to be keep at 1.0 except for special cases.
  112051. */
  112052. get: function () {
  112053. return this._fovMultiplier;
  112054. },
  112055. set: function (value) {
  112056. if (isNaN(value)) {
  112057. value = 1.0;
  112058. }
  112059. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112060. },
  112061. enumerable: true,
  112062. configurable: true
  112063. });
  112064. /**
  112065. * Attaches a new image processing configuration to the PBR Material.
  112066. * @param configuration (if null the scene configuration will be use)
  112067. */
  112068. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112069. var _this = this;
  112070. if (configuration === this._imageProcessingConfiguration) {
  112071. return;
  112072. }
  112073. // Detaches observer.
  112074. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112075. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112076. }
  112077. // Pick the scene configuration if needed.
  112078. if (!configuration) {
  112079. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112080. }
  112081. else {
  112082. this._imageProcessingConfiguration = configuration;
  112083. }
  112084. // Attaches observer.
  112085. if (this._imageProcessingConfiguration) {
  112086. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112087. _this._computePrimaryColorFromPerceptualColor();
  112088. _this._markAllSubMeshesAsImageProcessingDirty();
  112089. });
  112090. }
  112091. };
  112092. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112093. /**
  112094. * Gets the image processing configuration used either in this material.
  112095. */
  112096. get: function () {
  112097. return this._imageProcessingConfiguration;
  112098. },
  112099. /**
  112100. * Sets the Default image processing configuration used either in the this material.
  112101. *
  112102. * If sets to null, the scene one is in use.
  112103. */
  112104. set: function (value) {
  112105. this._attachImageProcessingConfiguration(value);
  112106. // Ensure the effect will be rebuilt.
  112107. this._markAllSubMeshesAsTexturesDirty();
  112108. },
  112109. enumerable: true,
  112110. configurable: true
  112111. });
  112112. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  112113. /**
  112114. * Gets wether the color curves effect is enabled.
  112115. */
  112116. get: function () {
  112117. return this.imageProcessingConfiguration.colorCurvesEnabled;
  112118. },
  112119. /**
  112120. * Sets wether the color curves effect is enabled.
  112121. */
  112122. set: function (value) {
  112123. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  112124. },
  112125. enumerable: true,
  112126. configurable: true
  112127. });
  112128. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  112129. /**
  112130. * Gets wether the color grading effect is enabled.
  112131. */
  112132. get: function () {
  112133. return this.imageProcessingConfiguration.colorGradingEnabled;
  112134. },
  112135. /**
  112136. * Gets wether the color grading effect is enabled.
  112137. */
  112138. set: function (value) {
  112139. this.imageProcessingConfiguration.colorGradingEnabled = value;
  112140. },
  112141. enumerable: true,
  112142. configurable: true
  112143. });
  112144. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  112145. /**
  112146. * Gets wether tonemapping is enabled or not.
  112147. */
  112148. get: function () {
  112149. return this._imageProcessingConfiguration.toneMappingEnabled;
  112150. },
  112151. /**
  112152. * Sets wether tonemapping is enabled or not
  112153. */
  112154. set: function (value) {
  112155. this._imageProcessingConfiguration.toneMappingEnabled = value;
  112156. },
  112157. enumerable: true,
  112158. configurable: true
  112159. });
  112160. ;
  112161. ;
  112162. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  112163. /**
  112164. * The camera exposure used on this material.
  112165. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  112166. * This corresponds to a photographic exposure.
  112167. */
  112168. get: function () {
  112169. return this._imageProcessingConfiguration.exposure;
  112170. },
  112171. /**
  112172. * The camera exposure used on this material.
  112173. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  112174. * This corresponds to a photographic exposure.
  112175. */
  112176. set: function (value) {
  112177. this._imageProcessingConfiguration.exposure = value;
  112178. },
  112179. enumerable: true,
  112180. configurable: true
  112181. });
  112182. ;
  112183. ;
  112184. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  112185. /**
  112186. * Gets The camera contrast used on this material.
  112187. */
  112188. get: function () {
  112189. return this._imageProcessingConfiguration.contrast;
  112190. },
  112191. /**
  112192. * Sets The camera contrast used on this material.
  112193. */
  112194. set: function (value) {
  112195. this._imageProcessingConfiguration.contrast = value;
  112196. },
  112197. enumerable: true,
  112198. configurable: true
  112199. });
  112200. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  112201. /**
  112202. * Gets the Color Grading 2D Lookup Texture.
  112203. */
  112204. get: function () {
  112205. return this._imageProcessingConfiguration.colorGradingTexture;
  112206. },
  112207. /**
  112208. * Sets the Color Grading 2D Lookup Texture.
  112209. */
  112210. set: function (value) {
  112211. this.imageProcessingConfiguration.colorGradingTexture = value;
  112212. },
  112213. enumerable: true,
  112214. configurable: true
  112215. });
  112216. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  112217. /**
  112218. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  112219. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  112220. * 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;
  112221. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  112222. */
  112223. get: function () {
  112224. return this.imageProcessingConfiguration.colorCurves;
  112225. },
  112226. /**
  112227. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  112228. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  112229. * 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;
  112230. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  112231. */
  112232. set: function (value) {
  112233. this.imageProcessingConfiguration.colorCurves = value;
  112234. },
  112235. enumerable: true,
  112236. configurable: true
  112237. });
  112238. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  112239. /**
  112240. * Gets a boolean indicating that current material needs to register RTT
  112241. */
  112242. get: function () {
  112243. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  112244. return true;
  112245. }
  112246. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  112247. return true;
  112248. }
  112249. return false;
  112250. },
  112251. enumerable: true,
  112252. configurable: true
  112253. });
  112254. /**
  112255. * The entire material has been created in order to prevent overdraw.
  112256. * @returns false
  112257. */
  112258. BackgroundMaterial.prototype.needAlphaTesting = function () {
  112259. return true;
  112260. };
  112261. /**
  112262. * The entire material has been created in order to prevent overdraw.
  112263. * @returns true if blending is enable
  112264. */
  112265. BackgroundMaterial.prototype.needAlphaBlending = function () {
  112266. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  112267. };
  112268. /**
  112269. * Checks wether the material is ready to be rendered for a given mesh.
  112270. * @param mesh The mesh to render
  112271. * @param subMesh The submesh to check against
  112272. * @param useInstances Specify wether or not the material is used with instances
  112273. * @returns true if all the dependencies are ready (Textures, Effects...)
  112274. */
  112275. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  112276. var _this = this;
  112277. if (useInstances === void 0) { useInstances = false; }
  112278. if (subMesh.effect && this.isFrozen) {
  112279. if (this._wasPreviouslyReady) {
  112280. return true;
  112281. }
  112282. }
  112283. if (!subMesh._materialDefines) {
  112284. subMesh._materialDefines = new BackgroundMaterialDefines();
  112285. }
  112286. var scene = this.getScene();
  112287. var defines = subMesh._materialDefines;
  112288. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  112289. if (defines._renderId === scene.getRenderId()) {
  112290. return true;
  112291. }
  112292. }
  112293. var engine = scene.getEngine();
  112294. // Lights
  112295. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  112296. defines._needNormals = true;
  112297. // Textures
  112298. if (defines._areTexturesDirty) {
  112299. defines._needUVs = false;
  112300. if (scene.texturesEnabled) {
  112301. if (scene.getEngine().getCaps().textureLOD) {
  112302. defines.TEXTURELODSUPPORT = true;
  112303. }
  112304. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112305. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  112306. return false;
  112307. }
  112308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  112309. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  112310. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  112311. defines.OPACITYFRESNEL = this._opacityFresnel;
  112312. }
  112313. else {
  112314. defines.DIFFUSE = false;
  112315. defines.DIFFUSEHASALPHA = false;
  112316. defines.GAMMADIFFUSE = false;
  112317. defines.OPACITYFRESNEL = false;
  112318. }
  112319. var reflectionTexture = this._reflectionTexture;
  112320. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112321. if (!reflectionTexture.isReadyOrNotBlocking()) {
  112322. return false;
  112323. }
  112324. defines.REFLECTION = true;
  112325. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  112326. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  112327. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  112328. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  112329. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  112330. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  112331. defines.REFLECTIONBGR = this.switchToBGR;
  112332. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  112333. defines.INVERTCUBICMAP = true;
  112334. }
  112335. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  112336. switch (reflectionTexture.coordinatesMode) {
  112337. case BABYLON.Texture.EXPLICIT_MODE:
  112338. defines.REFLECTIONMAP_EXPLICIT = true;
  112339. break;
  112340. case BABYLON.Texture.PLANAR_MODE:
  112341. defines.REFLECTIONMAP_PLANAR = true;
  112342. break;
  112343. case BABYLON.Texture.PROJECTION_MODE:
  112344. defines.REFLECTIONMAP_PROJECTION = true;
  112345. break;
  112346. case BABYLON.Texture.SKYBOX_MODE:
  112347. defines.REFLECTIONMAP_SKYBOX = true;
  112348. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  112349. break;
  112350. case BABYLON.Texture.SPHERICAL_MODE:
  112351. defines.REFLECTIONMAP_SPHERICAL = true;
  112352. break;
  112353. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  112354. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  112355. break;
  112356. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  112357. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  112358. break;
  112359. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  112360. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  112361. break;
  112362. case BABYLON.Texture.CUBIC_MODE:
  112363. case BABYLON.Texture.INVCUBIC_MODE:
  112364. default:
  112365. defines.REFLECTIONMAP_CUBIC = true;
  112366. break;
  112367. }
  112368. if (this.reflectionFresnel) {
  112369. defines.REFLECTIONFRESNEL = true;
  112370. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  112371. this._reflectionControls.x = this.reflectionAmount;
  112372. this._reflectionControls.y = this.reflectionReflectance0;
  112373. this._reflectionControls.z = this.reflectionReflectance90;
  112374. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  112375. }
  112376. else {
  112377. defines.REFLECTIONFRESNEL = false;
  112378. defines.REFLECTIONFALLOFF = false;
  112379. }
  112380. }
  112381. else {
  112382. defines.REFLECTION = false;
  112383. defines.REFLECTIONFRESNEL = false;
  112384. defines.REFLECTIONFALLOFF = false;
  112385. defines.REFLECTIONBLUR = false;
  112386. defines.REFLECTIONMAP_3D = false;
  112387. defines.REFLECTIONMAP_SPHERICAL = false;
  112388. defines.REFLECTIONMAP_PLANAR = false;
  112389. defines.REFLECTIONMAP_CUBIC = false;
  112390. defines.REFLECTIONMAP_PROJECTION = false;
  112391. defines.REFLECTIONMAP_SKYBOX = false;
  112392. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112393. defines.REFLECTIONMAP_EXPLICIT = false;
  112394. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112395. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112396. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112397. defines.INVERTCUBICMAP = false;
  112398. defines.REFLECTIONMAP_OPPOSITEZ = false;
  112399. defines.LODINREFLECTIONALPHA = false;
  112400. defines.GAMMAREFLECTION = false;
  112401. defines.RGBDREFLECTION = false;
  112402. }
  112403. }
  112404. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  112405. defines.USERGBCOLOR = this._useRGBColor;
  112406. defines.NOISE = this._enableNoise;
  112407. }
  112408. if (defines._areLightsDirty) {
  112409. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  112410. }
  112411. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  112412. if (!this._imageProcessingConfiguration.isReady()) {
  112413. return false;
  112414. }
  112415. this._imageProcessingConfiguration.prepareDefines(defines);
  112416. }
  112417. // Misc.
  112418. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  112419. // Values that need to be evaluated on every frame
  112420. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  112421. // Attribs
  112422. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  112423. if (mesh) {
  112424. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  112425. mesh.createNormals(true);
  112426. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  112427. }
  112428. }
  112429. }
  112430. // Get correct effect
  112431. if (defines.isDirty) {
  112432. defines.markAsProcessed();
  112433. scene.resetCachedMaterial();
  112434. // Fallbacks
  112435. var fallbacks = new BABYLON.EffectFallbacks();
  112436. if (defines.FOG) {
  112437. fallbacks.addFallback(0, "FOG");
  112438. }
  112439. if (defines.POINTSIZE) {
  112440. fallbacks.addFallback(1, "POINTSIZE");
  112441. }
  112442. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  112443. if (defines.NUM_BONE_INFLUENCERS > 0) {
  112444. fallbacks.addCPUSkinningFallback(0, mesh);
  112445. }
  112446. //Attributes
  112447. var attribs = [BABYLON.VertexBuffer.PositionKind];
  112448. if (defines.NORMAL) {
  112449. attribs.push(BABYLON.VertexBuffer.NormalKind);
  112450. }
  112451. if (defines.UV1) {
  112452. attribs.push(BABYLON.VertexBuffer.UVKind);
  112453. }
  112454. if (defines.UV2) {
  112455. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  112456. }
  112457. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  112458. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  112459. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  112460. "vFogInfos", "vFogColor", "pointSize",
  112461. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  112462. "vPrimaryColor", "vPrimaryColorShadow",
  112463. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  112464. "shadowLevel", "alpha",
  112465. "vBackgroundCenter", "vReflectionControl",
  112466. "vDiffuseInfos", "diffuseMatrix",
  112467. ];
  112468. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  112469. var uniformBuffers = ["Material", "Scene"];
  112470. if (BABYLON.ImageProcessingConfiguration) {
  112471. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  112472. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  112473. }
  112474. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  112475. uniformsNames: uniforms,
  112476. uniformBuffersNames: uniformBuffers,
  112477. samplers: samplers,
  112478. defines: defines,
  112479. maxSimultaneousLights: this._maxSimultaneousLights
  112480. });
  112481. var onCompiled = function (effect) {
  112482. if (_this.onCompiled) {
  112483. _this.onCompiled(effect);
  112484. }
  112485. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  112486. };
  112487. var join = defines.toString();
  112488. subMesh.setEffect(scene.getEngine().createEffect("background", {
  112489. attributes: attribs,
  112490. uniformsNames: uniforms,
  112491. uniformBuffersNames: uniformBuffers,
  112492. samplers: samplers,
  112493. defines: join,
  112494. fallbacks: fallbacks,
  112495. onCompiled: onCompiled,
  112496. onError: this.onError,
  112497. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  112498. }, engine), defines);
  112499. this.buildUniformLayout();
  112500. }
  112501. if (!subMesh.effect || !subMesh.effect.isReady()) {
  112502. return false;
  112503. }
  112504. defines._renderId = scene.getRenderId();
  112505. this._wasPreviouslyReady = true;
  112506. return true;
  112507. };
  112508. /**
  112509. * Compute the primary color according to the chosen perceptual color.
  112510. */
  112511. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  112512. if (!this.__perceptualColor) {
  112513. return;
  112514. }
  112515. this._primaryColor.copyFrom(this.__perceptualColor);
  112516. // Revert gamma space.
  112517. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  112518. // Revert image processing configuration.
  112519. if (this._imageProcessingConfiguration) {
  112520. // Revert Exposure.
  112521. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  112522. }
  112523. this._computePrimaryColors();
  112524. };
  112525. /**
  112526. * Compute the highlights and shadow colors according to their chosen levels.
  112527. */
  112528. BackgroundMaterial.prototype._computePrimaryColors = function () {
  112529. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  112530. return;
  112531. }
  112532. // Find the highlight color based on the configuration.
  112533. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  112534. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  112535. // Find the shadow color based on the configuration.
  112536. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  112537. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  112538. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  112539. };
  112540. /**
  112541. * Build the uniform buffer used in the material.
  112542. */
  112543. BackgroundMaterial.prototype.buildUniformLayout = function () {
  112544. // Order is important !
  112545. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  112546. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  112547. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  112548. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  112549. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  112550. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  112551. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  112552. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  112553. this._uniformBuffer.addUniform("pointSize", 1);
  112554. this._uniformBuffer.addUniform("shadowLevel", 1);
  112555. this._uniformBuffer.addUniform("alpha", 1);
  112556. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  112557. this._uniformBuffer.addUniform("vReflectionControl", 4);
  112558. this._uniformBuffer.create();
  112559. };
  112560. /**
  112561. * Unbind the material.
  112562. */
  112563. BackgroundMaterial.prototype.unbind = function () {
  112564. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  112565. this._uniformBuffer.setTexture("diffuseSampler", null);
  112566. }
  112567. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  112568. this._uniformBuffer.setTexture("reflectionSampler", null);
  112569. }
  112570. _super.prototype.unbind.call(this);
  112571. };
  112572. /**
  112573. * Bind only the world matrix to the material.
  112574. * @param world The world matrix to bind.
  112575. */
  112576. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  112577. this._activeEffect.setMatrix("world", world);
  112578. };
  112579. /**
  112580. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  112581. * @param world The world matrix to bind.
  112582. * @param subMesh The submesh to bind for.
  112583. */
  112584. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  112585. var scene = this.getScene();
  112586. var defines = subMesh._materialDefines;
  112587. if (!defines) {
  112588. return;
  112589. }
  112590. var effect = subMesh.effect;
  112591. if (!effect) {
  112592. return;
  112593. }
  112594. this._activeEffect = effect;
  112595. // Matrices
  112596. this.bindOnlyWorldMatrix(world);
  112597. // Bones
  112598. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  112599. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  112600. if (mustRebind) {
  112601. this._uniformBuffer.bindToEffect(effect, "Material");
  112602. this.bindViewProjection(effect);
  112603. var reflectionTexture = this._reflectionTexture;
  112604. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  112605. // Texture uniforms
  112606. if (scene.texturesEnabled) {
  112607. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112608. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  112609. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  112610. }
  112611. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112612. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  112613. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  112614. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  112615. }
  112616. }
  112617. if (this.shadowLevel > 0) {
  112618. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  112619. }
  112620. this._uniformBuffer.updateFloat("alpha", this.alpha);
  112621. // Point size
  112622. if (this.pointsCloud) {
  112623. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  112624. }
  112625. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  112626. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  112627. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  112628. }
  112629. else {
  112630. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  112631. }
  112632. }
  112633. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  112634. // Textures
  112635. if (scene.texturesEnabled) {
  112636. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  112637. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  112638. }
  112639. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  112640. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  112641. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  112642. }
  112643. else if (!defines.REFLECTIONBLUR) {
  112644. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  112645. }
  112646. else {
  112647. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  112648. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  112649. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  112650. }
  112651. if (defines.REFLECTIONFRESNEL) {
  112652. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  112653. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  112654. }
  112655. }
  112656. }
  112657. // Clip plane
  112658. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  112659. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  112660. }
  112661. if (mustRebind || !this.isFrozen) {
  112662. if (scene.lightsEnabled) {
  112663. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  112664. }
  112665. // View
  112666. this.bindView(effect);
  112667. // Fog
  112668. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  112669. // image processing
  112670. if (this._imageProcessingConfiguration) {
  112671. this._imageProcessingConfiguration.bind(this._activeEffect);
  112672. }
  112673. }
  112674. this._uniformBuffer.update();
  112675. this._afterBind(mesh, this._activeEffect);
  112676. };
  112677. /**
  112678. * Dispose the material.
  112679. * @param forceDisposeEffect Force disposal of the associated effect.
  112680. * @param forceDisposeTextures Force disposal of the associated textures.
  112681. */
  112682. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  112683. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  112684. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  112685. if (forceDisposeTextures) {
  112686. if (this.diffuseTexture) {
  112687. this.diffuseTexture.dispose();
  112688. }
  112689. if (this.reflectionTexture) {
  112690. this.reflectionTexture.dispose();
  112691. }
  112692. }
  112693. this._renderTargets.dispose();
  112694. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112695. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112696. }
  112697. _super.prototype.dispose.call(this, forceDisposeEffect);
  112698. };
  112699. /**
  112700. * Clones the material.
  112701. * @param name The cloned name.
  112702. * @returns The cloned material.
  112703. */
  112704. BackgroundMaterial.prototype.clone = function (name) {
  112705. var _this = this;
  112706. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  112707. };
  112708. /**
  112709. * Serializes the current material to its JSON representation.
  112710. * @returns The JSON representation.
  112711. */
  112712. BackgroundMaterial.prototype.serialize = function () {
  112713. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112714. serializationObject.customType = "BABYLON.BackgroundMaterial";
  112715. return serializationObject;
  112716. };
  112717. /**
  112718. * Gets the class name of the material
  112719. * @returns "BackgroundMaterial"
  112720. */
  112721. BackgroundMaterial.prototype.getClassName = function () {
  112722. return "BackgroundMaterial";
  112723. };
  112724. /**
  112725. * Parse a JSON input to create back a background material.
  112726. * @param source The JSON data to parse
  112727. * @param scene The scene to create the parsed material in
  112728. * @param rootUrl The root url of the assets the material depends upon
  112729. * @returns the instantiated BackgroundMaterial.
  112730. */
  112731. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  112732. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  112733. };
  112734. /**
  112735. * Standard reflectance value at parallel view angle.
  112736. */
  112737. BackgroundMaterial.StandardReflectance0 = 0.05;
  112738. /**
  112739. * Standard reflectance value at grazing angle.
  112740. */
  112741. BackgroundMaterial.StandardReflectance90 = 0.5;
  112742. __decorate([
  112743. BABYLON.serializeAsColor3()
  112744. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  112745. __decorate([
  112746. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  112747. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  112748. __decorate([
  112749. BABYLON.serializeAsColor3()
  112750. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  112751. __decorate([
  112752. BABYLON.serialize()
  112753. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  112754. __decorate([
  112755. BABYLON.serialize()
  112756. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  112757. __decorate([
  112758. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  112759. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  112760. __decorate([
  112761. BABYLON.serializeAsTexture()
  112762. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  112763. __decorate([
  112764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112765. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  112766. __decorate([
  112767. BABYLON.serialize()
  112768. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  112769. __decorate([
  112770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112771. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  112772. __decorate([
  112773. BABYLON.serializeAsTexture()
  112774. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  112775. __decorate([
  112776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112777. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  112778. __decorate([
  112779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112780. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  112781. __decorate([
  112782. BABYLON.serialize()
  112783. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  112784. __decorate([
  112785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112786. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  112787. __decorate([
  112788. BABYLON.serializeAsVector3()
  112789. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  112790. __decorate([
  112791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112792. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  112793. __decorate([
  112794. BABYLON.serialize()
  112795. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  112796. __decorate([
  112797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112798. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  112799. __decorate([
  112800. BABYLON.serialize()
  112801. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  112802. __decorate([
  112803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112804. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  112805. __decorate([
  112806. BABYLON.serialize()
  112807. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  112808. __decorate([
  112809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112810. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  112811. __decorate([
  112812. BABYLON.serialize()
  112813. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  112814. __decorate([
  112815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112816. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  112817. __decorate([
  112818. BABYLON.serialize()
  112819. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  112820. __decorate([
  112821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112822. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  112823. __decorate([
  112824. BABYLON.serialize()
  112825. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  112826. __decorate([
  112827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112828. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  112829. __decorate([
  112830. BABYLON.serialize()
  112831. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  112832. __decorate([
  112833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112834. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  112835. __decorate([
  112836. BABYLON.serialize()
  112837. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  112838. __decorate([
  112839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112840. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  112841. __decorate([
  112842. BABYLON.serialize()
  112843. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  112844. __decorate([
  112845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112846. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  112847. __decorate([
  112848. BABYLON.serializeAsImageProcessingConfiguration()
  112849. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  112850. return BackgroundMaterial;
  112851. }(BABYLON.PushMaterial));
  112852. BABYLON.BackgroundMaterial = BackgroundMaterial;
  112853. })(BABYLON || (BABYLON = {}));
  112854. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  112855. var __assign = (this && this.__assign) || function () {
  112856. __assign = Object.assign || function(t) {
  112857. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112858. s = arguments[i];
  112859. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112860. t[p] = s[p];
  112861. }
  112862. return t;
  112863. };
  112864. return __assign.apply(this, arguments);
  112865. };
  112866. var BABYLON;
  112867. (function (BABYLON) {
  112868. /**
  112869. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  112870. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  112871. * It also helps with the default setup of your imageProcessing configuration.
  112872. */
  112873. var EnvironmentHelper = /** @class */ (function () {
  112874. /**
  112875. * constructor
  112876. * @param options
  112877. * @param scene The scene to add the material to
  112878. */
  112879. function EnvironmentHelper(options, scene) {
  112880. var _this = this;
  112881. this._errorHandler = function (message, exception) {
  112882. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  112883. };
  112884. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  112885. this._scene = scene;
  112886. this.onErrorObservable = new BABYLON.Observable();
  112887. this._setupBackground();
  112888. this._setupImageProcessing();
  112889. }
  112890. /**
  112891. * Creates the default options for the helper.
  112892. */
  112893. EnvironmentHelper._getDefaultOptions = function () {
  112894. return {
  112895. createGround: true,
  112896. groundSize: 15,
  112897. groundTexture: this._groundTextureCDNUrl,
  112898. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112899. groundOpacity: 0.9,
  112900. enableGroundShadow: true,
  112901. groundShadowLevel: 0.5,
  112902. enableGroundMirror: false,
  112903. groundMirrorSizeRatio: 0.3,
  112904. groundMirrorBlurKernel: 64,
  112905. groundMirrorAmount: 1,
  112906. groundMirrorFresnelWeight: 1,
  112907. groundMirrorFallOffDistance: 0,
  112908. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  112909. groundYBias: 0.00001,
  112910. createSkybox: true,
  112911. skyboxSize: 20,
  112912. skyboxTexture: this._skyboxTextureCDNUrl,
  112913. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112914. backgroundYRotation: 0,
  112915. sizeAuto: true,
  112916. rootPosition: BABYLON.Vector3.Zero(),
  112917. setupImageProcessing: true,
  112918. environmentTexture: this._environmentTextureCDNUrl,
  112919. cameraExposure: 0.8,
  112920. cameraContrast: 1.2,
  112921. toneMappingEnabled: true,
  112922. };
  112923. };
  112924. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  112925. /**
  112926. * Gets the root mesh created by the helper.
  112927. */
  112928. get: function () {
  112929. return this._rootMesh;
  112930. },
  112931. enumerable: true,
  112932. configurable: true
  112933. });
  112934. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  112935. /**
  112936. * Gets the skybox created by the helper.
  112937. */
  112938. get: function () {
  112939. return this._skybox;
  112940. },
  112941. enumerable: true,
  112942. configurable: true
  112943. });
  112944. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  112945. /**
  112946. * Gets the skybox texture created by the helper.
  112947. */
  112948. get: function () {
  112949. return this._skyboxTexture;
  112950. },
  112951. enumerable: true,
  112952. configurable: true
  112953. });
  112954. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  112955. /**
  112956. * Gets the skybox material created by the helper.
  112957. */
  112958. get: function () {
  112959. return this._skyboxMaterial;
  112960. },
  112961. enumerable: true,
  112962. configurable: true
  112963. });
  112964. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  112965. /**
  112966. * Gets the ground mesh created by the helper.
  112967. */
  112968. get: function () {
  112969. return this._ground;
  112970. },
  112971. enumerable: true,
  112972. configurable: true
  112973. });
  112974. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  112975. /**
  112976. * Gets the ground texture created by the helper.
  112977. */
  112978. get: function () {
  112979. return this._groundTexture;
  112980. },
  112981. enumerable: true,
  112982. configurable: true
  112983. });
  112984. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  112985. /**
  112986. * Gets the ground mirror created by the helper.
  112987. */
  112988. get: function () {
  112989. return this._groundMirror;
  112990. },
  112991. enumerable: true,
  112992. configurable: true
  112993. });
  112994. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  112995. /**
  112996. * Gets the ground mirror render list to helps pushing the meshes
  112997. * you wish in the ground reflection.
  112998. */
  112999. get: function () {
  113000. if (this._groundMirror) {
  113001. return this._groundMirror.renderList;
  113002. }
  113003. return null;
  113004. },
  113005. enumerable: true,
  113006. configurable: true
  113007. });
  113008. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  113009. /**
  113010. * Gets the ground material created by the helper.
  113011. */
  113012. get: function () {
  113013. return this._groundMaterial;
  113014. },
  113015. enumerable: true,
  113016. configurable: true
  113017. });
  113018. /**
  113019. * Updates the background according to the new options
  113020. * @param options
  113021. */
  113022. EnvironmentHelper.prototype.updateOptions = function (options) {
  113023. var newOptions = __assign({}, this._options, options);
  113024. if (this._ground && !newOptions.createGround) {
  113025. this._ground.dispose();
  113026. this._ground = null;
  113027. }
  113028. if (this._groundMaterial && !newOptions.createGround) {
  113029. this._groundMaterial.dispose();
  113030. this._groundMaterial = null;
  113031. }
  113032. if (this._groundTexture) {
  113033. if (this._options.groundTexture != newOptions.groundTexture) {
  113034. this._groundTexture.dispose();
  113035. this._groundTexture = null;
  113036. }
  113037. }
  113038. if (this._skybox && !newOptions.createSkybox) {
  113039. this._skybox.dispose();
  113040. this._skybox = null;
  113041. }
  113042. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113043. this._skyboxMaterial.dispose();
  113044. this._skyboxMaterial = null;
  113045. }
  113046. if (this._skyboxTexture) {
  113047. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113048. this._skyboxTexture.dispose();
  113049. this._skyboxTexture = null;
  113050. }
  113051. }
  113052. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113053. this._groundMirror.dispose();
  113054. this._groundMirror = null;
  113055. }
  113056. if (this._scene.environmentTexture) {
  113057. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113058. this._scene.environmentTexture.dispose();
  113059. }
  113060. }
  113061. this._options = newOptions;
  113062. this._setupBackground();
  113063. this._setupImageProcessing();
  113064. };
  113065. /**
  113066. * Sets the primary color of all the available elements.
  113067. * @param color the main color to affect to the ground and the background
  113068. */
  113069. EnvironmentHelper.prototype.setMainColor = function (color) {
  113070. if (this.groundMaterial) {
  113071. this.groundMaterial.primaryColor = color;
  113072. }
  113073. if (this.skyboxMaterial) {
  113074. this.skyboxMaterial.primaryColor = color;
  113075. }
  113076. if (this.groundMirror) {
  113077. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113078. }
  113079. };
  113080. /**
  113081. * Setup the image processing according to the specified options.
  113082. */
  113083. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113084. if (this._options.setupImageProcessing) {
  113085. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113086. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113087. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113088. this._setupEnvironmentTexture();
  113089. }
  113090. };
  113091. /**
  113092. * Setup the environment texture according to the specified options.
  113093. */
  113094. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  113095. if (this._scene.environmentTexture) {
  113096. return;
  113097. }
  113098. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  113099. this._scene.environmentTexture = this._options.environmentTexture;
  113100. return;
  113101. }
  113102. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  113103. this._scene.environmentTexture = environmentTexture;
  113104. };
  113105. /**
  113106. * Setup the background according to the specified options.
  113107. */
  113108. EnvironmentHelper.prototype._setupBackground = function () {
  113109. if (!this._rootMesh) {
  113110. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  113111. }
  113112. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  113113. var sceneSize = this._getSceneSize();
  113114. if (this._options.createGround) {
  113115. this._setupGround(sceneSize);
  113116. this._setupGroundMaterial();
  113117. this._setupGroundDiffuseTexture();
  113118. if (this._options.enableGroundMirror) {
  113119. this._setupGroundMirrorTexture(sceneSize);
  113120. }
  113121. this._setupMirrorInGroundMaterial();
  113122. }
  113123. if (this._options.createSkybox) {
  113124. this._setupSkybox(sceneSize);
  113125. this._setupSkyboxMaterial();
  113126. this._setupSkyboxReflectionTexture();
  113127. }
  113128. this._rootMesh.position.x = sceneSize.rootPosition.x;
  113129. this._rootMesh.position.z = sceneSize.rootPosition.z;
  113130. this._rootMesh.position.y = sceneSize.rootPosition.y;
  113131. };
  113132. /**
  113133. * Get the scene sizes according to the setup.
  113134. */
  113135. EnvironmentHelper.prototype._getSceneSize = function () {
  113136. var _this = this;
  113137. var groundSize = this._options.groundSize;
  113138. var skyboxSize = this._options.skyboxSize;
  113139. var rootPosition = this._options.rootPosition;
  113140. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  113141. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113142. }
  113143. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  113144. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  113145. });
  113146. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  113147. if (this._options.sizeAuto) {
  113148. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  113149. this._scene.activeCamera.upperRadiusLimit) {
  113150. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  113151. skyboxSize = groundSize;
  113152. }
  113153. var sceneDiagonalLenght = sceneDiagonal.length();
  113154. if (sceneDiagonalLenght > groundSize) {
  113155. groundSize = sceneDiagonalLenght * 2;
  113156. skyboxSize = groundSize;
  113157. }
  113158. // 10 % bigger.
  113159. groundSize *= 1.1;
  113160. skyboxSize *= 1.5;
  113161. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  113162. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  113163. }
  113164. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  113165. };
  113166. /**
  113167. * Setup the ground according to the specified options.
  113168. */
  113169. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  113170. var _this = this;
  113171. if (!this._ground || this._ground.isDisposed()) {
  113172. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  113173. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  113174. this._ground.parent = this._rootMesh;
  113175. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  113176. }
  113177. this._ground.receiveShadows = this._options.enableGroundShadow;
  113178. };
  113179. /**
  113180. * Setup the ground material according to the specified options.
  113181. */
  113182. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  113183. if (!this._groundMaterial) {
  113184. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  113185. }
  113186. this._groundMaterial.alpha = this._options.groundOpacity;
  113187. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  113188. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  113189. this._groundMaterial.primaryColor = this._options.groundColor;
  113190. this._groundMaterial.useRGBColor = false;
  113191. this._groundMaterial.enableNoise = true;
  113192. if (this._ground) {
  113193. this._ground.material = this._groundMaterial;
  113194. }
  113195. };
  113196. /**
  113197. * Setup the ground diffuse texture according to the specified options.
  113198. */
  113199. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  113200. if (!this._groundMaterial) {
  113201. return;
  113202. }
  113203. if (this._groundTexture) {
  113204. return;
  113205. }
  113206. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  113207. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  113208. return;
  113209. }
  113210. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  113211. diffuseTexture.gammaSpace = false;
  113212. diffuseTexture.hasAlpha = true;
  113213. this._groundMaterial.diffuseTexture = diffuseTexture;
  113214. };
  113215. /**
  113216. * Setup the ground mirror texture according to the specified options.
  113217. */
  113218. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  113219. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113220. if (!this._groundMirror) {
  113221. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  113222. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  113223. this._groundMirror.anisotropicFilteringLevel = 1;
  113224. this._groundMirror.wrapU = wrapping;
  113225. this._groundMirror.wrapV = wrapping;
  113226. this._groundMirror.gammaSpace = false;
  113227. if (this._groundMirror.renderList) {
  113228. for (var i = 0; i < this._scene.meshes.length; i++) {
  113229. var mesh = this._scene.meshes[i];
  113230. if (mesh !== this._ground &&
  113231. mesh !== this._skybox &&
  113232. mesh !== this._rootMesh) {
  113233. this._groundMirror.renderList.push(mesh);
  113234. }
  113235. }
  113236. }
  113237. }
  113238. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  113239. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  113240. };
  113241. /**
  113242. * Setup the ground to receive the mirror texture.
  113243. */
  113244. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  113245. if (this._groundMaterial) {
  113246. this._groundMaterial.reflectionTexture = this._groundMirror;
  113247. this._groundMaterial.reflectionFresnel = true;
  113248. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  113249. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  113250. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  113251. }
  113252. };
  113253. /**
  113254. * Setup the skybox according to the specified options.
  113255. */
  113256. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  113257. var _this = this;
  113258. if (!this._skybox || this._skybox.isDisposed()) {
  113259. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  113260. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  113261. }
  113262. this._skybox.parent = this._rootMesh;
  113263. };
  113264. /**
  113265. * Setup the skybox material according to the specified options.
  113266. */
  113267. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  113268. if (!this._skybox) {
  113269. return;
  113270. }
  113271. if (!this._skyboxMaterial) {
  113272. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  113273. }
  113274. this._skyboxMaterial.useRGBColor = false;
  113275. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  113276. this._skyboxMaterial.enableNoise = true;
  113277. this._skybox.material = this._skyboxMaterial;
  113278. };
  113279. /**
  113280. * Setup the skybox reflection texture according to the specified options.
  113281. */
  113282. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  113283. if (!this._skyboxMaterial) {
  113284. return;
  113285. }
  113286. if (this._skyboxTexture) {
  113287. return;
  113288. }
  113289. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  113290. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  113291. return;
  113292. }
  113293. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  113294. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113295. this._skyboxTexture.gammaSpace = false;
  113296. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  113297. };
  113298. /**
  113299. * Dispose all the elements created by the Helper.
  113300. */
  113301. EnvironmentHelper.prototype.dispose = function () {
  113302. if (this._groundMaterial) {
  113303. this._groundMaterial.dispose(true, true);
  113304. }
  113305. if (this._skyboxMaterial) {
  113306. this._skyboxMaterial.dispose(true, true);
  113307. }
  113308. this._rootMesh.dispose(false);
  113309. };
  113310. /**
  113311. * Default ground texture URL.
  113312. */
  113313. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  113314. /**
  113315. * Default skybox texture URL.
  113316. */
  113317. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  113318. /**
  113319. * Default environment texture URL.
  113320. */
  113321. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  113322. return EnvironmentHelper;
  113323. }());
  113324. BABYLON.EnvironmentHelper = EnvironmentHelper;
  113325. })(BABYLON || (BABYLON = {}));
  113326. //# sourceMappingURL=babylon.environmentHelper.js.map
  113327. var BABYLON;
  113328. (function (BABYLON) {
  113329. /** Internal class used to store shapes for emitters */
  113330. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  113331. function ParticleSystemSetEmitterCreationOptions() {
  113332. }
  113333. return ParticleSystemSetEmitterCreationOptions;
  113334. }());
  113335. /**
  113336. * Represents a set of particle systems working together to create a specific effect
  113337. */
  113338. var ParticleSystemSet = /** @class */ (function () {
  113339. function ParticleSystemSet() {
  113340. /**
  113341. * Gets the particle system list
  113342. */
  113343. this.systems = new Array();
  113344. }
  113345. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  113346. /**
  113347. * Gets the emitter node used with this set
  113348. */
  113349. get: function () {
  113350. return this._emitterNode;
  113351. },
  113352. enumerable: true,
  113353. configurable: true
  113354. });
  113355. /**
  113356. * Creates a new emitter mesh as a sphere
  113357. * @param options defines the options used to create the sphere
  113358. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  113359. * @param scene defines the hosting scene
  113360. */
  113361. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  113362. if (this._emitterNode) {
  113363. this._emitterNode.dispose();
  113364. }
  113365. this._emitterCreationOptions = {
  113366. kind: "Sphere",
  113367. options: options,
  113368. renderingGroupId: renderingGroupId
  113369. };
  113370. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  113371. emitterMesh.renderingGroupId = renderingGroupId;
  113372. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  113373. material.emissiveColor = options.color;
  113374. emitterMesh.material = material;
  113375. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113376. var system = _a[_i];
  113377. system.emitter = emitterMesh;
  113378. }
  113379. this._emitterNode = emitterMesh;
  113380. };
  113381. /**
  113382. * Starts all particle systems of the set
  113383. * @param emitter defines an optional mesh to use as emitter for the particle systems
  113384. */
  113385. ParticleSystemSet.prototype.start = function (emitter) {
  113386. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113387. var system = _a[_i];
  113388. if (emitter) {
  113389. system.emitter = emitter;
  113390. }
  113391. system.start();
  113392. }
  113393. };
  113394. /**
  113395. * Release all associated resources
  113396. */
  113397. ParticleSystemSet.prototype.dispose = function () {
  113398. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113399. var system = _a[_i];
  113400. system.dispose();
  113401. }
  113402. this.systems = [];
  113403. if (this._emitterNode) {
  113404. this._emitterNode.dispose();
  113405. this._emitterNode = null;
  113406. }
  113407. };
  113408. /**
  113409. * Serialize the set into a JSON compatible object
  113410. * @returns a JSON compatible representation of the set
  113411. */
  113412. ParticleSystemSet.prototype.serialize = function () {
  113413. var result = {};
  113414. result.systems = [];
  113415. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  113416. var system = _a[_i];
  113417. result.systems.push(system.serialize());
  113418. }
  113419. if (this._emitterNode) {
  113420. result.emitter = this._emitterCreationOptions;
  113421. }
  113422. return result;
  113423. };
  113424. /**
  113425. * Parse a new ParticleSystemSet from a serialized source
  113426. * @param data defines a JSON compatible representation of the set
  113427. * @param scene defines the hosting scene
  113428. * @param gpu defines if we want GPU particles or CPU particles
  113429. * @returns a new ParticleSystemSet
  113430. */
  113431. ParticleSystemSet.Parse = function (data, scene, gpu) {
  113432. if (gpu === void 0) { gpu = false; }
  113433. var result = new ParticleSystemSet();
  113434. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  113435. scene = scene || BABYLON.Engine.LastCreatedScene;
  113436. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  113437. var system = _a[_i];
  113438. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  113439. }
  113440. if (data.emitter) {
  113441. var options = data.emitter.options;
  113442. switch (data.emitter.kind) {
  113443. case "Sphere":
  113444. result.setEmitterAsSphere({
  113445. diameter: options.diameter,
  113446. segments: options.segments,
  113447. color: BABYLON.Color3.FromArray(options.color)
  113448. }, data.emitter.renderingGroupId, scene);
  113449. break;
  113450. }
  113451. }
  113452. return result;
  113453. };
  113454. return ParticleSystemSet;
  113455. }());
  113456. BABYLON.ParticleSystemSet = ParticleSystemSet;
  113457. })(BABYLON || (BABYLON = {}));
  113458. //# sourceMappingURL=babylon.particleSystemSet.js.map
  113459. var BABYLON;
  113460. (function (BABYLON) {
  113461. /**
  113462. * This class is made for on one-liner static method to help creating particle system set.
  113463. */
  113464. var ParticleHelper = /** @class */ (function () {
  113465. function ParticleHelper() {
  113466. }
  113467. /**
  113468. * Create a default particle system that you can tweak
  113469. * @param emitter defines the emitter to use
  113470. * @param capacity defines the system capacity (default is 500 particles)
  113471. * @param scene defines the hosting scene
  113472. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  113473. * @returns the new Particle system
  113474. */
  113475. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  113476. if (capacity === void 0) { capacity = 500; }
  113477. if (useGPU === void 0) { useGPU = false; }
  113478. var system;
  113479. if (useGPU) {
  113480. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  113481. }
  113482. else {
  113483. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  113484. }
  113485. system.emitter = emitter;
  113486. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  113487. system.createConeEmitter(0.1, Math.PI / 4);
  113488. // Particle color
  113489. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  113490. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  113491. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  113492. // Particle Size
  113493. system.minSize = 0.1;
  113494. system.maxSize = 0.1;
  113495. // Emission speed
  113496. system.minEmitPower = 2;
  113497. system.maxEmitPower = 2;
  113498. // Update speed
  113499. system.updateSpeed = 1 / 60;
  113500. system.emitRate = 30;
  113501. return system;
  113502. };
  113503. /**
  113504. * This is the main static method (one-liner) of this helper to create different particle systems
  113505. * @param type This string represents the type to the particle system to create
  113506. * @param scene The scene where the particle system should live
  113507. * @param gpu If the system will use gpu
  113508. * @returns the ParticleSystemSet created
  113509. */
  113510. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  113511. if (gpu === void 0) { gpu = false; }
  113512. if (!scene) {
  113513. scene = BABYLON.Engine.LastCreatedScene;
  113514. ;
  113515. }
  113516. var token = {};
  113517. scene._addPendingData(token);
  113518. return new Promise(function (resolve, reject) {
  113519. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  113520. scene._removePendingData(token);
  113521. return reject("Particle system with GPU is not supported.");
  113522. }
  113523. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  113524. scene._removePendingData(token);
  113525. var newData = JSON.parse(data.toString());
  113526. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  113527. }, undefined, undefined, undefined, function (req, exception) {
  113528. scene._removePendingData(token);
  113529. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  113530. });
  113531. });
  113532. };
  113533. /**
  113534. * Static function used to export a particle system to a ParticleSystemSet variable.
  113535. * Please note that the emitter shape is not exported
  113536. * @param system defines the particle systems to export
  113537. */
  113538. ParticleHelper.ExportSet = function (systems) {
  113539. var set = new BABYLON.ParticleSystemSet();
  113540. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  113541. var system = systems_1[_i];
  113542. set.systems.push(system);
  113543. }
  113544. return set;
  113545. };
  113546. /**
  113547. * Gets or sets base Assets URL
  113548. */
  113549. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  113550. return ParticleHelper;
  113551. }());
  113552. BABYLON.ParticleHelper = ParticleHelper;
  113553. })(BABYLON || (BABYLON = {}));
  113554. //# sourceMappingURL=babylon.particleHelper.js.map
  113555. var BABYLON;
  113556. (function (BABYLON) {
  113557. /**
  113558. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  113559. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  113560. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  113561. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  113562. */
  113563. var VideoDome = /** @class */ (function (_super) {
  113564. __extends(VideoDome, _super);
  113565. /**
  113566. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  113567. * @param name Element's name, child elements will append suffixes for their own names.
  113568. * @param urlsOrVideo defines the url(s) or the video element to use
  113569. * @param options An object containing optional or exposed sub element properties
  113570. */
  113571. function VideoDome(name, urlsOrVideo, options, scene) {
  113572. var _this = _super.call(this, name, scene) || this;
  113573. _this._useDirectMapping = false;
  113574. // set defaults and manage values
  113575. name = name || "videoDome";
  113576. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  113577. options.clickToPlay = Boolean(options.clickToPlay);
  113578. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  113579. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  113580. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  113581. if (options.useDirectMapping === undefined) {
  113582. _this._useDirectMapping = true;
  113583. }
  113584. else {
  113585. _this._useDirectMapping = options.useDirectMapping;
  113586. }
  113587. _this._setReady(false);
  113588. // create
  113589. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  113590. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  113591. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  113592. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  113593. texture.onLoadObservable.addOnce(function () {
  113594. _this._setReady(true);
  113595. });
  113596. // configure material
  113597. material.useEquirectangularFOV = true;
  113598. material.fovMultiplier = 1.0;
  113599. material.opacityFresnel = false;
  113600. if (_this._useDirectMapping) {
  113601. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113602. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113603. material.diffuseTexture = texture;
  113604. }
  113605. else {
  113606. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  113607. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113608. material.reflectionTexture = texture;
  113609. }
  113610. // configure mesh
  113611. _this._mesh.material = material;
  113612. _this._mesh.parent = _this;
  113613. // optional configuration
  113614. if (options.clickToPlay) {
  113615. scene.onPointerUp = function () {
  113616. _this._videoTexture.video.play();
  113617. };
  113618. }
  113619. return _this;
  113620. }
  113621. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  113622. /**
  113623. * Gets the video texture being displayed on the sphere
  113624. */
  113625. get: function () {
  113626. return this._videoTexture;
  113627. },
  113628. enumerable: true,
  113629. configurable: true
  113630. });
  113631. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  113632. /**
  113633. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  113634. * Also see the options.resolution property.
  113635. */
  113636. get: function () {
  113637. return this._material.fovMultiplier;
  113638. },
  113639. set: function (value) {
  113640. this._material.fovMultiplier = value;
  113641. },
  113642. enumerable: true,
  113643. configurable: true
  113644. });
  113645. /**
  113646. * Releases resources associated with this node.
  113647. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  113648. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  113649. */
  113650. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  113651. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  113652. this._videoTexture.dispose();
  113653. this._mesh.dispose();
  113654. this._material.dispose();
  113655. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  113656. };
  113657. return VideoDome;
  113658. }(BABYLON.TransformNode));
  113659. BABYLON.VideoDome = VideoDome;
  113660. })(BABYLON || (BABYLON = {}));
  113661. //# sourceMappingURL=babylon.videoDome.js.map
  113662. var BABYLON;
  113663. (function (BABYLON) {
  113664. /**
  113665. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  113666. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  113667. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  113668. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  113669. */
  113670. var PhotoDome = /** @class */ (function (_super) {
  113671. __extends(PhotoDome, _super);
  113672. /**
  113673. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  113674. * @param name Element's name, child elements will append suffixes for their own names.
  113675. * @param urlsOfPhoto defines the url of the photo to display
  113676. * @param options defines an object containing optional or exposed sub element properties
  113677. * @param onError defines a callback called when an error occured while loading the texture
  113678. */
  113679. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  113680. if (onError === void 0) { onError = null; }
  113681. var _this = _super.call(this, name, scene) || this;
  113682. _this._useDirectMapping = false;
  113683. /**
  113684. * Observable raised when an error occured while loading the 360 image
  113685. */
  113686. _this.onLoadErrorObservable = new BABYLON.Observable();
  113687. // set defaults and manage values
  113688. name = name || "photoDome";
  113689. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  113690. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  113691. if (options.useDirectMapping === undefined) {
  113692. _this._useDirectMapping = true;
  113693. }
  113694. else {
  113695. _this._useDirectMapping = options.useDirectMapping;
  113696. }
  113697. _this._setReady(false);
  113698. // create
  113699. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  113700. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  113701. // configure material
  113702. material.opacityFresnel = false;
  113703. material.useEquirectangularFOV = true;
  113704. material.fovMultiplier = 1.0;
  113705. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  113706. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  113707. if (onError) {
  113708. onError(message, exception);
  113709. }
  113710. });
  113711. _this.photoTexture.onLoadObservable.addOnce(function () {
  113712. _this._setReady(true);
  113713. });
  113714. // configure mesh
  113715. _this._mesh.material = material;
  113716. _this._mesh.parent = _this;
  113717. return _this;
  113718. }
  113719. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  113720. /**
  113721. * Gets or sets the texture being displayed on the sphere
  113722. */
  113723. get: function () {
  113724. return this._photoTexture;
  113725. },
  113726. set: function (value) {
  113727. if (this._photoTexture === value) {
  113728. return;
  113729. }
  113730. this._photoTexture = value;
  113731. if (this._useDirectMapping) {
  113732. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113733. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113734. this._material.diffuseTexture = this._photoTexture;
  113735. }
  113736. else {
  113737. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  113738. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113739. this._material.reflectionTexture = this._photoTexture;
  113740. }
  113741. },
  113742. enumerable: true,
  113743. configurable: true
  113744. });
  113745. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  113746. /**
  113747. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  113748. * Also see the options.resolution property.
  113749. */
  113750. get: function () {
  113751. return this._material.fovMultiplier;
  113752. },
  113753. set: function (value) {
  113754. this._material.fovMultiplier = value;
  113755. },
  113756. enumerable: true,
  113757. configurable: true
  113758. });
  113759. /**
  113760. * Releases resources associated with this node.
  113761. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  113762. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  113763. */
  113764. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  113765. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  113766. this._photoTexture.dispose();
  113767. this._mesh.dispose();
  113768. this._material.dispose();
  113769. this.onLoadErrorObservable.clear();
  113770. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  113771. };
  113772. return PhotoDome;
  113773. }(BABYLON.TransformNode));
  113774. BABYLON.PhotoDome = PhotoDome;
  113775. })(BABYLON || (BABYLON = {}));
  113776. //# sourceMappingURL=babylon.photoDome.js.map
  113777. var BABYLON;
  113778. (function (BABYLON) {
  113779. /** @hidden */
  113780. var _OcclusionDataStorage = /** @class */ (function () {
  113781. function _OcclusionDataStorage() {
  113782. /** @hidden */
  113783. this.occlusionInternalRetryCounter = 0;
  113784. /** @hidden */
  113785. this.isOcclusionQueryInProgress = false;
  113786. /** @hidden */
  113787. this.isOccluded = false;
  113788. /** @hidden */
  113789. this.occlusionRetryCount = -1;
  113790. /** @hidden */
  113791. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  113792. /** @hidden */
  113793. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  113794. }
  113795. return _OcclusionDataStorage;
  113796. }());
  113797. BABYLON.Engine.prototype.createQuery = function () {
  113798. return this._gl.createQuery();
  113799. };
  113800. BABYLON.Engine.prototype.deleteQuery = function (query) {
  113801. this._gl.deleteQuery(query);
  113802. return this;
  113803. };
  113804. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  113805. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  113806. };
  113807. BABYLON.Engine.prototype.getQueryResult = function (query) {
  113808. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  113809. };
  113810. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  113811. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113812. this._gl.beginQuery(glAlgorithm, query);
  113813. return this;
  113814. };
  113815. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  113816. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  113817. this._gl.endQuery(glAlgorithm);
  113818. return this;
  113819. };
  113820. BABYLON.Engine.prototype._createTimeQuery = function () {
  113821. var timerQuery = this.getCaps().timerQuery;
  113822. if (timerQuery.createQueryEXT) {
  113823. return timerQuery.createQueryEXT();
  113824. }
  113825. return this.createQuery();
  113826. };
  113827. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  113828. var timerQuery = this.getCaps().timerQuery;
  113829. if (timerQuery.deleteQueryEXT) {
  113830. timerQuery.deleteQueryEXT(query);
  113831. return;
  113832. }
  113833. this.deleteQuery(query);
  113834. };
  113835. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  113836. var timerQuery = this.getCaps().timerQuery;
  113837. if (timerQuery.getQueryObjectEXT) {
  113838. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  113839. }
  113840. return this.getQueryResult(query);
  113841. };
  113842. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  113843. var timerQuery = this.getCaps().timerQuery;
  113844. if (timerQuery.getQueryObjectEXT) {
  113845. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  113846. }
  113847. return this.isQueryResultAvailable(query);
  113848. };
  113849. BABYLON.Engine.prototype.startTimeQuery = function () {
  113850. var caps = this.getCaps();
  113851. var timerQuery = caps.timerQuery;
  113852. if (!timerQuery) {
  113853. return null;
  113854. }
  113855. var token = new BABYLON._TimeToken();
  113856. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113857. if (caps.canUseTimestampForTimerQuery) {
  113858. token._startTimeQuery = this._createTimeQuery();
  113859. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  113860. }
  113861. else {
  113862. if (this._currentNonTimestampToken) {
  113863. return this._currentNonTimestampToken;
  113864. }
  113865. token._timeElapsedQuery = this._createTimeQuery();
  113866. if (timerQuery.beginQueryEXT) {
  113867. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113868. }
  113869. else {
  113870. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113871. }
  113872. this._currentNonTimestampToken = token;
  113873. }
  113874. return token;
  113875. };
  113876. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  113877. var caps = this.getCaps();
  113878. var timerQuery = caps.timerQuery;
  113879. if (!timerQuery || !token) {
  113880. return -1;
  113881. }
  113882. if (caps.canUseTimestampForTimerQuery) {
  113883. if (!token._startTimeQuery) {
  113884. return -1;
  113885. }
  113886. if (!token._endTimeQuery) {
  113887. token._endTimeQuery = this._createTimeQuery();
  113888. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  113889. }
  113890. }
  113891. else if (!token._timeElapsedQueryEnded) {
  113892. if (!token._timeElapsedQuery) {
  113893. return -1;
  113894. }
  113895. if (timerQuery.endQueryEXT) {
  113896. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  113897. }
  113898. else {
  113899. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  113900. }
  113901. token._timeElapsedQueryEnded = true;
  113902. }
  113903. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113904. var available = false;
  113905. if (token._endTimeQuery) {
  113906. available = this._getTimeQueryAvailability(token._endTimeQuery);
  113907. }
  113908. else if (token._timeElapsedQuery) {
  113909. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  113910. }
  113911. if (available && !disjoint) {
  113912. var result = 0;
  113913. if (caps.canUseTimestampForTimerQuery) {
  113914. if (!token._startTimeQuery || !token._endTimeQuery) {
  113915. return -1;
  113916. }
  113917. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  113918. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  113919. result = timeEnd - timeStart;
  113920. this._deleteTimeQuery(token._startTimeQuery);
  113921. this._deleteTimeQuery(token._endTimeQuery);
  113922. token._startTimeQuery = null;
  113923. token._endTimeQuery = null;
  113924. }
  113925. else {
  113926. if (!token._timeElapsedQuery) {
  113927. return -1;
  113928. }
  113929. result = this._getTimeQueryResult(token._timeElapsedQuery);
  113930. this._deleteTimeQuery(token._timeElapsedQuery);
  113931. token._timeElapsedQuery = null;
  113932. token._timeElapsedQueryEnded = false;
  113933. this._currentNonTimestampToken = null;
  113934. }
  113935. return result;
  113936. }
  113937. return -1;
  113938. };
  113939. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  113940. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  113941. };
  113942. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  113943. get: function () {
  113944. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  113945. },
  113946. enumerable: false,
  113947. configurable: true
  113948. });
  113949. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  113950. get: function () {
  113951. if (!this.__occlusionDataStorage) {
  113952. this.__occlusionDataStorage = new _OcclusionDataStorage();
  113953. }
  113954. return this.__occlusionDataStorage;
  113955. },
  113956. enumerable: false,
  113957. configurable: true
  113958. });
  113959. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  113960. get: function () {
  113961. return this._occlusionDataStorage.isOccluded;
  113962. },
  113963. set: function (value) {
  113964. this._occlusionDataStorage.isOccluded = value;
  113965. },
  113966. enumerable: true,
  113967. configurable: true
  113968. });
  113969. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  113970. get: function () {
  113971. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  113972. },
  113973. set: function (value) {
  113974. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  113975. },
  113976. enumerable: true,
  113977. configurable: true
  113978. });
  113979. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  113980. get: function () {
  113981. return this._occlusionDataStorage.occlusionType;
  113982. },
  113983. set: function (value) {
  113984. this._occlusionDataStorage.occlusionType = value;
  113985. },
  113986. enumerable: true,
  113987. configurable: true
  113988. });
  113989. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  113990. get: function () {
  113991. return this._occlusionDataStorage.occlusionRetryCount;
  113992. },
  113993. set: function (value) {
  113994. this._occlusionDataStorage.occlusionRetryCount = value;
  113995. },
  113996. enumerable: true,
  113997. configurable: true
  113998. });
  113999. // We also need to update AbstractMesh as there is a portion of the code there
  114000. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  114001. var dataStorage = this._occlusionDataStorage;
  114002. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  114003. dataStorage.isOccluded = false;
  114004. return false;
  114005. }
  114006. var engine = this.getEngine();
  114007. if (engine.webGLVersion < 2) {
  114008. dataStorage.isOccluded = false;
  114009. return false;
  114010. }
  114011. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  114012. dataStorage.isOccluded = false;
  114013. return false;
  114014. }
  114015. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  114016. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  114017. if (isOcclusionQueryAvailable) {
  114018. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  114019. dataStorage.isOcclusionQueryInProgress = false;
  114020. dataStorage.occlusionInternalRetryCounter = 0;
  114021. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  114022. }
  114023. else {
  114024. dataStorage.occlusionInternalRetryCounter++;
  114025. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  114026. dataStorage.isOcclusionQueryInProgress = false;
  114027. dataStorage.occlusionInternalRetryCounter = 0;
  114028. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114029. // if strict continue the last state of the object.
  114030. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114031. }
  114032. else {
  114033. return false;
  114034. }
  114035. }
  114036. }
  114037. var scene = this.getScene();
  114038. if (scene.getBoundingBoxRenderer) {
  114039. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114040. if (!this._occlusionQuery) {
  114041. this._occlusionQuery = engine.createQuery();
  114042. }
  114043. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114044. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114045. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114046. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114047. }
  114048. return dataStorage.isOccluded;
  114049. };
  114050. })(BABYLON || (BABYLON = {}));
  114051. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114052. var BABYLON;
  114053. (function (BABYLON) {
  114054. /**
  114055. * Class used to generate noise procedural textures
  114056. */
  114057. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114058. __extends(NoiseProceduralTexture, _super);
  114059. /**
  114060. * Creates a new NoiseProceduralTexture
  114061. * @param name defines the name fo the texture
  114062. * @param size defines the size of the texture (default is 256)
  114063. * @param scene defines the hosting scene
  114064. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114065. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114066. */
  114067. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114068. if (size === void 0) { size = 256; }
  114069. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114070. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114071. _this._time = 0;
  114072. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114073. _this.brightness = 0.2;
  114074. /** Defines the number of octaves to process */
  114075. _this.octaves = 3;
  114076. /** Defines the level of persistence (0.8 by default) */
  114077. _this.persistence = 0.8;
  114078. /** Gets or sets animation speed factor (default is 1) */
  114079. _this.animationSpeedFactor = 1;
  114080. _this._updateShaderUniforms();
  114081. return _this;
  114082. }
  114083. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114084. var scene = this.getScene();
  114085. if (!scene) {
  114086. return;
  114087. }
  114088. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114089. this.setFloat("brightness", this.brightness);
  114090. this.setFloat("persistence", this.persistence);
  114091. this.setFloat("timeScale", this._time);
  114092. };
  114093. NoiseProceduralTexture.prototype._getDefines = function () {
  114094. return "#define OCTAVES " + (this.octaves | 0);
  114095. };
  114096. /** Generate the current state of the procedural texture */
  114097. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  114098. this._updateShaderUniforms();
  114099. _super.prototype.render.call(this, useCameraPostProcess);
  114100. };
  114101. /**
  114102. * Serializes this noise procedural texture
  114103. * @returns a serialized noise procedural texture object
  114104. */
  114105. NoiseProceduralTexture.prototype.serialize = function () {
  114106. var serializationObject = {};
  114107. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  114108. serializationObject.brightness = this.brightness;
  114109. serializationObject.octaves = this.octaves;
  114110. serializationObject.persistence = this.persistence;
  114111. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  114112. serializationObject.size = this.getSize().width;
  114113. serializationObject.generateMipMaps = this._generateMipMaps;
  114114. return serializationObject;
  114115. };
  114116. /**
  114117. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  114118. * @param parsedTexture defines parsed texture data
  114119. * @param scene defines the current scene
  114120. * @param rootUrl defines the root URL containing noise procedural texture information
  114121. * @returns a parsed NoiseProceduralTexture
  114122. */
  114123. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  114124. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  114125. texture.brightness = parsedTexture.brightness;
  114126. texture.octaves = parsedTexture.octaves;
  114127. texture.persistence = parsedTexture.persistence;
  114128. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  114129. return texture;
  114130. };
  114131. return NoiseProceduralTexture;
  114132. }(BABYLON.ProceduralTexture));
  114133. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  114134. })(BABYLON || (BABYLON = {}));
  114135. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  114136. var __assign = (this && this.__assign) || function () {
  114137. __assign = Object.assign || function(t) {
  114138. for (var s, i = 1, n = arguments.length; i < n; i++) {
  114139. s = arguments[i];
  114140. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  114141. t[p] = s[p];
  114142. }
  114143. return t;
  114144. };
  114145. return __assign.apply(this, arguments);
  114146. };
  114147. var BABYLON;
  114148. (function (BABYLON) {
  114149. /**
  114150. * This can helps recording videos from BabylonJS.
  114151. * This is based on the available WebRTC functionalities of the browser.
  114152. *
  114153. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  114154. */
  114155. var VideoRecorder = /** @class */ (function () {
  114156. /**
  114157. * Create a new VideoCapture object which can help converting what you see in Babylon to
  114158. * a video file.
  114159. * @param engine Defines the BabylonJS Engine you wish to record
  114160. * @param options Defines options that can be used to customized the capture
  114161. */
  114162. function VideoRecorder(engine, options) {
  114163. if (options === void 0) { options = null; }
  114164. if (!VideoRecorder.IsSupported(engine)) {
  114165. throw "Your browser does not support recording so far.";
  114166. }
  114167. var canvas = engine.getRenderingCanvas();
  114168. if (!canvas) {
  114169. throw "The babylon engine must have a canvas to be recorded";
  114170. }
  114171. this._canvas = canvas;
  114172. this._canvas.isRecording = false;
  114173. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  114174. var stream = this._canvas.captureStream(this._options.fps);
  114175. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  114176. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  114177. this._mediaRecorder.onerror = this._handleError.bind(this);
  114178. this._mediaRecorder.onstop = this._handleStop.bind(this);
  114179. }
  114180. /**
  114181. * Returns wehther or not the VideoRecorder is available in your browser.
  114182. * @param engine Defines the Babylon Engine to check the support for
  114183. * @returns true if supported otherwise false
  114184. */
  114185. VideoRecorder.IsSupported = function (engine) {
  114186. var canvas = engine.getRenderingCanvas();
  114187. return (!!canvas && typeof canvas.captureStream === "function");
  114188. };
  114189. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  114190. /**
  114191. * True wether a recording is already in progress.
  114192. */
  114193. get: function () {
  114194. return !!this._canvas && this._canvas.isRecording;
  114195. },
  114196. enumerable: true,
  114197. configurable: true
  114198. });
  114199. /**
  114200. * Stops the current recording before the default capture timeout passed in the startRecording
  114201. * functions.
  114202. */
  114203. VideoRecorder.prototype.stopRecording = function () {
  114204. if (!this._canvas || !this._mediaRecorder) {
  114205. return;
  114206. }
  114207. if (!this.isRecording) {
  114208. return;
  114209. }
  114210. this._canvas.isRecording = false;
  114211. this._mediaRecorder.stop();
  114212. };
  114213. /**
  114214. * Starts recording the canvas for a max duration specified in parameters.
  114215. * @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.
  114216. * @param maxDuration Defines the maximum recording time in seconds.
  114217. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  114218. * @return a promise callback at the end of the recording with the video data in Blob.
  114219. */
  114220. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  114221. var _this = this;
  114222. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  114223. if (maxDuration === void 0) { maxDuration = 7; }
  114224. if (!this._canvas || !this._mediaRecorder) {
  114225. throw "Recorder has already been disposed";
  114226. }
  114227. if (this.isRecording) {
  114228. throw "Recording already in progress";
  114229. }
  114230. if (maxDuration > 0) {
  114231. setTimeout(function () {
  114232. _this.stopRecording();
  114233. }, maxDuration * 1000);
  114234. }
  114235. this._fileName = fileName;
  114236. this._recordedChunks = [];
  114237. this._resolve = null;
  114238. this._reject = null;
  114239. this._canvas.isRecording = true;
  114240. this._mediaRecorder.start(this._options.recordChunckSize);
  114241. return new Promise(function (resolve, reject) {
  114242. _this._resolve = resolve;
  114243. _this._reject = reject;
  114244. });
  114245. };
  114246. /**
  114247. * Releases internal resources used during the recording.
  114248. */
  114249. VideoRecorder.prototype.dispose = function () {
  114250. this._canvas = null;
  114251. this._mediaRecorder = null;
  114252. this._recordedChunks = [];
  114253. this._fileName = null;
  114254. this._resolve = null;
  114255. this._reject = null;
  114256. };
  114257. VideoRecorder.prototype._handleDataAvailable = function (event) {
  114258. if (event.data.size > 0) {
  114259. this._recordedChunks.push(event.data);
  114260. }
  114261. };
  114262. VideoRecorder.prototype._handleError = function (event) {
  114263. this.stopRecording();
  114264. if (this._reject) {
  114265. this._reject(event.error);
  114266. }
  114267. else {
  114268. throw new event.error;
  114269. }
  114270. };
  114271. VideoRecorder.prototype._handleStop = function () {
  114272. this.stopRecording();
  114273. var superBuffer = new Blob(this._recordedChunks);
  114274. if (this._resolve) {
  114275. this._resolve(superBuffer);
  114276. }
  114277. window.URL.createObjectURL(superBuffer);
  114278. if (this._fileName) {
  114279. BABYLON.Tools.Download(superBuffer, this._fileName);
  114280. }
  114281. };
  114282. VideoRecorder._defaultOptions = {
  114283. mimeType: "video/webm",
  114284. fps: 25,
  114285. recordChunckSize: 3000
  114286. };
  114287. return VideoRecorder;
  114288. }());
  114289. BABYLON.VideoRecorder = VideoRecorder;
  114290. })(BABYLON || (BABYLON = {}));
  114291. //# sourceMappingURL=babylon.videoRecorder.js.map
  114292. var BABYLON;
  114293. (function (BABYLON) {
  114294. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  114295. if (replace === void 0) { replace = false; }
  114296. // Dispose existing light in replace mode.
  114297. if (replace) {
  114298. if (this.lights) {
  114299. for (var i = 0; i < this.lights.length; i++) {
  114300. this.lights[i].dispose();
  114301. }
  114302. }
  114303. }
  114304. // Light
  114305. if (this.lights.length === 0) {
  114306. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  114307. }
  114308. };
  114309. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  114310. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  114311. if (replace === void 0) { replace = false; }
  114312. if (attachCameraControls === void 0) { attachCameraControls = false; }
  114313. // Dispose existing camera in replace mode.
  114314. if (replace) {
  114315. if (this.activeCamera) {
  114316. this.activeCamera.dispose();
  114317. this.activeCamera = null;
  114318. }
  114319. }
  114320. // Camera
  114321. if (!this.activeCamera) {
  114322. var worldExtends = this.getWorldExtends();
  114323. var worldSize = worldExtends.max.subtract(worldExtends.min);
  114324. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  114325. var camera;
  114326. var radius = worldSize.length() * 1.5;
  114327. // empty scene scenario!
  114328. if (!isFinite(radius)) {
  114329. radius = 1;
  114330. worldCenter.copyFromFloats(0, 0, 0);
  114331. }
  114332. if (createArcRotateCamera) {
  114333. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  114334. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  114335. arcRotateCamera.wheelPrecision = 100 / radius;
  114336. camera = arcRotateCamera;
  114337. }
  114338. else {
  114339. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  114340. freeCamera.setTarget(worldCenter);
  114341. camera = freeCamera;
  114342. }
  114343. camera.minZ = radius * 0.01;
  114344. camera.maxZ = radius * 1000;
  114345. camera.speed = radius * 0.2;
  114346. this.activeCamera = camera;
  114347. var canvas = this.getEngine().getRenderingCanvas();
  114348. if (attachCameraControls && canvas) {
  114349. camera.attachControl(canvas);
  114350. }
  114351. }
  114352. };
  114353. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  114354. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  114355. if (replace === void 0) { replace = false; }
  114356. if (attachCameraControls === void 0) { attachCameraControls = false; }
  114357. this.createDefaultLight(replace);
  114358. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  114359. };
  114360. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  114361. if (pbr === void 0) { pbr = false; }
  114362. if (scale === void 0) { scale = 1000; }
  114363. if (blur === void 0) { blur = 0; }
  114364. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  114365. if (!environmentTexture) {
  114366. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  114367. return null;
  114368. }
  114369. if (setGlobalEnvTexture) {
  114370. if (environmentTexture) {
  114371. this.environmentTexture = environmentTexture;
  114372. }
  114373. }
  114374. // Skybox
  114375. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  114376. if (pbr) {
  114377. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  114378. hdrSkyboxMaterial.backFaceCulling = false;
  114379. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  114380. if (hdrSkyboxMaterial.reflectionTexture) {
  114381. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114382. }
  114383. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  114384. hdrSkyboxMaterial.disableLighting = true;
  114385. hdrSkyboxMaterial.twoSidedLighting = true;
  114386. hdrSkybox.infiniteDistance = true;
  114387. hdrSkybox.material = hdrSkyboxMaterial;
  114388. }
  114389. else {
  114390. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  114391. skyboxMaterial.backFaceCulling = false;
  114392. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  114393. if (skyboxMaterial.reflectionTexture) {
  114394. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114395. }
  114396. skyboxMaterial.disableLighting = true;
  114397. hdrSkybox.infiniteDistance = true;
  114398. hdrSkybox.material = skyboxMaterial;
  114399. }
  114400. return hdrSkybox;
  114401. };
  114402. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  114403. if (BABYLON.EnvironmentHelper) {
  114404. return new BABYLON.EnvironmentHelper(options, this);
  114405. }
  114406. return null;
  114407. };
  114408. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  114409. if (webVROptions === void 0) { webVROptions = {}; }
  114410. return new BABYLON.VRExperienceHelper(this, webVROptions);
  114411. };
  114412. })(BABYLON || (BABYLON = {}));
  114413. //# sourceMappingURL=babylon.sceneHelpers.js.map
  114414. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  114415. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  114416. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  114417. globalObject["BABYLON"] = BABYLON;
  114418. //backwards compatibility
  114419. if(typeof earcut !== 'undefined') {
  114420. globalObject["Earcut"] = {
  114421. earcut: earcut
  114422. };
  114423. }
  114424. return BABYLON;
  114425. });